forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing_neighborhoods.cc
1358 lines (1269 loc) · 50.1 KB
/
routing_neighborhoods.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_neighborhoods.h"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <utility>
#include <vector>
#include "absl/log/check.h"
#include "absl/types/span.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_types.h"
#include "ortools/constraint_solver/routing_utils.h"
#include "ortools/util/saturated_arithmetic.h"
namespace operations_research {
MakeRelocateNeighborsOperator::MakeRelocateNeighborsOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
std::function<const std::vector<int>&(int, int)> get_neighbors,
RoutingTransitCallback2 arc_evaluator)
: PathOperator(vars, secondary_vars,
/*number_of_base_nodes=*/get_neighbors == nullptr ? 2 : 1,
/*skip_locally_optimal_paths=*/true,
/*accept_path_end_base=*/false,
std::move(start_empty_path_class), std::move(get_neighbors)),
arc_evaluator_(std::move(arc_evaluator)) {}
bool MakeRelocateNeighborsOperator::MakeNeighbor() {
const auto do_move = [this](int64_t before_chain, int64_t destination) {
int64_t chain_end = Next(before_chain);
if (IsPathEnd(chain_end)) return false;
if (chain_end == destination) return false;
const int64_t max_arc_value = arc_evaluator_(destination, chain_end);
int64_t next = Next(chain_end);
while (!IsPathEnd(next) &&
arc_evaluator_(chain_end, next) <= max_arc_value) {
// We return false here to avoid symmetric moves. The rationale is that
// if destination is part of the same group as the chain, we probably want
// to extend the chain to contain it, which means finding another
// destination further down the path.
// TODO(user): Add a parameter to either return false or break here,
// depending if we want to permutate nodes within the same chain.
if (next == destination) return false;
chain_end = next;
next = Next(chain_end);
}
return MoveChainAndRepair(before_chain, chain_end, destination);
};
if (HasNeighbors()) {
const int64_t node = GetNeighborForBaseNode(0);
if (IsInactive(node)) return false;
return do_move(/*before_chain=*/Prev(node),
/*destination=*/BaseNode(0));
} else {
return do_move(/*before_chain=*/BaseNode(0),
/*destination=*/BaseNode(1));
}
}
bool MakeRelocateNeighborsOperator::MoveChainAndRepair(int64_t before_chain,
int64_t chain_end,
int64_t destination) {
if (MoveChain(before_chain, chain_end, destination)) {
if (!IsPathStart(destination)) {
int64_t current = Prev(destination);
int64_t last = chain_end;
if (current == last) { // chain was just before destination
current = before_chain;
}
while (last >= 0 && !IsPathStart(current) && current != last) {
last = Reposition(current, last);
current = Prev(current);
}
}
return true;
}
return false;
}
int64_t MakeRelocateNeighborsOperator::Reposition(int64_t before_to_move,
int64_t up_to) {
const int64_t kNoChange = -1;
const int64_t to_move = Next(before_to_move);
int64_t next = Next(to_move);
if (Var(to_move)->Contains(next)) {
return kNoChange;
}
int64_t prev = next;
next = Next(next);
while (prev != up_to) {
if (Var(prev)->Contains(to_move) && Var(to_move)->Contains(next)) {
MoveChain(before_to_move, to_move, prev);
return up_to;
}
prev = next;
next = Next(next);
}
if (Var(prev)->Contains(to_move)) {
MoveChain(before_to_move, to_move, prev);
return to_move;
}
return kNoChange;
}
SwapActiveToShortestPathOperator::SwapActiveToShortestPathOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
std::vector<std::vector<int64_t>> alternative_sets,
RoutingTransitCallback2 arc_evaluator)
: PathOperator(vars, secondary_vars, 1, true, false,
std::move(start_empty_path_class), nullptr),
arc_evaluator_(std::move(arc_evaluator)),
alternative_sets_(std::move(alternative_sets)),
to_alternative_set_(vars.size(), -1),
path_predecessor_(vars.size(), -1),
touched_(vars.size()) {
for (int i = 0; i < alternative_sets_.size(); ++i) {
for (int j : alternative_sets_[i]) {
if (j < to_alternative_set_.size()) to_alternative_set_[j] = i;
}
}
}
bool SwapActiveToShortestPathOperator::MakeNeighbor() {
const int64_t before_chain = BaseNode(0);
if (to_alternative_set_[before_chain] != -1) return false;
int64_t next = Next(before_chain);
std::vector<int> alternatives;
while (!IsPathEnd(next) && to_alternative_set_[next] != -1 &&
alternative_sets_[to_alternative_set_[next]].size() > 1) {
alternatives.push_back(to_alternative_set_[next]);
next = Next(next);
}
if (alternatives.empty()) return false;
const int sink = next;
next = OldNext(before_chain);
bool swap_done = false;
for (int64_t node : GetShortestPath(before_chain, sink, alternatives)) {
if (node != next) {
SwapActiveAndInactive(next, node);
swap_done = true;
}
next = OldNext(next);
}
return swap_done;
}
const std::vector<int64_t>& SwapActiveToShortestPathOperator::GetShortestPath(
int source, int sink, const std::vector<int>& alternative_chain) {
path_.clear();
if (alternative_chain.empty()) return path_;
// Initializing values at the first "layer" after the source (from source to
// all alternatives at rank 0).
const std::vector<int64_t>& first_alternative_set =
alternative_sets_[alternative_chain[0]];
std::vector<int64_t> prev_values;
prev_values.reserve(first_alternative_set.size());
for (int alternative_node : first_alternative_set) {
prev_values.push_back(arc_evaluator_(source, alternative_node));
}
// Updating values "layer" by "layer" (each one is fully connected to the
// previous one).
std::vector<int64_t> current_values;
for (int rank = 1; rank < alternative_chain.size(); ++rank) {
const std::vector<int64_t>& current_alternative_set =
alternative_sets_[alternative_chain[rank]];
current_values.clear();
current_values.reserve(current_alternative_set.size());
const std::vector<int64_t>& prev_alternative_set =
alternative_sets_[alternative_chain[rank - 1]];
for (int alternative_node : current_alternative_set) {
int64_t min_value = kint64max;
int predecessor = -1;
for (int prev_alternative = 0;
prev_alternative < prev_alternative_set.size(); ++prev_alternative) {
const int64_t new_value =
CapAdd(prev_values[prev_alternative],
arc_evaluator_(prev_alternative_set[prev_alternative],
alternative_node));
if (new_value <= min_value) {
min_value = new_value;
predecessor = prev_alternative_set[prev_alternative];
}
}
current_values.push_back(min_value);
path_predecessor_[alternative_node] = predecessor;
}
prev_values.swap(current_values);
}
// Get the predecessor in the shortest path to sink in the last layer.
int64_t min_value = kint64max;
int predecessor = -1;
const std::vector<int64_t>& last_alternative_set =
alternative_sets_[alternative_chain.back()];
for (int alternative = 0; alternative < last_alternative_set.size();
++alternative) {
const int64_t new_value =
CapAdd(prev_values[alternative],
arc_evaluator_(last_alternative_set[alternative], sink));
if (new_value <= min_value) {
min_value = new_value;
predecessor = last_alternative_set[alternative];
}
}
if (predecessor == -1) return path_;
// Build the path from predecessors on the shortest path.
path_.resize(alternative_chain.size(), predecessor);
touched_.SparseClearAll();
touched_.Set(predecessor);
for (int rank = alternative_chain.size() - 2; rank >= 0; --rank) {
path_[rank] = path_predecessor_[path_[rank + 1]];
if (touched_[path_[rank]]) {
path_.clear();
return path_;
}
touched_.Set(path_[rank]);
}
return path_;
}
MakePairActiveOperator::MakePairActiveOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars, 2, false, true,
std::move(start_empty_path_class), nullptr),
inactive_pair_(0),
inactive_pair_first_index_(0),
inactive_pair_second_index_(0),
pairs_(pairs) {}
bool MakePairActiveOperator::MakeOneNeighbor() {
while (inactive_pair_ < pairs_.size()) {
if (PathOperator::MakeOneNeighbor()) return true;
ResetPosition();
const auto& [pickup_alternatives, delivery_alternatives] =
pairs_[inactive_pair_];
if (inactive_pair_first_index_ < pickup_alternatives.size() - 1) {
++inactive_pair_first_index_;
} else if (inactive_pair_second_index_ < delivery_alternatives.size() - 1) {
inactive_pair_first_index_ = 0;
++inactive_pair_second_index_;
} else {
inactive_pair_ = FindNextInactivePair(inactive_pair_ + 1);
inactive_pair_first_index_ = 0;
inactive_pair_second_index_ = 0;
}
}
return false;
}
bool MakePairActiveOperator::MakeNeighbor() {
DCHECK_EQ(StartNode(0), StartNode(1));
// Inserting the second node of the pair before the first one which ensures
// that the only solutions where both nodes are next to each other have the
// first node before the second (the move is not symmetric and doing it this
// way ensures that a potential precedence constraint between the nodes of the
// pair is not violated).
const auto& [pickup_alternatives, delivery_alternatives] =
pairs_[inactive_pair_];
return MakeActive(delivery_alternatives[inactive_pair_second_index_],
BaseNode(1)) &&
MakeActive(pickup_alternatives[inactive_pair_first_index_],
BaseNode(0));
}
int64_t MakePairActiveOperator::GetBaseNodeRestartPosition(int base_index) {
// Base node 1 must be after base node 0 if they are both on the same path.
if (base_index == 0 || StartNode(base_index) != StartNode(base_index - 1)) {
return StartNode(base_index);
} else {
return BaseNode(base_index - 1);
}
}
void MakePairActiveOperator::OnNodeInitialization() {
inactive_pair_ = FindNextInactivePair(0);
inactive_pair_first_index_ = 0;
inactive_pair_second_index_ = 0;
}
int MakePairActiveOperator::FindNextInactivePair(int pair_index) const {
for (int index = pair_index; index < pairs_.size(); ++index) {
if (!ContainsActiveNodes(pairs_[index].pickup_alternatives) &&
!ContainsActiveNodes(pairs_[index].delivery_alternatives)) {
return index;
}
}
return pairs_.size();
}
bool MakePairActiveOperator::ContainsActiveNodes(
const std::vector<int64_t>& nodes) const {
for (int64_t node : nodes) {
if (!IsInactive(node)) return true;
}
return false;
}
MakePairInactiveOperator::MakePairInactiveOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars, 1, true, false,
std::move(start_empty_path_class), nullptr) {
AddPairAlternativeSets(pairs);
}
bool MakePairInactiveOperator::MakeNeighbor() {
const int64_t base = BaseNode(0);
const int64_t first_index = Next(base);
const int64_t second_index = GetActiveAlternativeSibling(first_index);
if (second_index < 0) {
return false;
}
return MakeChainInactive(base, first_index) &&
MakeChainInactive(Prev(second_index), second_index);
}
PairRelocateOperator::PairRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars, 3, true, false,
std::move(start_empty_path_class), nullptr) {
AddPairAlternativeSets(pairs);
}
bool PairRelocateOperator::MakeNeighbor() {
DCHECK_EQ(StartNode(1), StartNode(2));
const int64_t first_pair_node = BaseNode(kPairFirstNode);
if (IsPathStart(first_pair_node)) {
return false;
}
int64_t first_prev = Prev(first_pair_node);
const int second_pair_node = GetActiveAlternativeSibling(first_pair_node);
if (second_pair_node < 0 || IsPathEnd(second_pair_node) ||
IsPathStart(second_pair_node)) {
return false;
}
const int64_t second_prev = Prev(second_pair_node);
const int64_t first_node_destination = BaseNode(kPairFirstNodeDestination);
if (first_node_destination == second_pair_node) {
// The second_pair_node -> first_pair_node link is forbidden.
return false;
}
const int64_t second_node_destination = BaseNode(kPairSecondNodeDestination);
if (second_prev == first_pair_node && first_node_destination == first_prev &&
second_node_destination == first_prev) {
// If the current sequence is first_prev -> first_pair_node ->
// second_pair_node, and both 1st and 2nd are moved both to prev, the result
// of the move will be first_prev -> first_pair_node -> second_pair_node,
// which is no move.
return false;
}
// Relocation is successful if both moves are feasible and at least one of the
// nodes moves.
if (second_pair_node == second_node_destination ||
first_pair_node == first_node_destination) {
return false;
}
const bool moved_second_pair_node =
MoveChain(second_prev, second_pair_node, second_node_destination);
// Explicitly calling Prev as second_pair_node might have been moved before
// first_pair_node.
const bool moved_first_pair_node =
MoveChain(Prev(first_pair_node), first_pair_node, first_node_destination);
// Swapping alternatives in.
SwapActiveAndInactive(second_pair_node,
BaseSiblingAlternativeNode(kPairFirstNode));
SwapActiveAndInactive(first_pair_node, BaseAlternativeNode(kPairFirstNode));
return moved_first_pair_node || moved_second_pair_node;
}
int64_t PairRelocateOperator::GetBaseNodeRestartPosition(int base_index) {
// Destination node of the second node of a pair must be after the
// destination node of the first node of a pair.
if (base_index == kPairSecondNodeDestination) {
return BaseNode(kPairFirstNodeDestination);
} else {
return StartNode(base_index);
}
}
GroupPairAndRelocateOperator::GroupPairAndRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
std::function<const std::vector<int>&(int, int)> get_neighbors,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars,
/*number_of_base_nodes=*/get_neighbors == nullptr ? 2 : 1,
/*skip_locally_optimal_paths=*/true,
/*accept_path_end_base=*/false,
std::move(start_empty_path_class),
std::move(get_neighbors)) {
AddPairAlternativeSets(pairs);
}
bool GroupPairAndRelocateOperator::MakeNeighbor() {
const auto do_move = [this](int64_t node, int64_t destination) {
if (IsPathEnd(node) || IsInactive(node)) return false;
const int64_t sibling = GetActiveAlternativeSibling(node);
if (sibling == -1) return false;
// Skip redundant cases.
if (destination == node || destination == sibling) return false;
const bool ok = MoveChain(Prev(node), node, destination);
return MoveChain(Prev(sibling), sibling, node) || ok;
};
return HasNeighbors()
? do_move(/*node=*/GetNeighborForBaseNode(0),
/*destination=*/BaseNode(0))
: do_move(/*node=*/Next(BaseNode(0)), /*destination=*/BaseNode(1));
}
LightPairRelocateOperator::LightPairRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
std::function<const std::vector<int>&(int, int)> get_neighbors,
const std::vector<PickupDeliveryPair>& pairs,
std::function<bool(int64_t)> force_lifo)
: PathOperator(vars, secondary_vars,
/*number_of_base_nodes=*/get_neighbors == nullptr ? 2 : 1,
/*skip_locally_optimal_paths=*/true,
/*accept_path_end_base=*/false,
std::move(start_empty_path_class), std::move(get_neighbors)),
force_lifo_(std::move(force_lifo)) {
AddPairAlternativeSets(pairs);
}
LightPairRelocateOperator::LightPairRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs,
std::function<bool(int64_t)> force_lifo)
: LightPairRelocateOperator(vars, secondary_vars, start_empty_path_class,
nullptr, pairs, std::move(force_lifo)) {}
bool LightPairRelocateOperator::MakeNeighbor() {
const auto do_move = [this](int64_t node, int64_t destination,
bool destination_is_lifo) {
if (IsPathStart(node) || IsPathEnd(node) || IsInactive(node)) return false;
const int64_t prev = Prev(node);
if (IsPathEnd(node)) return false;
const int64_t sibling = GetActiveAlternativeSibling(node);
if (sibling == -1 || destination == sibling) return false;
// Note: MoveChain will return false if it is a no-op (moving the chain to
// its current position). However we want to accept the move if at least
// node or sibling gets moved to a new position. Therefore we want to be
// sure both MoveChains are called and at least one succeeds.
// Special case handling relocating the first node of a pair "before" the
// first node of another pair. Limiting this to relocating after the start
// of the path as other moves will be mostly equivalent to relocating
// "after".
// TODO(user): extend to relocating before the start of sub-tours (when
// all pairs have been matched).
if (IsPathStart(destination)) {
const bool ok = MoveChain(prev, node, destination);
const int64_t destination_sibling =
GetActiveAlternativeSibling(Next(node));
if (destination_sibling == -1) {
// Not inserting before a pair node: insert sibling after node.
return MoveChain(Prev(sibling), sibling, node) || ok;
} else {
// Depending on the lifo status of the path, insert sibling before or
// after destination_sibling since node is being inserted before
// next(destination).
if (!destination_is_lifo) {
if (Prev(destination_sibling) == sibling) return ok;
return MoveChain(Prev(sibling), sibling, Prev(destination_sibling)) ||
ok;
} else {
return MoveChain(Prev(sibling), sibling, destination_sibling) || ok;
}
}
}
// Relocating the first node of a pair "after" the first node of another
// pair.
const int64_t destination_sibling =
GetActiveAlternativeSibling(destination);
if (destination_sibling == -1) return false;
const bool ok = MoveChain(prev, node, destination);
if (!destination_is_lifo) {
return MoveChain(Prev(sibling), sibling, destination_sibling) || ok;
} else {
if (Prev(destination_sibling) == sibling) return ok;
return MoveChain(Prev(sibling), sibling, Prev(destination_sibling)) || ok;
}
};
// TODO(user): Add support for lifo for neighbor-based move.
return HasNeighbors()
? do_move(/*node=*/GetNeighborForBaseNode(0),
/*destination=*/BaseNode(0),
/*destination_is_lifo=*/false)
: do_move(/*node=*/Next(BaseNode(0)), /*destination=*/BaseNode(1),
force_lifo_ != nullptr && force_lifo_(StartNode(1)));
}
PairExchangeOperator::PairExchangeOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
std::function<const std::vector<int>&(int, int)> get_neighbors,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars,
/*number_of_base_nodes=*/get_neighbors == nullptr ? 2 : 1,
/*skip_locally_optimal_paths=*/true,
/*accept_path_end_base=*/true,
std::move(start_empty_path_class),
std::move(get_neighbors)) {
AddPairAlternativeSets(pairs);
}
bool PairExchangeOperator::MakeNeighbor() {
const int64_t node1 = BaseNode(0);
int64_t prev1, sibling1, sibling_prev1 = -1;
if (!GetPreviousAndSibling(node1, &prev1, &sibling1, &sibling_prev1)) {
return false;
}
int64_t node2 = -1;
if (!HasNeighbors()) {
node2 = BaseNode(1);
} else {
const int64_t neighbor = GetNeighborForBaseNode(0);
if (IsInactive(neighbor) || IsPathStart(neighbor)) return false;
node2 = Prev(neighbor);
}
int64_t prev2, sibling2, sibling_prev2 = -1;
if (!GetPreviousAndSibling(node2, &prev2, &sibling2, &sibling_prev2)) {
return false;
}
bool status = true;
// Exchanging node1 and node2.
if (node1 == prev2) {
status = MoveChain(prev2, node2, prev1);
if (sibling_prev1 == node2) sibling_prev1 = node1;
if (sibling_prev2 == node2) sibling_prev2 = node1;
} else if (node2 == prev1) {
status = MoveChain(prev1, node1, prev2);
if (sibling_prev1 == node1) sibling_prev1 = node2;
if (sibling_prev2 == node1) sibling_prev2 = node2;
} else {
status = MoveChain(prev1, node1, node2) && MoveChain(prev2, node2, prev1);
if (sibling_prev1 == node1) {
sibling_prev1 = node2;
} else if (sibling_prev1 == node2) {
sibling_prev1 = node1;
}
if (sibling_prev2 == node1) {
sibling_prev2 = node2;
} else if (sibling_prev2 == node2) {
sibling_prev2 = node1;
}
}
if (!status) return false;
// Exchanging sibling1 and sibling2.
if (sibling1 == sibling_prev2) {
status = MoveChain(sibling_prev2, sibling2, sibling_prev1);
} else if (sibling2 == sibling_prev1) {
status = MoveChain(sibling_prev1, sibling1, sibling_prev2);
} else {
status = MoveChain(sibling_prev1, sibling1, sibling2) &&
MoveChain(sibling_prev2, sibling2, sibling_prev1);
}
// Swapping alternatives in.
SwapActiveAndInactive(sibling1, BaseSiblingAlternativeNode(0));
SwapActiveAndInactive(node1, BaseAlternativeNode(0));
if (!HasNeighbors()) {
// TODO(user): Support alternatives with neighbors.
SwapActiveAndInactive(sibling2, BaseSiblingAlternativeNode(1));
SwapActiveAndInactive(node2, BaseAlternativeNode(1));
}
return status;
}
bool PairExchangeOperator::GetPreviousAndSibling(
int64_t node, int64_t* previous, int64_t* sibling,
int64_t* sibling_previous) const {
if (IsPathStart(node)) return false;
*previous = Prev(node);
*sibling = GetActiveAlternativeSibling(node);
*sibling_previous = *sibling >= 0 ? Prev(*sibling) : -1;
return *sibling_previous >= 0;
}
PairExchangeRelocateOperator::PairExchangeRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars, 6, true, false,
std::move(start_empty_path_class), nullptr) {
AddPairAlternativeSets(pairs);
}
bool PairExchangeRelocateOperator::MakeNeighbor() {
DCHECK_EQ(StartNode(kSecondPairFirstNodeDestination),
StartNode(kSecondPairSecondNodeDestination));
DCHECK_EQ(StartNode(kSecondPairFirstNode),
StartNode(kFirstPairFirstNodeDestination));
DCHECK_EQ(StartNode(kSecondPairFirstNode),
StartNode(kFirstPairSecondNodeDestination));
if (StartNode(kFirstPairFirstNode) == StartNode(kSecondPairFirstNode)) {
SetNextBaseToIncrement(kSecondPairFirstNode);
return false;
}
// Through this method, <base>[X][Y] represent the <base> variable for the
// node Y of pair X. <base> is in node, prev, dest.
int64_t nodes[2][2];
int64_t prev[2][2];
int64_t dest[2][2];
nodes[0][0] = BaseNode(kFirstPairFirstNode);
nodes[1][0] = BaseNode(kSecondPairFirstNode);
if (nodes[1][0] <= nodes[0][0]) {
// Exchange is symmetric.
SetNextBaseToIncrement(kSecondPairFirstNode);
return false;
}
if (!GetPreviousAndSibling(nodes[0][0], &prev[0][0], &nodes[0][1],
&prev[0][1])) {
SetNextBaseToIncrement(kFirstPairFirstNode);
return false;
}
if (!GetPreviousAndSibling(nodes[1][0], &prev[1][0], &nodes[1][1],
&prev[1][1])) {
SetNextBaseToIncrement(kSecondPairFirstNode);
return false;
}
if (!LoadAndCheckDest(0, 0, kFirstPairFirstNodeDestination, nodes, dest)) {
SetNextBaseToIncrement(kFirstPairFirstNodeDestination);
return false;
}
if (!LoadAndCheckDest(0, 1, kFirstPairSecondNodeDestination, nodes, dest)) {
SetNextBaseToIncrement(kFirstPairSecondNodeDestination);
return false;
}
if (StartNode(kSecondPairFirstNodeDestination) !=
StartNode(kFirstPairFirstNode) ||
!LoadAndCheckDest(1, 0, kSecondPairFirstNodeDestination, nodes, dest)) {
SetNextBaseToIncrement(kSecondPairFirstNodeDestination);
return false;
}
if (!LoadAndCheckDest(1, 1, kSecondPairSecondNodeDestination, nodes, dest)) {
SetNextBaseToIncrement(kSecondPairSecondNodeDestination);
return false;
}
if (!MoveNode(0, 1, nodes, dest, prev)) {
SetNextBaseToIncrement(kFirstPairSecondNodeDestination);
return false;
}
if (!MoveNode(0, 0, nodes, dest, prev)) {
SetNextBaseToIncrement(kFirstPairSecondNodeDestination);
return false;
}
if (!MoveNode(1, 1, nodes, dest, prev)) {
return false;
}
if (!MoveNode(1, 0, nodes, dest, prev)) {
return false;
}
return true;
}
bool PairExchangeRelocateOperator::MoveNode(int pair, int node,
int64_t nodes[2][2],
int64_t dest[2][2],
int64_t prev[2][2]) {
if (!MoveChain(prev[pair][node], nodes[pair][node], dest[pair][node])) {
return false;
}
// Update the other pair if needed.
if (prev[1 - pair][0] == dest[pair][node]) {
prev[1 - pair][0] = nodes[pair][node];
}
if (prev[1 - pair][1] == dest[pair][node]) {
prev[1 - pair][1] = nodes[pair][node];
}
return true;
}
bool PairExchangeRelocateOperator::LoadAndCheckDest(int pair, int node,
int64_t base_node,
int64_t nodes[2][2],
int64_t dest[2][2]) const {
dest[pair][node] = BaseNode(base_node);
// A destination cannot be a node that will be moved.
return !(nodes[0][0] == dest[pair][node] || nodes[0][1] == dest[pair][node] ||
nodes[1][0] == dest[pair][node] || nodes[1][1] == dest[pair][node]);
}
bool PairExchangeRelocateOperator::OnSamePathAsPreviousBase(
int64_t base_index) {
// Ensuring the destination of the first pair is on the route of the second.
// pair.
// Ensuring that destination of both nodes of a pair are on the same route.
return base_index == kFirstPairFirstNodeDestination ||
base_index == kFirstPairSecondNodeDestination ||
base_index == kSecondPairSecondNodeDestination;
}
int64_t PairExchangeRelocateOperator::GetBaseNodeRestartPosition(
int base_index) {
if (base_index == kFirstPairSecondNodeDestination ||
base_index == kSecondPairSecondNodeDestination) {
return BaseNode(base_index - 1);
} else {
return StartNode(base_index);
}
}
bool PairExchangeRelocateOperator::GetPreviousAndSibling(
int64_t node, int64_t* previous, int64_t* sibling,
int64_t* sibling_previous) const {
if (IsPathStart(node)) return false;
*previous = Prev(node);
*sibling = GetActiveAlternativeSibling(node);
*sibling_previous = *sibling >= 0 ? Prev(*sibling) : -1;
return *sibling_previous >= 0;
}
SwapIndexPairOperator::SwapIndexPairOperator(
const std::vector<IntVar*>& vars, const std::vector<IntVar*>& path_vars,
const std::vector<PickupDeliveryPair>& pairs)
: IntVarLocalSearchOperator(vars),
pairs_(pairs),
pair_index_(0),
first_index_(0),
second_index_(0),
number_of_nexts_(vars.size()),
ignore_path_vars_(path_vars.empty()) {
if (!ignore_path_vars_) {
AddVars(path_vars);
}
}
bool SwapIndexPairOperator::MakeNextNeighbor(Assignment* delta,
Assignment* deltadelta) {
const int64_t kNoPath = -1;
CHECK(delta != nullptr);
while (true) {
RevertChanges(true);
if (pair_index_ >= pairs_.size()) return false;
const int64_t path =
ignore_path_vars_ ? 0LL : Value(first_active_ + number_of_nexts_);
const int64_t prev_first = prevs_[first_active_];
const int64_t next_first = Value(first_active_);
// Making current active "pickup" unperformed.
SetNext(first_active_, first_active_, kNoPath);
// Inserting "pickup" alternative at the same position.
const auto& [pickup_alternatives, delivery_alternatives] =
pairs_[pair_index_];
const int64_t insert_first = pickup_alternatives[first_index_];
SetNext(prev_first, insert_first, path);
SetNext(insert_first, next_first, path);
int64_t prev_second = prevs_[second_active_];
if (prev_second == first_active_) {
prev_second = insert_first;
}
DCHECK_EQ(path, ignore_path_vars_
? int64_t{0}
: Value(second_active_ + number_of_nexts_));
const int64_t next_second = Value(second_active_);
// Making current active "delivery" unperformed.
SetNext(second_active_, second_active_, kNoPath);
// Inserting "delivery" alternative at the same position.
const int64_t insert_second = delivery_alternatives[second_index_];
SetNext(prev_second, insert_second, path);
SetNext(insert_second, next_second, path);
// Move to next "pickup/delivery" alternative.
++second_index_;
if (second_index_ >= delivery_alternatives.size()) {
second_index_ = 0;
++first_index_;
if (first_index_ >= pickup_alternatives.size()) {
first_index_ = 0;
while (true) {
++pair_index_;
if (!UpdateActiveNodes()) break;
if (first_active_ != -1 && second_active_ != -1) {
break;
}
}
}
}
if (ApplyChanges(delta, deltadelta)) return true;
}
return false;
}
void SwapIndexPairOperator::OnStart() {
prevs_.resize(number_of_nexts_, -1);
for (int index = 0; index < number_of_nexts_; ++index) {
const int64_t next = Value(index);
if (next >= prevs_.size()) prevs_.resize(next + 1, -1);
prevs_[next] = index;
}
pair_index_ = 0;
first_index_ = 0;
second_index_ = 0;
first_active_ = -1;
second_active_ = -1;
while (true) {
if (!UpdateActiveNodes()) break;
if (first_active_ != -1 && second_active_ != -1) {
break;
}
++pair_index_;
}
}
bool SwapIndexPairOperator::UpdateActiveNodes() {
if (pair_index_ < pairs_.size()) {
const auto& [pickup_alternatives, delivery_alternatives] =
pairs_[pair_index_];
first_active_ = -1;
second_active_ = -1;
if (pickup_alternatives.size() == 1 && delivery_alternatives.size() == 1) {
// When there are no alternatives, the pair should be ignored whether
// there are active nodes or not.
return true;
}
for (const int64_t first : pickup_alternatives) {
if (Value(first) != first) {
first_active_ = first;
break;
}
}
for (const int64_t second : delivery_alternatives) {
if (Value(second) != second) {
second_active_ = second;
break;
}
}
return true;
}
return false;
}
IndexPairSwapActiveOperator::IndexPairSwapActiveOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const std::vector<PickupDeliveryPair>& pairs)
: PathOperator(vars, secondary_vars, 1, true, false,
std::move(start_empty_path_class), nullptr),
inactive_node_(0) {
AddPairAlternativeSets(pairs);
}
bool IndexPairSwapActiveOperator::MakeNextNeighbor(Assignment* delta,
Assignment* deltadelta) {
while (inactive_node_ < Size()) {
if (!IsInactive(inactive_node_) ||
!PathOperator::MakeNextNeighbor(delta, deltadelta)) {
ResetPosition();
++inactive_node_;
} else {
return true;
}
}
return false;
}
bool IndexPairSwapActiveOperator::MakeNeighbor() {
const int64_t base = BaseNode(0);
const int64_t next = Next(base);
const int64_t other = GetActiveAlternativeSibling(next);
if (other != -1) {
return MakeChainInactive(Prev(other), other) &&
MakeChainInactive(base, next) && MakeActive(inactive_node_, base);
}
return false;
}
void IndexPairSwapActiveOperator::OnNodeInitialization() {
PathOperator::OnNodeInitialization();
for (int i = 0; i < Size(); ++i) {
if (IsInactive(i)) {
inactive_node_ = i;
return;
}
}
inactive_node_ = Size();
}
RelocateExpensiveChain::RelocateExpensiveChain(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
int num_arcs_to_consider,
std::function<int64_t(int64_t, int64_t, int64_t)> arc_cost_for_path_start)
: PathOperator(vars, secondary_vars, 1, false, false,
std::move(start_empty_path_class), nullptr),
num_arcs_to_consider_(num_arcs_to_consider),
current_path_(0),
current_expensive_arc_indices_({-1, -1}),
arc_cost_for_path_start_(std::move(arc_cost_for_path_start)),
end_path_(0),
has_non_empty_paths_to_explore_(false) {
DCHECK_GE(num_arcs_to_consider_, 2);
}
bool RelocateExpensiveChain::MakeNeighbor() {
const int first_arc_index = current_expensive_arc_indices_.first;
const int second_arc_index = current_expensive_arc_indices_.second;
DCHECK_LE(0, first_arc_index);
DCHECK_LT(first_arc_index, second_arc_index);
DCHECK_LT(second_arc_index, most_expensive_arc_starts_and_ranks_.size());
const std::pair<int, int>& first_start_and_rank =
most_expensive_arc_starts_and_ranks_[first_arc_index];
const std::pair<int, int>& second_start_and_rank =
most_expensive_arc_starts_and_ranks_[second_arc_index];
if (first_start_and_rank.second < second_start_and_rank.second) {
return CheckChainValidity(first_start_and_rank.first,
second_start_and_rank.first, BaseNode(0)) &&
MoveChain(first_start_and_rank.first, second_start_and_rank.first,
BaseNode(0));
}
return CheckChainValidity(second_start_and_rank.first,
first_start_and_rank.first, BaseNode(0)) &&
MoveChain(second_start_and_rank.first, first_start_and_rank.first,
BaseNode(0));
}
bool RelocateExpensiveChain::MakeOneNeighbor() {
while (has_non_empty_paths_to_explore_) {
if (!PathOperator::MakeOneNeighbor()) {
ResetPosition();
// Move on to the next expensive arcs on the same path.
if (IncrementCurrentArcIndices()) {
continue;
}
// Move on to the next non_empty path.
IncrementCurrentPath();
has_non_empty_paths_to_explore_ =
current_path_ != end_path_ &&
FindMostExpensiveChainsOnRemainingPaths();
} else {
return true;
}
}
return false;
}
void RelocateExpensiveChain::OnNodeInitialization() {
if (current_path_ >= path_starts().size()) {
// current_path_ was made empty by last move (and it was the last non-empty
// path), restart from 0.
current_path_ = 0;
}
end_path_ = current_path_;
has_non_empty_paths_to_explore_ = FindMostExpensiveChainsOnRemainingPaths();
}
void RelocateExpensiveChain::IncrementCurrentPath() {
const int num_paths = path_starts().size();
if (++current_path_ == num_paths) {
current_path_ = 0;
}
}
bool RelocateExpensiveChain::IncrementCurrentArcIndices() {
int& second_index = current_expensive_arc_indices_.second;
if (++second_index < most_expensive_arc_starts_and_ranks_.size()) {
return true;
}