forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouting_neighborhoods.cc
1656 lines (1504 loc) · 57.5 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-2021 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 <iterator>
#include <memory>
#include <queue>
#include <tuple>
#include <utility>
#include <vector>
#include "ortools/base/int_type.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_search.h"
#include "ortools/constraint_solver/routing_types.h"
#include "ortools/util/bitset.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,
RoutingTransitCallback2 arc_evaluator)
: PathOperator(vars, secondary_vars, 2, true, false,
std::move(start_empty_path_class)),
arc_evaluator_(std::move(arc_evaluator)) {}
bool MakeRelocateNeighborsOperator::MakeNeighbor() {
const int64_t before_chain = BaseNode(0);
int64_t chain_end = Next(before_chain);
if (IsPathEnd(chain_end)) return false;
const int64_t destination = BaseNode(1);
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) {
if (next == destination) return false;
chain_end = next;
next = Next(chain_end);
}
return MoveChainAndRepair(before_chain, chain_end, destination);
}
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;
}
MakePairActiveOperator::MakePairActiveOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const RoutingIndexPairs& pairs)
: PathOperator(vars, secondary_vars, 2, false, true,
std::move(start_empty_path_class)),
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();
if (inactive_pair_first_index_ < pairs_[inactive_pair_].first.size() - 1) {
++inactive_pair_first_index_;
} else if (inactive_pair_second_index_ <
pairs_[inactive_pair_].second.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).
return MakeActive(pairs_[inactive_pair_].second[inactive_pair_second_index_],
BaseNode(1)) &&
MakeActive(pairs_[inactive_pair_].first[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].first) &&
!ContainsActiveNodes(pairs_[index].second)) {
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 RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 1, true, false,
std::move(start_empty_path_class)) {
AddPairAlternativeSets(index_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 RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 3, true, false,
std::move(start_empty_path_class)) {
AddPairAlternativeSets(index_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);
// Explictly 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);
}
}
LightPairRelocateOperator::LightPairRelocateOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 2, true, false,
std::move(start_empty_path_class)) {
AddPairAlternativeSets(index_pairs);
}
bool LightPairRelocateOperator::MakeNeighbor() {
const int64_t prev1 = BaseNode(0);
const int64_t node1 = Next(prev1);
if (IsPathEnd(node1)) return false;
const int64_t sibling1 = GetActiveAlternativeSibling(node1);
if (sibling1 == -1) return false;
const int64_t node2 = BaseNode(1);
if (node2 == sibling1) return false;
const int64_t sibling2 = GetActiveAlternativeSibling(node2);
if (sibling2 == -1) 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 node1 or
// sibling1 gets moved to a new position. Therefore we want to be sure both
// MoveChains are called and at least one succeeds.
const bool ok = MoveChain(prev1, node1, node2);
return MoveChain(Prev(sibling1), sibling1, sibling2) || ok;
}
PairExchangeOperator::PairExchangeOperator(
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64_t)> start_empty_path_class,
const RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 2, true, true,
std::move(start_empty_path_class)) {
AddPairAlternativeSets(index_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;
}
const int64_t node2 = BaseNode(1);
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));
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 RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 6, true, false,
std::move(start_empty_path_class)) {
AddPairAlternativeSets(index_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 symetric.
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,
std::function<int(int64_t)> start_empty_path_class,
const RoutingIndexPairs& index_pairs)
: IntVarLocalSearchOperator(vars),
index_pairs_(index_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_ < index_pairs_.size()) {
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 int64_t insert_first =
index_pairs_[pair_index_].first[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 =
index_pairs_[pair_index_].second[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_ >= index_pairs_[pair_index_].second.size()) {
second_index_ = 0;
++first_index_;
if (first_index_ >= index_pairs_[pair_index_].first.size()) {
first_index_ = 0;
++pair_index_;
UpdateActiveNodes();
}
}
} else {
return false;
}
if (ApplyChanges(delta, deltadelta)) {
VLOG(2) << "Delta (" << DebugString() << ") = " << delta->DebugString();
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_ < index_pairs_.size()) {
for (const int64_t first : index_pairs_[pair_index_].first) {
if (Value(first) != first) {
first_active_ = first;
break;
}
}
for (const int64_t second : index_pairs_[pair_index_].second) {
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 RoutingIndexPairs& index_pairs)
: PathOperator(vars, secondary_vars, 1, true, false,
std::move(start_empty_path_class)),
inactive_node_(0) {
AddPairAlternativeSets(index_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();
}
// FilteredHeuristicLocalSearchOperator
FilteredHeuristicLocalSearchOperator::FilteredHeuristicLocalSearchOperator(
std::unique_ptr<RoutingFilteredHeuristic> heuristic,
bool keep_inverse_values)
: IntVarLocalSearchOperator(heuristic->model()->Nexts(),
keep_inverse_values),
model_(heuristic->model()),
removed_nodes_(model_->Size()),
heuristic_(std::move(heuristic)),
consider_vehicle_vars_(!model_->CostsAreHomogeneousAcrossVehicles()) {
if (consider_vehicle_vars_) {
AddVars(model_->VehicleVars());
}
}
bool FilteredHeuristicLocalSearchOperator::MakeOneNeighbor() {
while (IncrementPosition()) {
if (model_->CheckLimit()) {
// NOTE: Even though the limit is checked in the BuildSolutionFromRoutes()
// method of the heuristics, we still check it here to avoid calling
// IncrementPosition() and building a solution for every possible position
// if the time limit is reached.
return false;
}
// NOTE: No need to call RevertChanges() here as MakeChangeAndInsertNodes()
// will always return true if any change was made.
if (MakeChangesAndInsertNodes()) {
return true;
}
}
return false;
}
bool FilteredHeuristicLocalSearchOperator::MakeChangesAndInsertNodes() {
removed_nodes_.SparseClearAll();
const std::function<int64_t(int64_t)> next_accessor =
SetupNextAccessorForNeighbor();
if (next_accessor == nullptr) {
return false;
}
const Assignment* const result_assignment =
heuristic_->BuildSolutionFromRoutes(next_accessor);
if (result_assignment == nullptr) {
return false;
}
bool has_change = false;
const std::vector<IntVarElement>& elements =
result_assignment->IntVarContainer().elements();
for (int vehicle = 0; vehicle < model_->vehicles(); vehicle++) {
int64_t node_index = model_->Start(vehicle);
while (!model_->IsEnd(node_index)) {
// NOTE: When building the solution in the heuristic, Next vars are added
// to the assignment at the position corresponding to their index.
const IntVarElement& node_element = elements[node_index];
DCHECK_EQ(node_element.Var(), model_->NextVar(node_index));
const int64_t new_node_value = node_element.Value();
DCHECK_NE(new_node_value, node_index);
const int64_t vehicle_var_index = VehicleVarIndex(node_index);
if (OldValue(node_index) != new_node_value ||
(consider_vehicle_vars_ && OldValue(vehicle_var_index) != vehicle)) {
has_change = true;
SetValue(node_index, new_node_value);
if (consider_vehicle_vars_) {
SetValue(vehicle_var_index, vehicle);
}
}
node_index = new_node_value;
}
}
// Check for newly unperformed nodes among the ones removed for insertion by
// the heuristic.
for (int64_t node : removed_nodes_.PositionsSetAtLeastOnce()) {
const IntVarElement& node_element = elements[node];
DCHECK_EQ(node_element.Var(), model_->NextVar(node));
if (node_element.Value() == node) {
DCHECK_NE(OldValue(node), node);
has_change = true;
SetValue(node, node);
if (consider_vehicle_vars_) {
const int64_t vehicle_var_index = VehicleVarIndex(node);
DCHECK_NE(OldValue(vehicle_var_index), -1);
SetValue(vehicle_var_index, -1);
}
}
}
return has_change;
}
// FilteredHeuristicPathLNSOperator
FilteredHeuristicPathLNSOperator::FilteredHeuristicPathLNSOperator(
std::unique_ptr<RoutingFilteredHeuristic> heuristic)
: FilteredHeuristicLocalSearchOperator(std::move(heuristic)),
current_route_(0),
last_route_(0),
just_started_(false) {}
void FilteredHeuristicPathLNSOperator::OnStart() {
// NOTE: We set last_route_ to current_route_ here to make sure all routes
// are scanned in IncrementCurrentRouteToNextNonEmpty().
last_route_ = current_route_;
if (CurrentRouteIsEmpty()) {
IncrementCurrentRouteToNextNonEmpty();
}
just_started_ = true;
}
bool FilteredHeuristicPathLNSOperator::IncrementPosition() {
if (just_started_) {
just_started_ = false;
return !CurrentRouteIsEmpty();
}
IncrementCurrentRouteToNextNonEmpty();
return current_route_ != last_route_;
}
bool FilteredHeuristicPathLNSOperator::CurrentRouteIsEmpty() const {
return model_->IsEnd(OldValue(model_->Start(current_route_)));
}
void FilteredHeuristicPathLNSOperator::IncrementCurrentRouteToNextNonEmpty() {
const int num_routes = model_->vehicles();
do {
++current_route_ %= num_routes;
if (current_route_ == last_route_) {
// All routes have been scanned.
return;
}
} while (CurrentRouteIsEmpty());
}
std::function<int64_t(int64_t)>
FilteredHeuristicPathLNSOperator::SetupNextAccessorForNeighbor() {
const int64_t start_node = model_->Start(current_route_);
const int64_t end_node = model_->End(current_route_);
int64_t node = Value(start_node);
while (node != end_node) {
removed_nodes_.Set(node);
node = Value(node);
}
return [this, start_node, end_node](int64_t node) {
if (node == start_node) return end_node;
return Value(node);
};
}
// RelocatePathAndHeuristicInsertUnperformedOperator
RelocatePathAndHeuristicInsertUnperformedOperator::
RelocatePathAndHeuristicInsertUnperformedOperator(
std::unique_ptr<RoutingFilteredHeuristic> heuristic)
: FilteredHeuristicLocalSearchOperator(std::move(heuristic)),
route_to_relocate_index_(0),
empty_route_index_(0),
just_started_(false) {}
void RelocatePathAndHeuristicInsertUnperformedOperator::OnStart() {
has_unperformed_nodes_ = false;
last_node_on_route_.resize(model_->vehicles());
routes_to_relocate_.clear();
empty_routes_.clear();
std::vector<bool> empty_vehicle_of_vehicle_class_added(
model_->GetVehicleClassesCount(), false);
for (int64_t node = 0; node < model_->Size(); node++) {
const int64_t next = OldValue(node);
if (next == node) {
has_unperformed_nodes_ = true;
continue;
}
if (model_->IsEnd(next)) {
last_node_on_route_[model_->VehicleIndex(next)] = node;
}
}
for (int vehicle = 0; vehicle < model_->vehicles(); vehicle++) {
const int64_t next = OldValue(model_->Start(vehicle));
if (!model_->IsEnd(next)) {
routes_to_relocate_.push_back(vehicle);
continue;
}
const int vehicle_class =
model_->GetVehicleClassIndexOfVehicle(vehicle).value();
if (!empty_vehicle_of_vehicle_class_added[vehicle_class]) {
empty_routes_.push_back(vehicle);
empty_vehicle_of_vehicle_class_added[vehicle_class] = true;
}
}
if (empty_route_index_ >= empty_routes_.size()) {
empty_route_index_ = 0;
}
if (route_to_relocate_index_ >= routes_to_relocate_.size()) {
route_to_relocate_index_ = 0;
}
last_empty_route_index_ = empty_route_index_;
last_route_to_relocate_index_ = route_to_relocate_index_;
just_started_ = true;
}
bool RelocatePathAndHeuristicInsertUnperformedOperator::IncrementPosition() {
if (!has_unperformed_nodes_ || empty_routes_.empty() ||
routes_to_relocate_.empty()) {
return false;
}
if (just_started_) {
just_started_ = false;
return true;
}
return IncrementRoutes();
}
bool RelocatePathAndHeuristicInsertUnperformedOperator::IncrementRoutes() {
++empty_route_index_ %= empty_routes_.size();
if (empty_route_index_ != last_empty_route_index_) {
return true;
}
++route_to_relocate_index_ %= routes_to_relocate_.size();
return route_to_relocate_index_ != last_route_to_relocate_index_;
}
std::function<int64_t(int64_t)>
RelocatePathAndHeuristicInsertUnperformedOperator::
SetupNextAccessorForNeighbor() {
const int empty_route = empty_routes_[empty_route_index_];
const int relocated_route = routes_to_relocate_[route_to_relocate_index_];
if (model_->GetVehicleClassIndexOfVehicle(empty_route) ==
model_->GetVehicleClassIndexOfVehicle(relocated_route)) {
// Don't try to relocate the route to an empty vehicle of the same class.
return nullptr;
}
const int64_t empty_start_node = model_->Start(empty_route);
const int64_t empty_end_node = model_->End(empty_route);
const int64_t relocated_route_start = model_->Start(relocated_route);
const int64_t first_relocated_node = OldValue(relocated_route_start);
const int64_t last_relocated_node = last_node_on_route_[relocated_route];
const int64_t relocated_route_end = model_->End(relocated_route);
return [this, empty_start_node, empty_end_node, first_relocated_node,
last_relocated_node, relocated_route_start,
relocated_route_end](int64_t node) {
if (node == relocated_route_start) return relocated_route_end;
if (node == empty_start_node) return first_relocated_node;
if (node == last_relocated_node) return empty_end_node;
return Value(node);
};
}
// FilteredHeuristicCloseNodesLNSOperator
FilteredHeuristicCloseNodesLNSOperator::FilteredHeuristicCloseNodesLNSOperator(
std::unique_ptr<RoutingFilteredHeuristic> heuristic, int num_close_nodes)
: FilteredHeuristicLocalSearchOperator(std::move(heuristic),
/*keep_inverse_values*/ true),
pickup_delivery_pairs_(model_->GetPickupAndDeliveryPairs()),
current_node_(0),
last_node_(0),
close_nodes_(model_->Size()),
new_nexts_(model_->Size()),
changed_nexts_(model_->Size()),
new_prevs_(model_->Size()),
changed_prevs_(model_->Size()) {
const int64_t size = model_->Size();
const int64_t max_num_neighbors =
std::max<int64_t>(0, size - 1 - model_->vehicles());
const int64_t num_closest_neighbors =
std::min<int64_t>(num_close_nodes, max_num_neighbors);
DCHECK_GE(num_closest_neighbors, 0);
if (num_closest_neighbors == 0) return;
const int64_t num_cost_classes = model_->GetCostClassesCount();
for (int64_t node = 0; node < size; node++) {
if (model_->IsStart(node) || model_->IsEnd(node)) continue;
std::vector<std::pair</*cost*/ double, /*node*/ int64_t>>
costed_after_nodes;
costed_after_nodes.reserve(size);
for (int64_t after_node = 0; after_node < size; after_node++) {
if (model_->IsStart(after_node) || model_->IsEnd(after_node) ||
after_node == node) {
continue;
}
double total_cost = 0.0;
// NOTE: We don't consider the 'always-zero' cost class when searching for
// closest neighbors.
for (int cost_class = 1; cost_class < num_cost_classes; cost_class++) {
total_cost += model_->GetArcCostForClass(node, after_node, cost_class);
}
costed_after_nodes.emplace_back(total_cost, after_node);
}
std::nth_element(costed_after_nodes.begin(),
costed_after_nodes.begin() + num_closest_neighbors - 1,
costed_after_nodes.end());
std::vector<int64_t>& neighbors = close_nodes_[node];
neighbors.reserve(num_closest_neighbors);
for (int index = 0; index < num_closest_neighbors; index++) {
neighbors.push_back(costed_after_nodes[index].second);
}
}
}
void FilteredHeuristicCloseNodesLNSOperator::OnStart() {
last_node_ = current_node_;
just_started_ = true;
}
bool FilteredHeuristicCloseNodesLNSOperator::IncrementPosition() {
if (just_started_) {
just_started_ = false;
return true;
}
++current_node_ %= model_->Size();
return current_node_ != last_node_;
}