forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.cc
7462 lines (6898 loc) · 304 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-2022 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 <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <deque>
#include <functional>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#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/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 "ortools/base/int_type.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/strong_vector.h"
#include "ortools/base/thorough_hash.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_filters.h"
#include "ortools/constraint_solver/routing_index_manager.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/solver_parameters.pb.h"
#include "ortools/graph/connected_components.h"
#include "ortools/graph/ebert_graph.h"
#include "ortools/graph/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
// TODO(user): Move most of the following settings to a model parameter
// proto.
namespace operations_research {
namespace {
using ResourceGroup = RoutingModel::ResourceGroup;
// 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_t> targets)
: variables_(std::move(variables)),
targets_(std::move(targets)),
index_(0),
steps_(variables_.size(), 0) {
DCHECK_EQ(variables_.size(), targets_.size());
}
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_t variable_min = variables_[index]->Min();
const int64_t 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_t step = steps_[index];
int64_t 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_t GetNextStep(int64_t step) const {
return (step > 0) ? -step : CapSub(1, step);
}
const std::vector<IntVar*> variables_;
const std::vector<int64_t> targets_;
Rev<int> index_;
RevArray<int64_t> steps_;
};
} // namespace
DecisionBuilder* MakeSetValuesFromTargets(Solver* solver,
std::vector<IntVar*> variables,
std::vector<int64_t> 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;
}
// Concatenates cumul_values and break_values into 'values', and generates the
// corresponding 'variables' vector.
void ConcatenateRouteCumulAndBreakVarAndValues(
const RoutingDimension& dimension, int vehicle,
const std::vector<int64_t>& cumul_values,
const std::vector<int64_t>& break_values, std::vector<IntVar*>* variables,
std::vector<int64_t>* values) {
*values = cumul_values;
variables->clear();
const RoutingModel& model = *dimension.model();
{
int current = model.Start(vehicle);
while (true) {
variables->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(variables->at(1), variables->back());
std::swap(values->at(1), values->back());
if (dimension.HasBreakConstraints()) {
for (IntervalVar* interval :
dimension.GetBreakIntervalsOfVehicle(vehicle)) {
variables->push_back(interval->SafeStartExpr(0)->Var());
variables->push_back(interval->SafeEndExpr(0)->Var());
}
values->insert(values->end(), break_values.begin(), break_values.end());
}
// Value kint64min signals an unoptimized variable, set to min instead.
for (int j = 0; j < values->size(); ++j) {
if (values->at(j) == std::numeric_limits<int64_t>::min()) {
values->at(j) = variables->at(j)->Min();
}
}
DCHECK_EQ(variables->size(), values->size());
}
class SetCumulsFromLocalDimensionCosts : public DecisionBuilder {
public:
SetCumulsFromLocalDimensionCosts(
LocalDimensionCumulOptimizer* local_optimizer,
LocalDimensionCumulOptimizer* local_mp_optimizer, SearchMonitor* monitor,
bool optimize_and_pack = false)
: local_optimizer_(local_optimizer),
local_mp_optimizer_(local_mp_optimizer),
monitor_(monitor),
optimize_and_pack_(optimize_and_pack) {
const RoutingDimension* const dimension = local_optimizer->dimension();
const std::vector<int>& resource_groups =
dimension->model()->GetDimensionResourceGroupIndices(dimension);
DCHECK_LE(resource_groups.size(), optimize_and_pack ? 1 : 0);
resource_group_index_ = resource_groups.empty() ? -1 : resource_groups[0];
}
Decision* Next(Solver* const solver) override {
const RoutingDimension& dimension = *local_optimizer_->dimension();
RoutingModel* const model = dimension.model();
// 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 (int vehicle = 0; vehicle < model->vehicles(); ++vehicle) {
solver->TopPeriodicCheck();
// TODO(user): Investigate if we should skip unused vehicles.
DCHECK(DimensionFixedTransitsEqualTransitEvaluatorForVehicle(dimension,
vehicle));
const bool vehicle_has_break_constraint =
dimension.HasBreakConstraints() &&
!dimension.GetBreakIntervalsOfVehicle(vehicle).empty();
LocalDimensionCumulOptimizer* const optimizer =
vehicle_has_break_constraint ? local_mp_optimizer_ : local_optimizer_;
DCHECK(optimizer != nullptr);
std::vector<int64_t> cumul_values;
std::vector<int64_t> break_start_end_values;
const DimensionSchedulingStatus status =
ComputeCumulAndBreakValuesForVehicle(
optimizer, vehicle, &cumul_values, &break_start_end_values);
if (status == DimensionSchedulingStatus::INFEASIBLE) {
should_fail = true;
break;
}
// If relaxation is not feasible, try the MILP optimizer.
if (status == DimensionSchedulingStatus::RELAXED_OPTIMAL_ONLY) {
DCHECK(local_mp_optimizer_ != nullptr);
if (ComputeCumulAndBreakValuesForVehicle(local_mp_optimizer_, vehicle,
&cumul_values,
&break_start_end_values) ==
DimensionSchedulingStatus::INFEASIBLE) {
should_fail = true;
break;
}
} else {
DCHECK(status == DimensionSchedulingStatus::OPTIMAL);
}
// Concatenate cumul_values and break_start_end_values into cp_values,
// generate corresponding cp_variables vector.
std::vector<IntVar*> cp_variables;
std::vector<int64_t> cp_values;
ConcatenateRouteCumulAndBreakVarAndValues(
dimension, vehicle, cumul_values, break_start_end_values,
&cp_variables, &cp_values);
if (!solver->SolveAndCommit(
MakeSetValuesFromTargets(solver, std::move(cp_variables),
std::move(cp_values)),
monitor_)) {
should_fail = true;
break;
}
}
if (should_fail) {
solver->Fail();
}
return nullptr;
}
private:
using Resource = RoutingModel::ResourceGroup::Resource;
DimensionSchedulingStatus ComputeCumulAndBreakValuesForVehicle(
LocalDimensionCumulOptimizer* optimizer, int vehicle,
std::vector<int64_t>* cumul_values,
std::vector<int64_t>* break_start_end_values) {
cumul_values->clear();
break_start_end_values->clear();
RoutingModel* const model = optimizer->dimension()->model();
const auto next = [model](int64_t n) { return model->NextVar(n)->Value(); };
if (optimize_and_pack_) {
const int resource_index =
resource_group_index_ < 0
? -1
: model->ResourceVar(vehicle, resource_group_index_)->Value();
const Resource* const resource =
resource_index < 0 ? nullptr
: &model->GetResourceGroup(resource_group_index_)
->GetResource(resource_index);
return optimizer->ComputePackedRouteCumuls(
vehicle, next, resource, cumul_values, break_start_end_values);
} else {
// TODO(user): Add the resource to the call in this case too!
return optimizer->ComputeRouteCumuls(vehicle, next, cumul_values,
break_start_end_values);
}
}
LocalDimensionCumulOptimizer* const local_optimizer_;
LocalDimensionCumulOptimizer* const local_mp_optimizer_;
// Stores the resource group index of the local_[mp_]optimizer_'s dimension.
int resource_group_index_;
SearchMonitor* const monitor_;
const bool optimize_and_pack_;
};
class SetCumulsFromGlobalDimensionCosts : public DecisionBuilder {
public:
SetCumulsFromGlobalDimensionCosts(
GlobalDimensionCumulOptimizer* global_optimizer,
GlobalDimensionCumulOptimizer* global_mp_optimizer,
SearchMonitor* monitor, bool optimize_and_pack = false)
: global_optimizer_(global_optimizer),
global_mp_optimizer_(global_mp_optimizer),
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 scope, so there are
// no memory leaks related to the cumul_values vector.
bool should_fail = false;
{
const RoutingDimension* dimension = global_optimizer_->dimension();
DCHECK(DimensionFixedTransitsEqualTransitEvaluators(*dimension));
RoutingModel* const model = dimension->model();
GlobalDimensionCumulOptimizer* const optimizer =
model->GetDimensionResourceGroupIndices(dimension).empty()
? global_optimizer_
: global_mp_optimizer_;
std::vector<int64_t> cumul_values;
std::vector<int64_t> break_start_end_values;
std::vector<std::vector<int>> resource_indices_per_group;
const DimensionSchedulingStatus status =
ComputeCumulBreakAndResourceValues(optimizer, &cumul_values,
&break_start_end_values,
&resource_indices_per_group);
if (status == DimensionSchedulingStatus::INFEASIBLE) {
should_fail = true;
} else if (status == DimensionSchedulingStatus::RELAXED_OPTIMAL_ONLY) {
// If relaxation is not feasible, try the MILP optimizer.
const DimensionSchedulingStatus mp_status =
ComputeCumulBreakAndResourceValues(
global_mp_optimizer_, &cumul_values, &break_start_end_values,
&resource_indices_per_group);
if (mp_status != DimensionSchedulingStatus::OPTIMAL) {
should_fail = true;
}
} else {
DCHECK(status == DimensionSchedulingStatus::OPTIMAL);
}
if (!should_fail) {
// Concatenate cumul_values and break_start_end_values into cp_values,
// generate corresponding cp_variables vector.
std::vector<IntVar*> cp_variables = dimension->cumuls();
std::vector<int64_t> cp_values;
std::swap(cp_values, cumul_values);
if (dimension->HasBreakConstraints()) {
const int num_vehicles = model->vehicles();
for (int vehicle = 0; vehicle < num_vehicles; ++vehicle) {
for (IntervalVar* interval :
dimension->GetBreakIntervalsOfVehicle(vehicle)) {
cp_variables.push_back(interval->SafeStartExpr(0)->Var());
cp_variables.push_back(interval->SafeEndExpr(0)->Var());
}
}
cp_values.insert(cp_values.end(), break_start_end_values.begin(),
break_start_end_values.end());
}
for (int rg_index :
model->GetDimensionResourceGroupIndices(dimension)) {
const std::vector<int>& resource_values =
resource_indices_per_group[rg_index];
DCHECK(!resource_values.empty());
cp_values.insert(cp_values.end(), resource_values.begin(),
resource_values.end());
const std::vector<IntVar*>& resource_vars =
model->ResourceVars(rg_index);
DCHECK_EQ(resource_vars.size(), resource_values.size());
cp_variables.insert(cp_variables.end(), resource_vars.begin(),
resource_vars.end());
}
// Value kint64min signals an unoptimized variable, set to min instead.
for (int j = 0; j < cp_values.size(); ++j) {
if (cp_values[j] == std::numeric_limits<int64_t>::min()) {
cp_values[j] = cp_variables[j]->Min();
}
}
if (!solver->SolveAndCommit(
MakeSetValuesFromTargets(solver, std::move(cp_variables),
std::move(cp_values)),
monitor_)) {
should_fail = true;
}
}
}
if (should_fail) {
solver->Fail();
}
return nullptr;
}
private:
DimensionSchedulingStatus ComputeCumulBreakAndResourceValues(
GlobalDimensionCumulOptimizer* optimizer,
std::vector<int64_t>* cumul_values,
std::vector<int64_t>* break_start_end_values,
std::vector<std::vector<int>>* resource_indices_per_group) {
DCHECK_NE(optimizer, nullptr);
cumul_values->clear();
break_start_end_values->clear();
resource_indices_per_group->clear();
RoutingModel* const model = optimizer->dimension()->model();
const auto next = [model](int64_t n) { return model->NextVar(n)->Value(); };
return optimize_and_pack_
? optimizer->ComputePackedCumuls(next, cumul_values,
break_start_end_values,
resource_indices_per_group)
: optimizer->ComputeCumuls(next, cumul_values,
break_start_end_values,
resource_indices_per_group);
}
GlobalDimensionCumulOptimizer* const global_optimizer_;
GlobalDimensionCumulOptimizer* const global_mp_optimizer_;
SearchMonitor* const monitor_;
const bool optimize_and_pack_;
};
class SetCumulsFromResourceAssignmentCosts : public DecisionBuilder {
public:
SetCumulsFromResourceAssignmentCosts(
LocalDimensionCumulOptimizer* optimizer,
LocalDimensionCumulOptimizer* mp_optimizer, SearchMonitor* monitor)
: model_(*optimizer->dimension()->model()),
dimension_(*optimizer->dimension()),
rg_index_(model_.GetDimensionResourceGroupIndex(&dimension_)),
resource_group_(*model_.GetResourceGroup(rg_index_)),
resource_assignment_optimizer_(&resource_group_, optimizer,
mp_optimizer),
monitor_(monitor) {}
Decision* Next(Solver* const solver) override {
bool should_fail = false;
{
const int num_vehicles = model_.vehicles();
std::vector<std::vector<int64_t>> assignment_costs(num_vehicles);
std::vector<std::vector<std::vector<int64_t>>> cumul_values(num_vehicles);
std::vector<std::vector<std::vector<int64_t>>> break_values(num_vehicles);
const auto next = [&model = model_](int64_t n) {
return model.NextVar(n)->Value();
};
DCHECK(DimensionFixedTransitsEqualTransitEvaluators(dimension_));
for (int v : resource_group_.GetVehiclesRequiringAResource()) {
if (!resource_assignment_optimizer_.ComputeAssignmentCostsForVehicle(
v, next, dimension_.transit_evaluator(v),
/*optimize_vehicle_costs*/ true, &assignment_costs[v],
&cumul_values[v], &break_values[v])) {
should_fail = true;
break;
}
}
std::vector<int> resource_indices;
should_fail = should_fail ||
resource_assignment_optimizer_.ComputeBestAssignmentCost(
assignment_costs, assignment_costs,
[](int) { return true; }, &resource_indices) < 0;
if (!should_fail) {
DCHECK_EQ(resource_indices.size(), num_vehicles);
const int num_resources = resource_group_.Size();
for (int v : resource_group_.GetVehiclesRequiringAResource()) {
if (next(model_.Start(v)) == model_.End(v) &&
!model_.IsVehicleUsedWhenEmpty(v)) {
continue;
}
const int resource_index = resource_indices[v];
DCHECK_GE(resource_index, 0);
DCHECK_EQ(cumul_values[v].size(), num_resources);
DCHECK_EQ(break_values[v].size(), num_resources);
const std::vector<int64_t>& optimal_cumul_values =
cumul_values[v][resource_index];
const std::vector<int64_t>& optimal_break_values =
break_values[v][resource_index];
std::vector<IntVar*> cp_variables;
std::vector<int64_t> cp_values;
ConcatenateRouteCumulAndBreakVarAndValues(
dimension_, v, optimal_cumul_values, optimal_break_values,
&cp_variables, &cp_values);
const std::vector<IntVar*>& resource_vars =
model_.ResourceVars(rg_index_);
DCHECK_EQ(resource_vars.size(), resource_indices.size());
cp_variables.insert(cp_variables.end(), resource_vars.begin(),
resource_vars.end());
cp_values.insert(cp_values.end(), resource_indices.begin(),
resource_indices.end());
if (!solver->SolveAndCommit(
MakeSetValuesFromTargets(solver, std::move(cp_variables),
std::move(cp_values)),
monitor_)) {
should_fail = true;
break;
}
}
}
}
if (should_fail) {
solver->Fail();
}
return nullptr;
}
private:
const RoutingModel& model_;
const RoutingDimension& dimension_;
const int rg_index_;
const ResourceGroup& resource_group_;
ResourceAssignmentOptimizer resource_assignment_optimizer_;
SearchMonitor* const monitor_;
};
} // namespace
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());
// 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 for dimensions with a single resource group.
for (const RoutingDimension* const dimension : dimensions_) {
const std::vector<int>& resource_groups =
GetDimensionResourceGroupIndices(dimension);
if (resource_groups.size() == 1) {
DCHECK(HasLocalCumulOptimizer(*dimension));
packed_assignment->Add(resource_vars_[resource_groups[0]]);
}
}
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(
solver_->RevAlloc(new SetCumulsFromLocalDimensionCosts(
lp_optimizer.get(), mp_optimizer.get(),
GetOrCreateLargeNeighborhoodSearchLimit(),
/*optimize_and_pack=*/true)));
}
for (auto& [lp_optimizer, mp_optimizer] : global_dimension_optimizers_) {
decision_builders.push_back(
solver_->RevAlloc(new SetCumulsFromGlobalDimensionCosts(
lp_optimizer.get(), mp_optimizer.get(),
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,
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();
}
namespace {
// Constraint which ensures that var != values.
class DifferentFromValues : public Constraint {
public:
DifferentFromValues(Solver* solver, IntVar* var, std::vector<int64_t> 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_t> 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_t index1_min = index1_->Min();
const int64_t 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_t 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)));
}
// For each vehicle, computes information on the partially fixed start/end
// chains (based on bound NextVar values):
// - For every 'end_node', the last node of a start chain of a vehicle,
// vehicle_index_of_start_chain_end[end_node] contains the corresponding
// vehicle index. Contains -1 for other nodes.
// - For every vehicle 'v', end_chain_starts[v] contains the first node of the
// end chain of that vehicle.
void ComputeVehicleChainStartEndInfo(
const RoutingModel& model, std::vector<int64_t>* end_chain_starts,
std::vector<int>* vehicle_index_of_start_chain_end) {
vehicle_index_of_start_chain_end->resize(model.Size() + model.vehicles(), -1);
for (int vehicle = 0; vehicle < model.vehicles(); ++vehicle) {
int64_t node = model.Start(vehicle);
while (!model.IsEnd(node) && model.NextVar(node)->Bound()) {
node = model.NextVar(node)->Value();
}
vehicle_index_of_start_chain_end->at(node) = vehicle;
}
*end_chain_starts = ComputeVehicleEndChainStarts(model);
}
class ResourceAssignmentConstraint : public Constraint {
public:
ResourceAssignmentConstraint(
const ResourceGroup* resource_group,
const std::vector<IntVar*>* vehicle_resource_vars, RoutingModel* model)
: Constraint(model->solver()),
model_(*model),
resource_group_(*resource_group),
vehicle_resource_vars_(*vehicle_resource_vars),
vehicle_to_start_bound_vars_per_dimension_(model->vehicles()),
vehicle_to_end_bound_vars_per_dimension_(model->vehicles()) {
DCHECK_EQ(vehicle_resource_vars_.size(), model_.vehicles());
const std::vector<RoutingDimension*>& dimensions = model_.GetDimensions();
for (int v = 0; v < model_.vehicles(); v++) {
IntVar* const resource_var = vehicle_resource_vars_[v];
model->AddToAssignment(resource_var);
// The resource variable must be fixed by the search.
model->AddVariableTargetToFinalizer(resource_var, -1);
if (!resource_group_.VehicleRequiresAResource(v)) {
continue;
}
vehicle_to_start_bound_vars_per_dimension_[v].resize(dimensions.size());
vehicle_to_end_bound_vars_per_dimension_[v].resize(dimensions.size());
for (const RoutingModel::DimensionIndex d :
resource_group_.GetAffectedDimensionIndices()) {
const RoutingDimension* const dim = dimensions[d.value()];
// The vehicle's start/end cumuls must be fixed by the search.
model->AddVariableMinimizedByFinalizer(dim->CumulVar(model_.End(v)));
model->AddVariableMaximizedByFinalizer(dim->CumulVar(model_.Start(v)));
for (ResourceBoundVars* bound_vars :
{&vehicle_to_start_bound_vars_per_dimension_[v][d.value()],
&vehicle_to_end_bound_vars_per_dimension_[v][d.value()]}) {
bound_vars->lower_bound =
solver()->MakeIntVar(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max());
bound_vars->upper_bound =
solver()->MakeIntVar(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max());
}
}
}
}
void Post() override {}
void InitialPropagate() override {
if (!AllResourceAssignmentsFeasible()) {
solver()->Fail();
}
SetupResourceConstraints();
}
private:
bool AllResourceAssignmentsFeasible() {
DCHECK(!model_.GetResourceGroups().empty());
std::vector<int64_t> end_chain_starts;
std::vector<int> vehicle_index_of_start_chain_end;
ComputeVehicleChainStartEndInfo(model_, &end_chain_starts,
&vehicle_index_of_start_chain_end);
const auto next = [&model = model_, &end_chain_starts,
&vehicle_index_of_start_chain_end](int64_t node) {
if (model.NextVar(node)->Bound()) return model.NextVar(node)->Value();
const int vehicle = vehicle_index_of_start_chain_end[node];
if (vehicle < 0) {
// The node isn't the last node of a route start chain and is considered
// as unperformed and ignored when evaluating the feasibility of the
// resource assignment.
return node;
}
return end_chain_starts[vehicle];
};
const std::vector<RoutingDimension*>& dimensions = model_.GetDimensions();
for (RoutingModel::DimensionIndex d :
resource_group_.GetAffectedDimensionIndices()) {
if (!ResourceAssignmentFeasibleForDimension(*dimensions[d.value()],
next)) {
return false;
}
}
return true;
}
bool ResourceAssignmentFeasibleForDimension(
const RoutingDimension& dimension,
const std::function<int64_t(int64_t)>& next) {
LocalDimensionCumulOptimizer* const optimizer =
model_.GetMutableLocalCumulLPOptimizer(dimension);
if (optimizer == nullptr) return true;
LocalDimensionCumulOptimizer* const mp_optimizer =
model_.GetMutableLocalCumulMPOptimizer(dimension);
DCHECK_NE(mp_optimizer, nullptr);
ResourceAssignmentOptimizer resource_assignment_optimizer(
&resource_group_, optimizer, mp_optimizer);
const auto transit = [&dimension](int64_t node, int64_t /*next*/) {
// TODO(user): Get rid of this max() by only allowing resources on
// dimensions with positive transits (model.AreVehicleTransitsPositive()).
// TODO(user): The transit lower bounds have not necessarily been
// propagated at this point. Add demons to check the resource assignment
// feasibility after the transit ranges have been propagated.
return std::max<int64_t>(dimension.FixedTransitVar(node)->Min(), 0);
};
std::vector<std::vector<int64_t>> assignment_costs(model_.vehicles());
for (int v : resource_group_.GetVehiclesRequiringAResource()) {
if (!resource_assignment_optimizer.ComputeAssignmentCostsForVehicle(
v, next, transit, /*optimize_vehicle_costs*/ false,
&assignment_costs[v], nullptr, nullptr)) {
return false;
}
}
return resource_assignment_optimizer.ComputeBestAssignmentCost(
assignment_costs, assignment_costs, [](int) { return true; },
nullptr) >= 0;
}
void SetupResourceConstraints() {