forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_search.cc
4369 lines (3966 loc) · 154 KB
/
local_search.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-2018 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 <algorithm>
#include <iterator>
#include <map>
#include <memory>
#include <numeric>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/random/distributions.h"
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/iterator_adaptors.h"
#include "ortools/base/logging.h"
#include "ortools/base/macros.h"
#include "ortools/base/map_util.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/graph/hamiltonian_path.h"
#include "ortools/util/saturated_arithmetic.h"
DEFINE_int32(cp_local_search_sync_frequency, 16,
"Frequency of checks for better solutions in the solution pool.");
DEFINE_int32(cp_local_search_tsp_opt_size, 13,
"Size of TSPs solved in the TSPOpt operator.");
DEFINE_int32(cp_local_search_tsp_lns_size, 10,
"Size of TSPs solved in the TSPLns operator.");
DEFINE_bool(cp_use_empty_path_symmetry_breaker, true,
"If true, equivalent empty paths are removed from the neighborhood "
"of PathOperators");
namespace operations_research {
// Utility methods to ensure the communication between local search and the
// search.
// Returns true if a local optimum has been reached and cannot be improved.
bool LocalOptimumReached(Search* const search);
// Returns true if the search accepts the delta (actually checking this by
// calling AcceptDelta on the monitors of the search).
bool AcceptDelta(Search* const search, Assignment* delta,
Assignment* deltadelta);
// Notifies the search that a neighbor has been accepted by local search.
void AcceptNeighbor(Search* const search);
void AcceptUncheckedNeighbor(Search* const search);
// ----- Base operator class for operators manipulating IntVars -----
bool IntVarLocalSearchOperator::MakeNextNeighbor(Assignment* delta,
Assignment* deltadelta) {
CHECK(delta != nullptr);
VLOG(2) << DebugString() << "::MakeNextNeighbor(delta=("
<< delta->DebugString() << "), deltadelta=("
<< (deltadelta ? deltadelta->DebugString() : std::string("nullptr"));
while (true) {
RevertChanges(true);
if (!MakeOneNeighbor()) {
return false;
}
if (ApplyChanges(delta, deltadelta)) {
VLOG(2) << "Delta (" << DebugString() << ") = " << delta->DebugString();
return true;
}
}
return false;
}
// TODO(user): Make this a pure virtual.
bool IntVarLocalSearchOperator::MakeOneNeighbor() { return true; }
// ----- Base Large Neighborhood Search operator -----
BaseLns::BaseLns(const std::vector<IntVar*>& vars)
: IntVarLocalSearchOperator(vars) {}
BaseLns::~BaseLns() {}
bool BaseLns::MakeOneNeighbor() {
fragment_.clear();
if (NextFragment()) {
for (int candidate : fragment_) {
Deactivate(candidate);
}
return true;
} else {
return false;
}
}
void BaseLns::OnStart() { InitFragments(); }
void BaseLns::InitFragments() {}
void BaseLns::AppendToFragment(int index) {
if (index >= 0 && index < Size()) {
fragment_.push_back(index);
}
}
int BaseLns::FragmentSize() const { return fragment_.size(); }
// ----- Simple Large Neighborhood Search operator -----
// Frees number_of_variables (contiguous in vars) variables.
namespace {
class SimpleLns : public BaseLns {
public:
SimpleLns(const std::vector<IntVar*>& vars, int number_of_variables)
: BaseLns(vars), index_(0), number_of_variables_(number_of_variables) {
CHECK_GT(number_of_variables_, 0);
}
~SimpleLns() override {}
void InitFragments() override { index_ = 0; }
bool NextFragment() override;
std::string DebugString() const override { return "SimpleLns"; }
private:
int index_;
const int number_of_variables_;
};
bool SimpleLns::NextFragment() {
const int size = Size();
if (index_ < size) {
for (int i = index_; i < index_ + number_of_variables_; ++i) {
AppendToFragment(i % size);
}
++index_;
return true;
} else {
return false;
}
}
// ----- Random Large Neighborhood Search operator -----
// Frees up to number_of_variables random variables.
class RandomLns : public BaseLns {
public:
RandomLns(const std::vector<IntVar*>& vars, int number_of_variables,
int32 seed)
: BaseLns(vars), rand_(seed), number_of_variables_(number_of_variables) {
CHECK_GT(number_of_variables_, 0);
CHECK_LE(number_of_variables_, Size());
}
~RandomLns() override {}
bool NextFragment() override;
std::string DebugString() const override { return "RandomLns"; }
private:
std::mt19937 rand_;
const int number_of_variables_;
};
bool RandomLns::NextFragment() {
DCHECK_GT(Size(), 0);
for (int i = 0; i < number_of_variables_; ++i) {
AppendToFragment(absl::Uniform<int>(rand_, 0, Size()));
}
return true;
}
} // namespace
LocalSearchOperator* Solver::MakeRandomLnsOperator(
const std::vector<IntVar*>& vars, int number_of_variables) {
return MakeRandomLnsOperator(vars, number_of_variables, CpRandomSeed());
}
LocalSearchOperator* Solver::MakeRandomLnsOperator(
const std::vector<IntVar*>& vars, int number_of_variables, int32 seed) {
return RevAlloc(new RandomLns(vars, number_of_variables, seed));
}
// ----- Move Toward Target Local Search operator -----
// A local search operator that compares the current assignment with a target
// one, and that generates neighbors corresponding to a single variable being
// changed from its current value to its target value.
namespace {
class MoveTowardTargetLS : public IntVarLocalSearchOperator {
public:
MoveTowardTargetLS(const std::vector<IntVar*>& variables,
const std::vector<int64>& target_values)
: IntVarLocalSearchOperator(variables),
target_(target_values),
// Initialize variable_index_ at the number of the of variables minus
// one, so that the first to be tried (after one increment) is the one
// of index 0.
variable_index_(Size() - 1) {
CHECK_EQ(target_values.size(), variables.size()) << "Illegal arguments.";
}
~MoveTowardTargetLS() override {}
std::string DebugString() const override { return "MoveTowardTargetLS"; }
protected:
// Make a neighbor assigning one variable to its target value.
bool MakeOneNeighbor() override {
while (num_var_since_last_start_ < Size()) {
++num_var_since_last_start_;
variable_index_ = (variable_index_ + 1) % Size();
const int64 target_value = target_.at(variable_index_);
const int64 current_value = OldValue(variable_index_);
if (current_value != target_value) {
SetValue(variable_index_, target_value);
return true;
}
}
return false;
}
private:
void OnStart() override {
// Do not change the value of variable_index_: this way, we keep going from
// where we last modified something. This is because we expect that most
// often, the variables we have just checked are less likely to be able
// to be changed to their target values than the ones we have not yet
// checked.
//
// Consider the case where oddly indexed variables can be assigned to their
// target values (no matter in what order they are considered), while even
// indexed ones cannot. Restarting at index 0 each time an odd-indexed
// variable is modified will cause a total of Theta(n^2) neighbors to be
// generated, while not restarting will produce only Theta(n) neighbors.
CHECK_GE(variable_index_, 0);
CHECK_LT(variable_index_, Size());
num_var_since_last_start_ = 0;
}
// Target values
const std::vector<int64> target_;
// Index of the next variable to try to restore
int64 variable_index_;
// Number of variables checked since the last call to OnStart().
int64 num_var_since_last_start_;
};
} // namespace
LocalSearchOperator* Solver::MakeMoveTowardTargetOperator(
const Assignment& target) {
typedef std::vector<IntVarElement> Elements;
const Elements& elements = target.IntVarContainer().elements();
// Copy target values and construct the vector of variables
std::vector<IntVar*> vars;
std::vector<int64> values;
vars.reserve(target.NumIntVars());
values.reserve(target.NumIntVars());
for (const auto& it : elements) {
vars.push_back(it.Var());
values.push_back(it.Value());
}
return MakeMoveTowardTargetOperator(vars, values);
}
LocalSearchOperator* Solver::MakeMoveTowardTargetOperator(
const std::vector<IntVar*>& variables,
const std::vector<int64>& target_values) {
return RevAlloc(new MoveTowardTargetLS(variables, target_values));
}
// ----- ChangeValue Operators -----
ChangeValue::ChangeValue(const std::vector<IntVar*>& vars)
: IntVarLocalSearchOperator(vars), index_(0) {}
ChangeValue::~ChangeValue() {}
bool ChangeValue::MakeOneNeighbor() {
const int size = Size();
while (index_ < size) {
const int64 value = ModifyValue(index_, Value(index_));
SetValue(index_, value);
++index_;
return true;
}
return false;
}
void ChangeValue::OnStart() { index_ = 0; }
// Increments the current value of variables.
namespace {
class IncrementValue : public ChangeValue {
public:
explicit IncrementValue(const std::vector<IntVar*>& vars)
: ChangeValue(vars) {}
~IncrementValue() override {}
int64 ModifyValue(int64 index, int64 value) override { return value + 1; }
std::string DebugString() const override { return "IncrementValue"; }
};
// Decrements the current value of variables.
class DecrementValue : public ChangeValue {
public:
explicit DecrementValue(const std::vector<IntVar*>& vars)
: ChangeValue(vars) {}
~DecrementValue() override {}
int64 ModifyValue(int64 index, int64 value) override { return value - 1; }
std::string DebugString() const override { return "DecrementValue"; }
};
} // namespace
// ----- Path-based Operators -----
PathOperator::PathOperator(const std::vector<IntVar*>& next_vars,
const std::vector<IntVar*>& path_vars,
int number_of_base_nodes,
bool skip_locally_optimal_paths,
bool accept_path_end_base,
std::function<int(int64)> start_empty_path_class)
: IntVarLocalSearchOperator(next_vars, true),
number_of_nexts_(next_vars.size()),
ignore_path_vars_(path_vars.empty()),
next_base_to_increment_(number_of_base_nodes),
base_nodes_(number_of_base_nodes),
base_alternatives_(number_of_base_nodes),
base_sibling_alternatives_(number_of_base_nodes),
end_nodes_(number_of_base_nodes),
base_paths_(number_of_base_nodes),
just_started_(false),
first_start_(true),
accept_path_end_base_(accept_path_end_base),
start_empty_path_class_(std::move(start_empty_path_class)),
skip_locally_optimal_paths_(skip_locally_optimal_paths),
optimal_paths_enabled_(false),
alternative_index_(next_vars.size(), -1) {
DCHECK_GT(number_of_base_nodes, 0);
if (!ignore_path_vars_) {
AddVars(path_vars);
}
path_basis_.push_back(0);
for (int i = 1; i < base_nodes_.size(); ++i) {
if (!OnSamePathAsPreviousBase(i)) path_basis_.push_back(i);
}
if ((path_basis_.size() > 2) ||
(!next_vars.empty() && !next_vars.back()
->solver()
->parameters()
.skip_locally_optimal_paths())) {
skip_locally_optimal_paths_ = false;
}
}
void PathOperator::Reset() { optimal_paths_.clear(); }
void PathOperator::OnStart() {
optimal_paths_enabled_ = false;
InitializeBaseNodes();
InitializeAlternatives();
OnNodeInitialization();
}
bool PathOperator::MakeOneNeighbor() {
while (IncrementPosition()) {
// Need to revert changes here since MakeNeighbor might have returned false
// and have done changes in the previous iteration.
RevertChanges(true);
if (MakeNeighbor()) {
return true;
}
}
return false;
}
bool PathOperator::SkipUnchanged(int index) const {
if (ignore_path_vars_) {
return true;
}
if (index < number_of_nexts_) {
int path_index = index + number_of_nexts_;
return Value(path_index) == OldValue(path_index);
} else {
int next_index = index - number_of_nexts_;
return Value(next_index) == OldValue(next_index);
}
}
bool PathOperator::MoveChain(int64 before_chain, int64 chain_end,
int64 destination) {
if (destination == before_chain || destination == chain_end) return false;
DCHECK(CheckChainValidity(before_chain, chain_end, destination) &&
!IsPathEnd(chain_end) && !IsPathEnd(destination));
const int64 destination_path = Path(destination);
const int64 after_chain = Next(chain_end);
SetNext(chain_end, Next(destination), destination_path);
if (!ignore_path_vars_) {
int current = destination;
int next = Next(before_chain);
while (current != chain_end) {
SetNext(current, next, destination_path);
current = next;
next = Next(next);
}
} else {
SetNext(destination, Next(before_chain), destination_path);
}
SetNext(before_chain, after_chain, Path(before_chain));
return true;
}
bool PathOperator::ReverseChain(int64 before_chain, int64 after_chain,
int64* chain_last) {
if (CheckChainValidity(before_chain, after_chain, -1)) {
int64 path = Path(before_chain);
int64 current = Next(before_chain);
if (current == after_chain) {
return false;
}
int64 current_next = Next(current);
SetNext(current, after_chain, path);
while (current_next != after_chain) {
const int64 next = Next(current_next);
SetNext(current_next, current, path);
current = current_next;
current_next = next;
}
SetNext(before_chain, current, path);
*chain_last = current;
return true;
}
return false;
}
bool PathOperator::MakeActive(int64 node, int64 destination) {
if (!IsPathEnd(destination)) {
int64 destination_path = Path(destination);
SetNext(node, Next(destination), destination_path);
SetNext(destination, node, destination_path);
return true;
} else {
return false;
}
}
bool PathOperator::MakeChainInactive(int64 before_chain, int64 chain_end) {
const int64 kNoPath = -1;
if (CheckChainValidity(before_chain, chain_end, -1) &&
!IsPathEnd(chain_end)) {
const int64 after_chain = Next(chain_end);
int64 current = Next(before_chain);
while (current != after_chain) {
const int64 next = Next(current);
SetNext(current, current, kNoPath);
current = next;
}
SetNext(before_chain, after_chain, Path(before_chain));
return true;
}
return false;
}
bool PathOperator::SwapActiveAndInactive(int64 active, int64 inactive) {
if (active == inactive) return false;
const int64 prev = Prev(active);
return MakeChainInactive(prev, active) && MakeActive(inactive, prev);
}
bool PathOperator::IncrementPosition() {
const int base_node_size = base_nodes_.size();
if (!just_started_) {
const int number_of_paths = path_starts_.size();
// Finding next base node positions.
// Increment the position of inner base nodes first (higher index nodes);
// if a base node is at the end of a path, reposition it at the start
// of the path and increment the position of the preceding base node (this
// action is called a restart).
int last_restarted = base_node_size;
for (int i = base_node_size - 1; i >= 0; --i) {
if (base_nodes_[i] < number_of_nexts_ && i <= next_base_to_increment_) {
if (ConsiderAlternatives(i)) {
// Iterate on sibling alternatives.
const int sibling_alternative_index =
GetSiblingAlternativeIndex(base_nodes_[i]);
if (sibling_alternative_index >= 0) {
if (base_sibling_alternatives_[i] <
alternative_sets_[sibling_alternative_index].size() - 1) {
++base_sibling_alternatives_[i];
break;
} else {
base_sibling_alternatives_[i] = 0;
}
}
// Iterate on base alternatives.
const int alternative_index = alternative_index_[base_nodes_[i]];
if (alternative_index >= 0) {
if (base_alternatives_[i] <
alternative_sets_[alternative_index].size() - 1) {
++base_alternatives_[i];
break;
} else {
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
}
}
}
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
base_nodes_[i] = OldNext(base_nodes_[i]);
if (accept_path_end_base_ || !IsPathEnd(base_nodes_[i])) break;
}
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
base_nodes_[i] = StartNode(i);
last_restarted = i;
}
next_base_to_increment_ = base_node_size;
// At the end of the loop, base nodes with indexes in
// [last_restarted, base_node_size[ have been restarted.
// Restarted base nodes are then repositioned by the virtual
// GetBaseNodeRestartPosition to reflect position constraints between
// base nodes (by default GetBaseNodeRestartPosition leaves the nodes
// at the start of the path).
// Base nodes are repositioned in ascending order to ensure that all
// base nodes "below" the node being repositioned have their final
// position.
for (int i = last_restarted; i < base_node_size; ++i) {
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
base_nodes_[i] = GetBaseNodeRestartPosition(i);
}
if (last_restarted > 0) {
return CheckEnds();
}
// If all base nodes have been restarted, base nodes are moved to new paths.
// First we mark the current paths as locally optimal if they have been
// completely explored.
if (optimal_paths_enabled_ && skip_locally_optimal_paths_) {
if (path_basis_.size() > 1) {
for (int i = 1; i < path_basis_.size(); ++i) {
optimal_paths_[num_paths_ *
start_to_path_[StartNode(path_basis_[i - 1])] +
start_to_path_[StartNode(path_basis_[i])]] = true;
}
} else {
optimal_paths_[num_paths_ * start_to_path_[StartNode(path_basis_[0])] +
start_to_path_[StartNode(path_basis_[0])]] = true;
}
}
std::vector<int> current_starts(base_node_size);
for (int i = 0; i < base_node_size; ++i) {
current_starts[i] = StartNode(i);
}
// Exploration of next paths can lead to locally optimal paths since we are
// exploring them from scratch.
optimal_paths_enabled_ = true;
while (true) {
for (int i = base_node_size - 1; i >= 0; --i) {
const int next_path_index = base_paths_[i] + 1;
if (next_path_index < number_of_paths) {
base_paths_[i] = next_path_index;
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
base_nodes_[i] = path_starts_[next_path_index];
if (i == 0 || !OnSamePathAsPreviousBase(i)) {
break;
}
} else {
base_paths_[i] = 0;
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
base_nodes_[i] = path_starts_[0];
}
}
if (!skip_locally_optimal_paths_) return CheckEnds();
// If the new paths have already been completely explored, we can
// skip them from now on.
if (path_basis_.size() > 1) {
for (int j = 1; j < path_basis_.size(); ++j) {
if (!optimal_paths_[num_paths_ * start_to_path_[StartNode(
path_basis_[j - 1])] +
start_to_path_[StartNode(path_basis_[j])]]) {
return CheckEnds();
}
}
} else {
if (!optimal_paths_[num_paths_ *
start_to_path_[StartNode(path_basis_[0])] +
start_to_path_[StartNode(path_basis_[0])]]) {
return CheckEnds();
}
}
// If we are back to paths we just iterated on or have reached the end
// of the neighborhood search space, we can stop.
if (!CheckEnds()) return false;
bool stop = true;
for (int i = 0; i < base_node_size; ++i) {
if (StartNode(i) != current_starts[i]) {
stop = false;
break;
}
}
if (stop) return false;
}
} else {
just_started_ = false;
return true;
}
return CheckEnds();
}
void PathOperator::InitializePathStarts() {
// Detect nodes which do not have any possible predecessor in a path; these
// nodes are path starts.
int max_next = -1;
std::vector<bool> has_prevs(number_of_nexts_, false);
for (int i = 0; i < number_of_nexts_; ++i) {
const int next = OldNext(i);
if (next < number_of_nexts_) {
has_prevs[next] = true;
}
max_next = std::max(max_next, next);
}
// Update locally optimal paths.
if (optimal_paths_.empty() && skip_locally_optimal_paths_) {
num_paths_ = 0;
start_to_path_.clear();
start_to_path_.resize(number_of_nexts_, -1);
for (int i = 0; i < number_of_nexts_; ++i) {
if (!has_prevs[i]) {
start_to_path_[i] = num_paths_;
++num_paths_;
}
}
optimal_paths_.resize(num_paths_ * num_paths_, false);
}
if (skip_locally_optimal_paths_) {
for (int i = 0; i < number_of_nexts_; ++i) {
if (!has_prevs[i]) {
int current = i;
while (!IsPathEnd(current)) {
if ((OldNext(current) != prev_values_[current])) {
for (int j = 0; j < num_paths_; ++j) {
optimal_paths_[num_paths_ * start_to_path_[i] + j] = false;
optimal_paths_[num_paths_ * j + start_to_path_[i]] = false;
}
break;
}
current = OldNext(current);
}
}
}
}
// Create a list of path starts, dropping equivalent path starts of
// currently empty paths.
std::vector<bool> empty_found(number_of_nexts_, false);
std::vector<int64> new_path_starts;
const bool use_empty_path_symmetry_breaker =
FLAGS_cp_use_empty_path_symmetry_breaker;
for (int i = 0; i < number_of_nexts_; ++i) {
if (!has_prevs[i]) {
if (use_empty_path_symmetry_breaker && IsPathEnd(OldNext(i))) {
if (start_empty_path_class_ != nullptr) {
if (empty_found[start_empty_path_class_(i)]) {
continue;
} else {
empty_found[start_empty_path_class_(i)] = true;
}
}
}
new_path_starts.push_back(i);
}
}
if (!first_start_) {
// Synchronizing base_paths_ with base node positions. When the last move
// was performed a base node could have been moved to a new route in which
// case base_paths_ needs to be updated. This needs to be done on the path
// starts before we re-adjust base nodes for new path starts.
std::vector<int> node_paths(max_next + 1, -1);
for (int i = 0; i < path_starts_.size(); ++i) {
int node = path_starts_[i];
while (!IsPathEnd(node)) {
node_paths[node] = i;
node = OldNext(node);
}
node_paths[node] = i;
}
for (int j = 0; j < base_nodes_.size(); ++j) {
// Always restart from first alternative.
base_alternatives_[j] = 0;
base_sibling_alternatives_[j] = 0;
if (IsInactive(base_nodes_[j]) || node_paths[base_nodes_[j]] == -1) {
// Base node was made inactive or was moved to a new path, reposition
// the base node to the start of the path on which it was.
base_nodes_[j] = path_starts_[base_paths_[j]];
} else {
base_paths_[j] = node_paths[base_nodes_[j]];
}
}
// Re-adjust current base_nodes and base_paths to take into account new
// path starts (there could be fewer if a new path was made empty, or more
// if nodes were added to a formerly empty path).
int new_index = 0;
absl::flat_hash_set<int> found_bases;
for (int i = 0; i < path_starts_.size(); ++i) {
int index = new_index;
// Note: old and new path starts are sorted by construction.
while (index < new_path_starts.size() &&
new_path_starts[index] < path_starts_[i]) {
++index;
}
const bool found = (index < new_path_starts.size() &&
new_path_starts[index] == path_starts_[i]);
if (found) {
new_index = index;
}
for (int j = 0; j < base_nodes_.size(); ++j) {
if (base_paths_[j] == i && !gtl::ContainsKey(found_bases, j)) {
found_bases.insert(j);
base_paths_[j] = new_index;
// If the current position of the base node is a removed empty path,
// readjusting it to the last visited path start.
if (!found) {
base_nodes_[j] = new_path_starts[new_index];
}
}
}
}
}
path_starts_.swap(new_path_starts);
}
void PathOperator::InitializeInactives() {
inactives_.clear();
for (int i = 0; i < number_of_nexts_; ++i) {
inactives_.push_back(OldNext(i) == i);
}
}
void PathOperator::InitializeBaseNodes() {
// Inactive nodes must be detected before determining new path starts.
InitializeInactives();
InitializePathStarts();
if (first_start_ || InitPosition()) {
// Only do this once since the following starts will continue from the
// preceding position
for (int i = 0; i < base_nodes_.size(); ++i) {
base_paths_[i] = 0;
base_nodes_[i] = path_starts_[0];
}
first_start_ = false;
}
for (int i = 0; i < base_nodes_.size(); ++i) {
// If base node has been made inactive, restart from path start.
int64 base_node = base_nodes_[i];
if (RestartAtPathStartOnSynchronize() || IsInactive(base_node)) {
base_node = path_starts_[base_paths_[i]];
base_nodes_[i] = base_node;
}
end_nodes_[i] = base_node;
}
// Repair end_nodes_ in case some must be on the same path and are not anymore
// (due to other operators moving these nodes).
for (int i = 1; i < base_nodes_.size(); ++i) {
if (OnSamePathAsPreviousBase(i) &&
!OnSamePath(base_nodes_[i - 1], base_nodes_[i])) {
const int64 base_node = base_nodes_[i - 1];
base_nodes_[i] = base_node;
end_nodes_[i] = base_node;
base_paths_[i] = base_paths_[i - 1];
}
}
for (int i = 0; i < base_nodes_.size(); ++i) {
base_alternatives_[i] = 0;
base_sibling_alternatives_[i] = 0;
}
just_started_ = true;
}
void PathOperator::InitializeAlternatives() {
active_in_alternative_set_.resize(alternative_sets_.size(), -1);
for (int i = 0; i < alternative_sets_.size(); ++i) {
const int64 current_active = active_in_alternative_set_[i];
if (current_active >= 0 && !IsInactive(current_active)) continue;
for (int64 index : alternative_sets_[i]) {
if (!IsInactive(index)) {
active_in_alternative_set_[i] = index;
break;
}
}
}
}
bool PathOperator::OnSamePath(int64 node1, int64 node2) const {
if (IsInactive(node1) != IsInactive(node2)) {
return false;
}
for (int node = node1; !IsPathEnd(node); node = OldNext(node)) {
if (node == node2) {
return true;
}
}
for (int node = node2; !IsPathEnd(node); node = OldNext(node)) {
if (node == node1) {
return true;
}
}
return false;
}
// Rejects chain if chain_end is not after before_chain on the path or if
// the chain contains exclude. Given before_chain is the node before the
// chain, if before_chain and chain_end are the same the chain is rejected too.
// Also rejects cycles (cycle detection is detected through chain length
// overflow).
bool PathOperator::CheckChainValidity(int64 before_chain, int64 chain_end,
int64 exclude) const {
if (before_chain == chain_end || before_chain == exclude) return false;
int64 current = before_chain;
int chain_size = 0;
while (current != chain_end) {
if (chain_size > number_of_nexts_) {
return false;
}
if (IsPathEnd(current)) {
return false;
}
current = Next(current);
++chain_size;
if (current == exclude) {
return false;
}
}
return true;
}
// ----- 2Opt -----
// Reverses a sub-chain of a path. It is called 2Opt because it breaks
// 2 arcs on the path; resulting paths are called 2-optimal.
// Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5
// (where (1, 5) are first and last nodes of the path and can therefore not be
// moved):
// 1 -> 3 -> 2 -> 4 -> 5
// 1 -> 4 -> 3 -> 2 -> 5
// 1 -> 2 -> 4 -> 3 -> 5
class TwoOpt : public PathOperator {
public:
TwoOpt(const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class)
: PathOperator(vars, secondary_vars, 2, true, true,
std::move(start_empty_path_class)),
last_base_(-1),
last_(-1) {}
~TwoOpt() override {}
bool MakeNeighbor() override;
bool IsIncremental() const override { return true; }
std::string DebugString() const override { return "TwoOpt"; }
protected:
bool OnSamePathAsPreviousBase(int64 base_index) override {
// Both base nodes have to be on the same path.
return true;
}
int64 GetBaseNodeRestartPosition(int base_index) override {
return (base_index == 0) ? StartNode(0) : BaseNode(0);
}
private:
void OnNodeInitialization() override { last_ = -1; }
int64 last_base_;
int64 last_;
};
bool TwoOpt::MakeNeighbor() {
DCHECK_EQ(StartNode(0), StartNode(1));
if (last_base_ != BaseNode(0) || last_ == -1) {
RevertChanges(false);
if (IsPathEnd(BaseNode(0))) {
last_ = -1;
return false;
}
last_base_ = BaseNode(0);
last_ = Next(BaseNode(0));
int64 chain_last;
if (ReverseChain(BaseNode(0), BaseNode(1), &chain_last)
// Check there are more than one node in the chain (reversing a
// single node is a NOP).
&& last_ != chain_last) {
return true;
} else {
last_ = -1;
return false;
}
} else {
const int64 to_move = Next(last_);
DCHECK_EQ(Next(to_move), BaseNode(1));
return MoveChain(last_, to_move, BaseNode(0));
}
}
// ----- Relocate -----
// Moves a sub-chain of a path to another position; the specified chain length
// is the fixed length of the chains being moved. When this length is 1 the
// operator simply moves a node to another position.
// Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5, for a chain length
// of 2 (where (1, 5) are first and last nodes of the path and can
// therefore not be moved):
// 1 -> 4 -> 2 -> 3 -> 5
// 1 -> 3 -> 4 -> 2 -> 5
//
// Using Relocate with chain lengths of 1, 2 and 3 together is equivalent to
// the OrOpt operator on a path. The OrOpt operator is a limited version of
// 3Opt (breaks 3 arcs on a path).
class Relocate : public PathOperator {
public:
Relocate(const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars, const std::string& name,
std::function<int(int64)> start_empty_path_class,
int64 chain_length = 1LL, bool single_path = false)
: PathOperator(vars, secondary_vars, 2, true, false,
std::move(start_empty_path_class)),
chain_length_(chain_length),
single_path_(single_path),
name_(name) {
CHECK_GT(chain_length_, 0);
}
Relocate(const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
int64 chain_length = 1LL, bool single_path = false)
: Relocate(vars, secondary_vars,
absl::StrCat("Relocate<", chain_length, ">"),
std::move(start_empty_path_class), chain_length, single_path) {
}
~Relocate() override {}
bool MakeNeighbor() override;
std::string DebugString() const override { return name_; }
protected:
bool OnSamePathAsPreviousBase(int64 base_index) override {
// Both base nodes have to be on the same path when it's the single path
// version.
return single_path_;
}
private:
const int64 chain_length_;
const bool single_path_;
const std::string name_;
};
bool Relocate::MakeNeighbor() {
DCHECK(!single_path_ || StartNode(0) == StartNode(1));
const int64 destination = BaseNode(1);
DCHECK(!IsPathEnd(destination));
const int64 before_chain = BaseNode(0);
int64 chain_end = before_chain;
for (int i = 0; i < chain_length_; ++i) {
if (IsPathEnd(chain_end) || chain_end == destination) {
return false;
}
chain_end = Next(chain_end);
}
return !IsPathEnd(chain_end) &&
MoveChain(before_chain, chain_end, destination);
}