forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing_lp_scheduling.cc
3317 lines (3075 loc) · 143 KB
/
routing_lp_scheduling.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_lp_scheduling.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <numeric>
#include <string>
#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/log/check.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/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/strong_vector.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_parameters.pb.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/graph/ebert_graph.h"
#include "ortools/graph/min_cost_flow.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/lp_utils.h"
#include "ortools/util/flat_matrix.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace {
// The following sets of parameters give the fastest response time without
// impacting solutions found negatively.
glop::GlopParameters GetGlopParametersForLocalLP() {
glop::GlopParameters parameters;
parameters.set_use_dual_simplex(true);
parameters.set_use_preprocessing(false);
return parameters;
}
glop::GlopParameters GetGlopParametersForGlobalLP() {
glop::GlopParameters parameters;
parameters.set_use_dual_simplex(true);
return parameters;
}
bool GetCumulBoundsWithOffset(const RoutingDimension& dimension,
int64_t node_index, int64_t cumul_offset,
int64_t* lower_bound, int64_t* upper_bound) {
DCHECK(lower_bound != nullptr);
DCHECK(upper_bound != nullptr);
const IntVar& cumul_var = *dimension.CumulVar(node_index);
*upper_bound = cumul_var.Max();
if (*upper_bound < cumul_offset) {
return false;
}
const int64_t first_after_offset =
std::max(dimension.GetFirstPossibleGreaterOrEqualValueForNode(
node_index, cumul_offset),
cumul_var.Min());
DCHECK_LT(first_after_offset, std::numeric_limits<int64_t>::max());
*lower_bound = CapSub(first_after_offset, cumul_offset);
DCHECK_GE(*lower_bound, 0);
if (*upper_bound == std::numeric_limits<int64_t>::max()) {
return true;
}
*upper_bound = CapSub(*upper_bound, cumul_offset);
DCHECK_GE(*upper_bound, *lower_bound);
return true;
}
int64_t GetFirstPossibleValueForCumulWithOffset(
const RoutingDimension& dimension, int64_t node_index,
int64_t lower_bound_without_offset, int64_t cumul_offset) {
return CapSub(
dimension.GetFirstPossibleGreaterOrEqualValueForNode(
node_index, CapAdd(lower_bound_without_offset, cumul_offset)),
cumul_offset);
}
int64_t GetLastPossibleValueForCumulWithOffset(
const RoutingDimension& dimension, int64_t node_index,
int64_t upper_bound_without_offset, int64_t cumul_offset) {
return CapSub(
dimension.GetLastPossibleLessOrEqualValueForNode(
node_index, CapAdd(upper_bound_without_offset, cumul_offset)),
cumul_offset);
}
// Finds the pickup/delivery pairs of nodes on a given vehicle's route.
// Returns the vector of visited pair indices, and stores the corresponding
// pickup/delivery indices in visited_pickup_delivery_indices_for_pair_.
// NOTE: Supposes that visited_pickup_delivery_indices_for_pair is correctly
// sized and initialized to {-1, -1} for all pairs.
void StoreVisitedPickupDeliveryPairsOnRoute(
const RoutingDimension& dimension, int vehicle,
const std::function<int64_t(int64_t)>& next_accessor,
std::vector<int>* visited_pairs,
std::vector<std::pair<int64_t, int64_t>>*
visited_pickup_delivery_indices_for_pair) {
// visited_pickup_delivery_indices_for_pair must be all {-1, -1}.
DCHECK_EQ(visited_pickup_delivery_indices_for_pair->size(),
dimension.model()->GetPickupAndDeliveryPairs().size());
DCHECK(std::all_of(visited_pickup_delivery_indices_for_pair->begin(),
visited_pickup_delivery_indices_for_pair->end(),
[](std::pair<int64_t, int64_t> p) {
return p.first == -1 && p.second == -1;
}));
visited_pairs->clear();
if (!dimension.HasPickupToDeliveryLimits()) {
return;
}
const RoutingModel& model = *dimension.model();
int64_t node_index = model.Start(vehicle);
while (!model.IsEnd(node_index)) {
const std::vector<RoutingModel::PickupDeliveryPosition>& pickup_positions =
model.GetPickupPositions(node_index);
const std::vector<RoutingModel::PickupDeliveryPosition>&
delivery_positions = model.GetDeliveryPositions(node_index);
if (!pickup_positions.empty()) {
// The current node is a pickup. We verify that it belongs to a single
// pickup index pair and that it's not a delivery, and store the index.
DCHECK(delivery_positions.empty());
DCHECK_EQ(pickup_positions.size(), 1);
const int pair_index = pickup_positions[0].pd_pair_index;
(*visited_pickup_delivery_indices_for_pair)[pair_index].first =
node_index;
visited_pairs->push_back(pair_index);
} else if (!delivery_positions.empty()) {
// The node is a delivery. We verify that it belongs to a single
// delivery pair, and set the limit with its pickup if one has been
// visited for this pair.
DCHECK_EQ(delivery_positions.size(), 1);
const int pair_index = delivery_positions[0].pd_pair_index;
std::pair<int64_t, int64_t>& pickup_delivery_index =
(*visited_pickup_delivery_indices_for_pair)[pair_index];
if (pickup_delivery_index.first < 0) {
// This case should not happen, as a delivery must have its pickup
// on the route, but we ignore it here.
node_index = next_accessor(node_index);
continue;
}
pickup_delivery_index.second = node_index;
}
node_index = next_accessor(node_index);
}
}
} // namespace
// LocalDimensionCumulOptimizer
LocalDimensionCumulOptimizer::LocalDimensionCumulOptimizer(
const RoutingDimension* dimension,
RoutingSearchParameters::SchedulingSolver solver_type)
: optimizer_core_(dimension, /*use_precedence_propagator=*/false) {
// Using one solver per vehicle in the hope that if routes don't change this
// will be faster.
const int vehicles = dimension->model()->vehicles();
solver_.resize(vehicles);
switch (solver_type) {
case RoutingSearchParameters::SCHEDULING_GLOP: {
const glop::GlopParameters parameters = GetGlopParametersForLocalLP();
for (int vehicle = 0; vehicle < vehicles; ++vehicle) {
// TODO(user): Instead of passing false, detect if the relaxation
// will always violate the MIPL constraints.
solver_[vehicle] =
std::make_unique<RoutingGlopWrapper>(false, parameters);
}
break;
}
case RoutingSearchParameters::SCHEDULING_CP_SAT: {
for (int vehicle = 0; vehicle < vehicles; ++vehicle) {
solver_[vehicle] = std::make_unique<RoutingCPSatWrapper>();
}
break;
}
default:
LOG(DFATAL) << "Unrecognized solver type: " << solver_type;
}
}
DimensionSchedulingStatus LocalDimensionCumulOptimizer::ComputeRouteCumulCost(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
int64_t* optimal_cost) {
int64_t transit_cost = 0;
const DimensionSchedulingStatus status =
optimizer_core_.OptimizeSingleRouteWithResource(
vehicle, next_accessor,
/*dimension_travel_info=*/{},
/*resource=*/nullptr,
/*optimize_vehicle_costs=*/optimal_cost != nullptr,
solver_[vehicle].get(), /*cumul_values=*/nullptr,
/*break_values=*/nullptr, optimal_cost, &transit_cost);
if (status != DimensionSchedulingStatus::INFEASIBLE &&
optimal_cost != nullptr) {
DCHECK_GE(*optimal_cost, 0);
*optimal_cost = CapAdd(*optimal_cost, transit_cost);
}
return status;
}
DimensionSchedulingStatus
LocalDimensionCumulOptimizer::ComputeRouteCumulCostWithoutFixedTransits(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
int64_t* optimal_cost_without_transits) {
return optimizer_core_.OptimizeSingleRouteWithResource(
vehicle, next_accessor,
/*dimension_travel_info=*/{},
/*resource=*/nullptr,
/*optimize_vehicle_costs=*/optimal_cost_without_transits != nullptr,
solver_[vehicle].get(), /*cumul_values=*/nullptr,
/*break_values=*/nullptr, optimal_cost_without_transits, nullptr);
}
std::vector<DimensionSchedulingStatus> LocalDimensionCumulOptimizer::
ComputeRouteCumulCostsForResourcesWithoutFixedTransits(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
const std::vector<RoutingModel::ResourceGroup::Resource>& resources,
const std::vector<int>& resource_indices, bool optimize_vehicle_costs,
std::vector<int64_t>* optimal_costs_without_transits,
std::vector<std::vector<int64_t>>* optimal_cumuls,
std::vector<std::vector<int64_t>>* optimal_breaks) {
return optimizer_core_.OptimizeSingleRouteWithResources(
vehicle, next_accessor, transit_accessor, {}, resources, resource_indices,
optimize_vehicle_costs, solver_[vehicle].get(), optimal_cumuls,
optimal_breaks, optimal_costs_without_transits, nullptr);
}
DimensionSchedulingStatus LocalDimensionCumulOptimizer::ComputeRouteCumuls(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RoutingModel::RouteDimensionTravelInfo& dimension_travel_info,
const RoutingModel::ResourceGroup::Resource* resource,
std::vector<int64_t>* optimal_cumuls,
std::vector<int64_t>* optimal_breaks) {
return optimizer_core_.OptimizeSingleRouteWithResource(
vehicle, next_accessor, dimension_travel_info, resource,
/*optimize_vehicle_costs=*/true, solver_[vehicle].get(), optimal_cumuls,
optimal_breaks, /*cost=*/nullptr, /*transit_cost=*/nullptr);
}
DimensionSchedulingStatus
LocalDimensionCumulOptimizer::ComputeRouteCumulsAndCostWithoutFixedTransits(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RoutingModel::RouteDimensionTravelInfo& dimension_travel_info,
std::vector<int64_t>* optimal_cumuls, std::vector<int64_t>* optimal_breaks,
int64_t* optimal_cost_without_transits) {
return optimizer_core_.OptimizeSingleRouteWithResource(
vehicle, next_accessor, dimension_travel_info, nullptr,
/*optimize_vehicle_costs=*/true, solver_[vehicle].get(), optimal_cumuls,
optimal_breaks, optimal_cost_without_transits, nullptr);
}
DimensionSchedulingStatus
LocalDimensionCumulOptimizer::ComputeRouteSolutionCostWithoutFixedTransits(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RoutingModel::RouteDimensionTravelInfo& dimension_travel_info,
const std::vector<int64_t>& solution_cumul_values,
const std::vector<int64_t>& solution_break_values, int64_t* solution_cost,
int64_t* cost_offset, bool reuse_previous_model_if_possible, bool clear_lp,
absl::Duration* solve_duration) {
RoutingLinearSolverWrapper* solver = solver_[vehicle].get();
return optimizer_core_.ComputeSingleRouteSolutionCostWithoutFixedTransits(
vehicle, next_accessor, dimension_travel_info, solver,
solution_cumul_values, solution_break_values, solution_cost, cost_offset,
reuse_previous_model_if_possible, clear_lp,
/*clear_solution_constraints=*/true, solve_duration);
}
DimensionSchedulingStatus
LocalDimensionCumulOptimizer::ComputePackedRouteCumuls(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RoutingModel::RouteDimensionTravelInfo& dimension_travel_info,
const RoutingModel::ResourceGroup::Resource* resource,
std::vector<int64_t>* packed_cumuls, std::vector<int64_t>* packed_breaks) {
return optimizer_core_.OptimizeAndPackSingleRoute(
vehicle, next_accessor, dimension_travel_info, resource,
solver_[vehicle].get(), packed_cumuls, packed_breaks);
}
const int CumulBoundsPropagator::kNoParent = -2;
const int CumulBoundsPropagator::kParentToBePropagated = -1;
CumulBoundsPropagator::CumulBoundsPropagator(const RoutingDimension* dimension)
: dimension_(*dimension), num_nodes_(2 * dimension->cumuls().size()) {
outgoing_arcs_.resize(num_nodes_);
node_in_queue_.resize(num_nodes_, false);
tree_parent_node_of_.resize(num_nodes_, kNoParent);
propagated_bounds_.resize(num_nodes_);
visited_pickup_delivery_indices_for_pair_.resize(
dimension->model()->GetPickupAndDeliveryPairs().size(), {-1, -1});
}
void CumulBoundsPropagator::AddArcs(int first_index, int second_index,
int64_t offset) {
// Add arc first_index + offset <= second_index
outgoing_arcs_[PositiveNode(first_index)].push_back(
{PositiveNode(second_index), offset});
AddNodeToQueue(PositiveNode(first_index));
// Add arc -second_index + transit <= -first_index
outgoing_arcs_[NegativeNode(second_index)].push_back(
{NegativeNode(first_index), offset});
AddNodeToQueue(NegativeNode(second_index));
}
bool CumulBoundsPropagator::InitializeArcsAndBounds(
const std::function<int64_t(int64_t)>& next_accessor, int64_t cumul_offset,
const std::vector<RoutingModel::RouteDimensionTravelInfo>*
dimension_travel_info_per_route) {
propagated_bounds_.assign(num_nodes_, std::numeric_limits<int64_t>::min());
for (std::vector<ArcInfo>& arcs : outgoing_arcs_) {
arcs.clear();
}
RoutingModel* const model = dimension_.model();
std::vector<int64_t>& lower_bounds = propagated_bounds_;
for (int vehicle = 0; vehicle < model->vehicles(); vehicle++) {
const std::function<int64_t(int64_t, int64_t)>& transit_accessor =
dimension_.transit_evaluator(vehicle);
int node = model->Start(vehicle);
int index_on_route = 0;
while (true) {
int64_t cumul_lb, cumul_ub;
if (!GetCumulBoundsWithOffset(dimension_, node, cumul_offset, &cumul_lb,
&cumul_ub)) {
return false;
}
lower_bounds[PositiveNode(node)] = cumul_lb;
if (cumul_ub < std::numeric_limits<int64_t>::max()) {
lower_bounds[NegativeNode(node)] = -cumul_ub;
}
if (model->IsEnd(node)) {
break;
}
const int next = next_accessor(node);
int64_t transit = transit_accessor(node, next);
if (dimension_travel_info_per_route != nullptr &&
!dimension_travel_info_per_route->empty()) {
const RoutingModel::RouteDimensionTravelInfo::TransitionInfo&
transition_info = (*dimension_travel_info_per_route)[vehicle]
.transition_info[index_on_route];
transit = transition_info.compressed_travel_value_lower_bound +
transition_info.pre_travel_transit_value +
transition_info.post_travel_transit_value;
++index_on_route;
}
const IntVar& slack_var = *dimension_.SlackVar(node);
// node + transit + slack_var == next
// Add arcs for node + transit + slack_min <= next
AddArcs(node, next, CapAdd(transit, slack_var.Min()));
if (slack_var.Max() < std::numeric_limits<int64_t>::max()) {
// Add arcs for node + transit + slack_max >= next.
AddArcs(next, node, CapSub(-slack_var.Max(), transit));
}
node = next;
}
// Add vehicle span upper bound: end - span_ub <= start.
const int64_t span_ub = dimension_.GetSpanUpperBoundForVehicle(vehicle);
if (span_ub < std::numeric_limits<int64_t>::max()) {
AddArcs(model->End(vehicle), model->Start(vehicle), -span_ub);
}
// Set pickup/delivery limits on route.
std::vector<int> visited_pairs;
StoreVisitedPickupDeliveryPairsOnRoute(
dimension_, vehicle, next_accessor, &visited_pairs,
&visited_pickup_delivery_indices_for_pair_);
for (int pair_index : visited_pairs) {
const int64_t pickup_index =
visited_pickup_delivery_indices_for_pair_[pair_index].first;
const int64_t delivery_index =
visited_pickup_delivery_indices_for_pair_[pair_index].second;
visited_pickup_delivery_indices_for_pair_[pair_index] = {-1, -1};
DCHECK_GE(pickup_index, 0);
if (delivery_index < 0) {
// We didn't encounter a delivery for this pickup.
continue;
}
const int64_t limit = dimension_.GetPickupToDeliveryLimitForPair(
pair_index,
model->GetPickupPositions(pickup_index)[0].alternative_index,
model->GetDeliveryPositions(delivery_index)[0].alternative_index);
if (limit < std::numeric_limits<int64_t>::max()) {
// delivery_cumul - limit <= pickup_cumul.
AddArcs(delivery_index, pickup_index, -limit);
}
}
}
for (const RoutingDimension::NodePrecedence& precedence :
dimension_.GetNodePrecedences()) {
const int first_index = precedence.first_node;
const int second_index = precedence.second_node;
if (lower_bounds[PositiveNode(first_index)] ==
std::numeric_limits<int64_t>::min() ||
lower_bounds[PositiveNode(second_index)] ==
std::numeric_limits<int64_t>::min()) {
// One of the nodes is unperformed, so the precedence rule doesn't apply.
continue;
}
AddArcs(first_index, second_index, precedence.offset);
}
return true;
}
bool CumulBoundsPropagator::UpdateCurrentLowerBoundOfNode(int node,
int64_t new_lb,
int64_t offset) {
const int cumul_var_index = node / 2;
if (node == PositiveNode(cumul_var_index)) {
// new_lb is a lower bound of the cumul of variable 'cumul_var_index'.
propagated_bounds_[node] = GetFirstPossibleValueForCumulWithOffset(
dimension_, cumul_var_index, new_lb, offset);
} else {
// -new_lb is an upper bound of the cumul of variable 'cumul_var_index'.
const int64_t new_ub = CapSub(0, new_lb);
propagated_bounds_[node] =
CapSub(0, GetLastPossibleValueForCumulWithOffset(
dimension_, cumul_var_index, new_ub, offset));
}
// Test that the lower/upper bounds do not cross each other.
const int64_t cumul_lower_bound =
propagated_bounds_[PositiveNode(cumul_var_index)];
const int64_t negated_cumul_upper_bound =
propagated_bounds_[NegativeNode(cumul_var_index)];
return CapAdd(negated_cumul_upper_bound, cumul_lower_bound) <= 0;
}
bool CumulBoundsPropagator::DisassembleSubtree(int source, int target) {
tmp_dfs_stack_.clear();
tmp_dfs_stack_.push_back(source);
while (!tmp_dfs_stack_.empty()) {
const int tail = tmp_dfs_stack_.back();
tmp_dfs_stack_.pop_back();
for (const ArcInfo& arc : outgoing_arcs_[tail]) {
const int child_node = arc.head;
if (tree_parent_node_of_[child_node] != tail) continue;
if (child_node == target) return false;
tree_parent_node_of_[child_node] = kParentToBePropagated;
tmp_dfs_stack_.push_back(child_node);
}
}
return true;
}
bool CumulBoundsPropagator::PropagateCumulBounds(
const std::function<int64_t(int64_t)>& next_accessor, int64_t cumul_offset,
const std::vector<RoutingModel::RouteDimensionTravelInfo>*
dimension_travel_info_per_route) {
tree_parent_node_of_.assign(num_nodes_, kNoParent);
DCHECK(std::none_of(node_in_queue_.begin(), node_in_queue_.end(),
[](bool b) { return b; }));
DCHECK(bf_queue_.empty());
if (!InitializeArcsAndBounds(next_accessor, cumul_offset,
dimension_travel_info_per_route)) {
return CleanupAndReturnFalse();
}
std::vector<int64_t>& current_lb = propagated_bounds_;
// Bellman-Ford-Tarjan algorithm.
while (!bf_queue_.empty()) {
const int node = bf_queue_.front();
bf_queue_.pop_front();
node_in_queue_[node] = false;
if (tree_parent_node_of_[node] == kParentToBePropagated) {
// The parent of this node is still in the queue, so no need to process
// node now, since it will be re-enqueued when its parent is processed.
continue;
}
const int64_t lower_bound = current_lb[node];
for (const ArcInfo& arc : outgoing_arcs_[node]) {
// NOTE: kint64min as a lower bound means no lower bound at all, so we
// don't use this value to propagate.
const int64_t induced_lb =
(lower_bound == std::numeric_limits<int64_t>::min())
? std::numeric_limits<int64_t>::min()
: CapAdd(lower_bound, arc.offset);
const int head_node = arc.head;
if (induced_lb <= current_lb[head_node]) {
// No update necessary for the head_node, continue to next children of
// node.
continue;
}
if (!UpdateCurrentLowerBoundOfNode(head_node, induced_lb, cumul_offset) ||
!DisassembleSubtree(head_node, node)) {
// The new lower bound is infeasible, or a positive cycle was detected
// in the precedence graph by DisassembleSubtree().
return CleanupAndReturnFalse();
}
tree_parent_node_of_[head_node] = node;
AddNodeToQueue(head_node);
}
}
return true;
}
DimensionCumulOptimizerCore::DimensionCumulOptimizerCore(
const RoutingDimension* dimension, bool use_precedence_propagator)
: dimension_(dimension),
visited_pickup_delivery_indices_for_pair_(
dimension->model()->GetPickupAndDeliveryPairs().size(), {-1, -1}) {
if (use_precedence_propagator) {
propagator_ = std::make_unique<CumulBoundsPropagator>(dimension);
}
const RoutingModel& model = *dimension_->model();
if (dimension_->HasBreakConstraints()) {
// Initialize vehicle_to_first_index_ so the variables of the breaks of
// vehicle v are stored from vehicle_to_first_index_[v] to
// vehicle_to_first_index_[v+1] - 1.
const int num_vehicles = model.vehicles();
vehicle_to_all_break_variables_offset_.reserve(num_vehicles);
int num_break_vars = 0;
for (int vehicle = 0; vehicle < num_vehicles; ++vehicle) {
vehicle_to_all_break_variables_offset_.push_back(num_break_vars);
const auto& intervals = dimension_->GetBreakIntervalsOfVehicle(vehicle);
num_break_vars += 2 * intervals.size(); // 2 variables per break.
}
all_break_variables_.resize(num_break_vars, -1);
}
if (!model.GetDimensionResourceGroupIndices(dimension_).empty()) {
resource_group_to_resource_to_vehicle_assignment_variables_.resize(
model.GetResourceGroups().size());
}
}
DimensionSchedulingStatus
DimensionCumulOptimizerCore::ComputeSingleRouteSolutionCostWithoutFixedTransits(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RouteDimensionTravelInfo& dimension_travel_info,
RoutingLinearSolverWrapper* solver,
absl::Span<const int64_t> solution_cumul_values,
absl::Span<const int64_t> solution_break_values,
int64_t* cost_without_transits, int64_t* cost_offset,
bool reuse_previous_model_if_possible, bool clear_lp,
bool clear_solution_constraints, absl::Duration* const solve_duration) {
absl::Duration solve_duration_value;
int64_t cost_offset_value;
if (!reuse_previous_model_if_possible || solver->ModelIsEmpty()) {
InitOptimizer(solver);
// Make sure SetRouteCumulConstraints will properly set the cumul bounds by
// looking at this route only.
DCHECK_EQ(propagator_.get(), nullptr);
RoutingModel* const model = dimension_->model();
const bool optimize_vehicle_costs =
!model->IsEnd(next_accessor(model->Start(vehicle))) ||
model->IsVehicleUsedWhenEmpty(vehicle);
if (!SetRouteCumulConstraints(
vehicle, next_accessor, dimension_->transit_evaluator(vehicle),
dimension_travel_info,
dimension_->GetLocalOptimizerOffsetForVehicle(vehicle),
optimize_vehicle_costs, solver, nullptr, &cost_offset_value)) {
return DimensionSchedulingStatus::INFEASIBLE;
}
if (model->CheckLimit()) {
return DimensionSchedulingStatus::INFEASIBLE;
}
solve_duration_value = model->RemainingTime();
if (solve_duration != nullptr) *solve_duration = solve_duration_value;
if (cost_offset != nullptr) *cost_offset = cost_offset_value;
} else {
CHECK(cost_offset != nullptr)
<< "Cannot reuse model without the cost_offset";
cost_offset_value = *cost_offset;
CHECK(solve_duration != nullptr)
<< "Cannot reuse model without the solve_duration";
solve_duration_value = *solve_duration;
}
// Constrains the cumuls.
DCHECK_EQ(solution_cumul_values.size(),
current_route_cumul_variables_.size());
for (int i = 0; i < current_route_cumul_variables_.size(); ++i) {
if (solution_cumul_values[i] < current_route_min_cumuls_[i] ||
solution_cumul_values[i] > current_route_max_cumuls_[i]) {
return DimensionSchedulingStatus::INFEASIBLE;
}
solver->SetVariableBounds(current_route_cumul_variables_[i],
/*lower_bound=*/solution_cumul_values[i],
/*upper_bound=*/solution_cumul_values[i]);
}
// Constrains the breaks.
DCHECK_EQ(solution_break_values.size(),
current_route_break_variables_.size());
std::vector<int64_t> current_route_min_breaks(
current_route_break_variables_.size());
std::vector<int64_t> current_route_max_breaks(
current_route_break_variables_.size());
for (int i = 0; i < current_route_break_variables_.size(); ++i) {
current_route_min_breaks[i] =
solver->GetVariableLowerBound(current_route_break_variables_[i]);
current_route_max_breaks[i] =
solver->GetVariableUpperBound(current_route_break_variables_[i]);
solver->SetVariableBounds(current_route_break_variables_[i],
/*lower_bound=*/solution_break_values[i],
/*upper_bound=*/solution_break_values[i]);
}
const DimensionSchedulingStatus status = solver->Solve(solve_duration_value);
if (status == DimensionSchedulingStatus::INFEASIBLE) {
solver->Clear();
return status;
}
if (cost_without_transits != nullptr) {
*cost_without_transits =
CapAdd(cost_offset_value, solver->GetObjectiveValue());
}
if (clear_lp) {
solver->Clear();
} else if (clear_solution_constraints) {
for (int i = 0; i < current_route_cumul_variables_.size(); ++i) {
solver->SetVariableBounds(current_route_cumul_variables_[i],
/*lower_bound=*/current_route_min_cumuls_[i],
/*upper_bound=*/current_route_max_cumuls_[i]);
}
for (int i = 0; i < current_route_break_variables_.size(); ++i) {
solver->SetVariableBounds(current_route_break_variables_[i],
/*lower_bound=*/current_route_min_breaks[i],
/*upper_bound=*/current_route_max_breaks[i]);
}
}
return status;
}
namespace {
template <typename T>
void ClearIfNonNull(std::vector<T>* v) {
if (v != nullptr) {
v->clear();
}
}
} // namespace
DimensionSchedulingStatus
DimensionCumulOptimizerCore::OptimizeSingleRouteWithResource(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const RouteDimensionTravelInfo& dimension_travel_info,
const RoutingModel::ResourceGroup::Resource* resource,
bool optimize_vehicle_costs, RoutingLinearSolverWrapper* solver,
std::vector<int64_t>* cumul_values, std::vector<int64_t>* break_values,
int64_t* cost_without_transits, int64_t* transit_cost, bool clear_lp) {
if (cost_without_transits != nullptr) *cost_without_transits = -1;
ClearIfNonNull(cumul_values);
ClearIfNonNull(break_values);
const std::vector<Resource> resources =
resource == nullptr ? std::vector<Resource>()
: std::vector<Resource>({*resource});
const std::vector<int> resource_indices =
resource == nullptr ? std::vector<int>() : std::vector<int>({0});
std::vector<int64_t> costs_without_transits;
std::vector<std::vector<int64_t>> cumul_values_vec;
std::vector<std::vector<int64_t>> break_values_vec;
const std::vector<DimensionSchedulingStatus> statuses =
DimensionCumulOptimizerCore::OptimizeSingleRouteWithResources(
vehicle, next_accessor, dimension_->transit_evaluator(vehicle),
dimension_travel_info, resources, resource_indices,
optimize_vehicle_costs, solver,
cumul_values != nullptr ? &cumul_values_vec : nullptr,
break_values != nullptr ? &break_values_vec : nullptr,
cost_without_transits != nullptr ? &costs_without_transits : nullptr,
transit_cost, clear_lp);
if (dimension()->model()->CheckLimit()) {
return DimensionSchedulingStatus::INFEASIBLE;
}
DCHECK_EQ(statuses.size(), 1);
const DimensionSchedulingStatus status = statuses[0];
if (status == DimensionSchedulingStatus::INFEASIBLE) return status;
if (cost_without_transits != nullptr) {
*cost_without_transits = costs_without_transits[0];
}
if (cumul_values != nullptr) *cumul_values = std::move(cumul_values_vec[0]);
if (break_values != nullptr) *break_values = std::move(break_values_vec[0]);
return status;
}
namespace {
using ResourceGroup = RoutingModel::ResourceGroup;
bool GetDomainOffsetBounds(const Domain& domain, int64_t offset,
ClosedInterval* interval) {
const int64_t lower_bound =
std::max<int64_t>(CapSub(domain.Min(), offset), 0);
const int64_t upper_bound =
domain.Max() == std::numeric_limits<int64_t>::max()
? std::numeric_limits<int64_t>::max()
: CapSub(domain.Max(), offset);
if (lower_bound > upper_bound) return false;
*interval = ClosedInterval(lower_bound, upper_bound);
return true;
}
bool GetIntervalIntersectionWithOffsetDomain(const ClosedInterval& interval,
const Domain& domain,
int64_t offset,
ClosedInterval* intersection) {
ClosedInterval domain_bounds;
if (!GetDomainOffsetBounds(domain, offset, &domain_bounds)) {
return false;
}
const int64_t intersection_lb = std::max(interval.start, domain_bounds.start);
const int64_t intersection_ub = std::min(interval.end, domain_bounds.end);
if (intersection_lb > intersection_ub) return false;
*intersection = ClosedInterval(intersection_lb, intersection_ub);
return true;
}
ClosedInterval GetVariableBounds(int index,
const RoutingLinearSolverWrapper& solver) {
return ClosedInterval(solver.GetVariableLowerBound(index),
solver.GetVariableUpperBound(index));
}
bool TightenStartEndVariableBoundsWithResource(
const RoutingDimension& dimension, const ResourceGroup::Resource& resource,
const ClosedInterval& start_bounds, int start_index,
const ClosedInterval& end_bounds, int end_index, int64_t offset,
RoutingLinearSolverWrapper* solver) {
const ResourceGroup::Attributes& attributes =
resource.GetDimensionAttributes(&dimension);
ClosedInterval new_start_bounds;
ClosedInterval new_end_bounds;
return GetIntervalIntersectionWithOffsetDomain(start_bounds,
attributes.start_domain(),
offset, &new_start_bounds) &&
solver->SetVariableBounds(start_index, new_start_bounds.start,
new_start_bounds.end) &&
GetIntervalIntersectionWithOffsetDomain(
end_bounds, attributes.end_domain(), offset, &new_end_bounds) &&
solver->SetVariableBounds(end_index, new_end_bounds.start,
new_end_bounds.end);
}
bool TightenStartEndVariableBoundsWithAssignedResources(
const RoutingDimension& dimension, int v, int start_index, int end_index,
int64_t offset, RoutingLinearSolverWrapper* solver) {
const RoutingModel* model = dimension.model();
for (int rg_index : model->GetDimensionResourceGroupIndices(&dimension)) {
const IntVar* res_var = model->ResourceVars(rg_index)[v];
DCHECK(res_var->Bound());
const int res_index = res_var->Value();
if (res_index < 0) {
// No resource from this group assigned to the vehicle.
DCHECK(!model->GetResourceGroup(rg_index)->VehicleRequiresAResource(v));
continue;
}
const ResourceGroup::Resource& resource =
model->GetResourceGroup(rg_index)->GetResource(res_index);
if (!TightenStartEndVariableBoundsWithResource(
dimension, resource, GetVariableBounds(start_index, *solver),
start_index, GetVariableBounds(end_index, *solver), end_index,
offset, solver)) {
return false;
}
}
return true;
}
} // namespace
std::vector<DimensionSchedulingStatus>
DimensionCumulOptimizerCore::OptimizeSingleRouteWithResources(
int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
const RouteDimensionTravelInfo& dimension_travel_info,
const std::vector<RoutingModel::ResourceGroup::Resource>& resources,
const std::vector<int>& resource_indices, bool optimize_vehicle_costs,
RoutingLinearSolverWrapper* solver,
std::vector<std::vector<int64_t>>* cumul_values,
std::vector<std::vector<int64_t>>* break_values,
std::vector<int64_t>* costs_without_transits, int64_t* transit_cost,
bool clear_lp) {
ClearIfNonNull(costs_without_transits);
const bool optimize_with_resources = !resource_indices.empty();
if (!optimize_with_resources && !resources.empty()) return {};
InitOptimizer(solver);
// Make sure SetRouteCumulConstraints will properly set the cumul bounds by
// looking at this route only.
DCHECK_EQ(propagator_.get(), nullptr);
RoutingModel* const model = dimension()->model();
if (model->IsEnd(next_accessor(model->Start(vehicle))) &&
!model->IsVehicleUsedWhenEmpty(vehicle)) {
// An unused empty vehicle doesn't require resources.
DCHECK(!optimize_with_resources);
optimize_vehicle_costs = false;
}
const int64_t cumul_offset =
dimension_->GetLocalOptimizerOffsetForVehicle(vehicle);
int64_t cost_offset = 0;
if (!SetRouteCumulConstraints(vehicle, next_accessor, transit_accessor,
dimension_travel_info, cumul_offset,
optimize_vehicle_costs, solver, transit_cost,
&cost_offset)) {
if (costs_without_transits != nullptr) {
costs_without_transits->assign(1, -1);
}
return {DimensionSchedulingStatus::INFEASIBLE};
}
DCHECK_GE(current_route_cumul_variables_.size(), 2);
// NOTE: When there are no resources to optimize for, we still solve the
// optimization problem for the route (without any added resource constraint).
const int num_solves =
std::max(static_cast<decltype(resource_indices.size())>(1UL),
resource_indices.size());
if (costs_without_transits != nullptr) {
costs_without_transits->assign(num_solves, -1);
}
if (cumul_values != nullptr) cumul_values->assign(num_solves, {});
if (break_values != nullptr) break_values->assign(num_solves, {});
const int start_cumul = current_route_cumul_variables_[0];
const ClosedInterval start_bounds = GetVariableBounds(start_cumul, *solver);
const int end_cumul = current_route_cumul_variables_.back();
const ClosedInterval end_bounds = GetVariableBounds(end_cumul, *solver);
std::vector<DimensionSchedulingStatus> statuses;
statuses.reserve(num_solves);
for (int i = 0; i < num_solves; i++) {
if (model->CheckLimit()) {
// The model's deadline has been reached, stop.
ClearIfNonNull(costs_without_transits);
ClearIfNonNull(cumul_values);
ClearIfNonNull(break_values);
solver->Clear();
return {};
}
if (optimize_with_resources &&
!TightenStartEndVariableBoundsWithResource(
*dimension_, resources[resource_indices[i]], start_bounds,
start_cumul, end_bounds, end_cumul, cumul_offset, solver)) {
// The resource attributes don't match this vehicle.
statuses.push_back(DimensionSchedulingStatus::INFEASIBLE);
continue;
}
statuses.push_back(solver->Solve(model->RemainingTime()));
if (statuses.back() == DimensionSchedulingStatus::INFEASIBLE) {
continue;
}
if (costs_without_transits != nullptr) {
costs_without_transits->at(i) =
optimize_vehicle_costs
? CapAdd(cost_offset, solver->GetObjectiveValue())
: 0;
}
if (cumul_values != nullptr) {
SetValuesFromLP(current_route_cumul_variables_, cumul_offset, solver,
&cumul_values->at(i));
}
if (break_values != nullptr) {
SetValuesFromLP(current_route_break_variables_, cumul_offset, solver,
&break_values->at(i));
}
}
if (clear_lp) {
solver->Clear();
}
return statuses;
}
DimensionSchedulingStatus DimensionCumulOptimizerCore::Optimize(
const std::function<int64_t(int64_t)>& next_accessor,
const std::vector<RouteDimensionTravelInfo>&
dimension_travel_info_per_route,
RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
std::vector<int64_t>* break_values,
std::vector<std::vector<int>>* resource_indices_per_group,
int64_t* cost_without_transits, int64_t* transit_cost, bool clear_lp,
bool optimize_resource_assignment) {
InitOptimizer(solver);
if (!optimize_resource_assignment) {
DCHECK_EQ(resource_indices_per_group, nullptr);
}
// If both "cumul_values" and "costs_without_transits" parameters are null,
// we don't try to optimize the cost and stop at the first feasible solution.
const bool optimize_costs =
(cumul_values != nullptr) || (cost_without_transits != nullptr);
bool has_vehicles_being_optimized = false;
const int64_t cumul_offset = dimension_->GetGlobalOptimizerOffset();
if (propagator_ != nullptr &&
!propagator_->PropagateCumulBounds(next_accessor, cumul_offset,
&dimension_travel_info_per_route)) {
return DimensionSchedulingStatus::INFEASIBLE;
}
int64_t total_transit_cost = 0;
int64_t total_cost_offset = 0;
const RoutingModel* model = dimension_->model();
for (int vehicle = 0; vehicle < model->vehicles(); vehicle++) {
int64_t route_transit_cost = 0;
int64_t route_cost_offset = 0;
const bool vehicle_is_used =
!model->IsEnd(next_accessor(model->Start(vehicle))) ||
model->IsVehicleUsedWhenEmpty(vehicle);
const bool optimize_vehicle_costs = optimize_costs && vehicle_is_used;
const RouteDimensionTravelInfo& dimension_travel_info =
dimension_travel_info_per_route.empty()
? RouteDimensionTravelInfo()
: dimension_travel_info_per_route[vehicle];
if (!SetRouteCumulConstraints(
vehicle, next_accessor, dimension_->transit_evaluator(vehicle),
dimension_travel_info, cumul_offset, optimize_vehicle_costs, solver,
&route_transit_cost, &route_cost_offset)) {
return DimensionSchedulingStatus::INFEASIBLE;
}
DCHECK_GE(current_route_cumul_variables_.size(), 2);
if (vehicle_is_used && !optimize_resource_assignment) {
// Tighten the route start/end cumul wrt. resources assigned to it.
if (!TightenStartEndVariableBoundsWithAssignedResources(
*dimension_, vehicle, current_route_cumul_variables_[0],
current_route_cumul_variables_.back(), cumul_offset, solver)) {
return DimensionSchedulingStatus::INFEASIBLE;
}
}
total_transit_cost = CapAdd(total_transit_cost, route_transit_cost);
total_cost_offset = CapAdd(total_cost_offset, route_cost_offset);
has_vehicles_being_optimized |= optimize_vehicle_costs;
}
if (transit_cost != nullptr) {
*transit_cost = total_transit_cost;
}
if (!SetGlobalConstraints(next_accessor, cumul_offset,
has_vehicles_being_optimized,
optimize_resource_assignment, solver)) {
return DimensionSchedulingStatus::INFEASIBLE;
}
const DimensionSchedulingStatus status =
solver->Solve(model->RemainingTime());