forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraint_solveri.h
3483 lines (3070 loc) · 125 KB
/
constraint_solveri.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2022 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Collection of objects used to extend the Constraint Solver library.
///
/// This file contains a set of objects that simplifies writing extensions
/// of the library.
///
/// The main objects that define extensions are:
/// - BaseIntExpr, the base class of all expressions that are not variables.
/// - SimpleRevFIFO, a reversible FIFO list with templatized values.
/// A reversible data structure is a data structure that reverts its
/// modifications when the search is going up in the search tree, usually
/// after a failure occurs.
/// - RevImmutableMultiMap, a reversible immutable multimap.
/// - MakeConstraintDemon<n> and MakeDelayedConstraintDemon<n> to wrap methods
/// of a constraint as a demon.
/// - RevSwitch, a reversible flip-once switch.
/// - SmallRevBitSet, RevBitSet, and RevBitMatrix: reversible 1D or 2D
/// bitsets.
/// - LocalSearchOperator, IntVarLocalSearchOperator, ChangeValue and
/// PathOperator, to create new local search operators.
/// - LocalSearchFilter and IntVarLocalSearchFilter, to create new local
/// search filters.
/// - BaseLns, to write Large Neighborhood Search operators.
/// - SymmetryBreaker, to describe model symmetries that will be broken during
/// search using the 'Symmetry Breaking During Search' framework
/// see Gent, I. P., Harvey, W., & Kelsey, T. (2002).
/// Groups and Constraints: Symmetry Breaking During Search.
/// Principles and Practice of Constraint Programming CP2002
/// (Vol. 2470, pp. 415-430). Springer. Retrieved from
/// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.11.1442.
///
/// Then, there are some internal classes that are used throughout the solver
/// and exposed in this file:
/// - SearchLog, the root class of all periodic outputs during search.
/// - ModelCache, A caching layer to avoid creating twice the same object.
#ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVERI_H_
#define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVERI_H_
#include <stdint.h>
#include <string.h>
#include <algorithm>
#include <functional>
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/timer.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/util/bitset.h"
#include "ortools/util/tuple_set.h"
namespace operations_research {
/// This is the base class for all expressions that are not variables.
/// It provides a basic 'CastToVar()' implementation.
///
/// The class of expressions represent two types of objects: variables
/// and subclasses of BaseIntExpr. Variables are stateful objects that
/// provide a rich API (remove values, WhenBound...). On the other hand,
/// subclasses of BaseIntExpr represent range-only stateless objects.
/// That is, min(A + B) is recomputed each time as min(A) + min(B).
///
/// Furthermore, sometimes, the propagation on an expression is not complete,
/// and Min(), Max() are not monotonic with respect to SetMin() and SetMax().
/// For instance, if A is a var with domain [0 .. 5], and B another variable
/// with domain [0 .. 5], then Plus(A, B) has domain [0, 10].
///
/// If we apply SetMax(Plus(A, B), 4)), we will deduce that both A
/// and B have domain [0 .. 4]. In that case, Max(Plus(A, B)) is 8
/// and not 4. To get back monotonicity, we 'cast' the expression
/// into a variable using the Var() method (that will call CastToVar()
/// internally). The resulting variable will be stateful and monotonic.
///
/// Finally, one should never store a pointer to a IntExpr, or
/// BaseIntExpr in the code. The safe code should always call Var() on an
/// expression built by the solver, and store the object as an IntVar*.
/// This is a consequence of the stateless nature of the expressions that
/// makes the code error-prone.
class LocalSearchMonitor;
class BaseIntExpr : public IntExpr {
public:
explicit BaseIntExpr(Solver* const s) : IntExpr(s), var_(nullptr) {}
~BaseIntExpr() override {}
IntVar* Var() override;
virtual IntVar* CastToVar();
private:
IntVar* var_;
};
/// This enum is used internally to do dynamic typing on subclasses of integer
/// variables.
enum VarTypes {
UNSPECIFIED,
DOMAIN_INT_VAR,
BOOLEAN_VAR,
CONST_VAR,
VAR_ADD_CST,
VAR_TIMES_CST,
CST_SUB_VAR,
OPP_VAR,
TRACE_VAR
};
/// This class represent a reversible FIFO structure.
/// The main difference w.r.t a standard FIFO structure is that a Solver is
/// given as parameter to the modifiers such that the solver can store the
/// backtrack information
/// Iterator's traversing order should not be changed, as some algorithm
/// depend on it to be consistent.
/// It's main use is to store a list of demons in the various classes of
/// variables.
#ifndef SWIG
template <class T>
class SimpleRevFIFO {
private:
enum { CHUNK_SIZE = 16 }; // TODO(user): could be an extra template param
struct Chunk {
T data_[CHUNK_SIZE];
const Chunk* const next_;
explicit Chunk(const Chunk* next) : next_(next) {}
};
public:
/// This iterator is not stable with respect to deletion.
class Iterator {
public:
explicit Iterator(const SimpleRevFIFO<T>* l)
: chunk_(l->chunks_), value_(l->Last()) {}
bool ok() const { return (value_ != nullptr); }
T operator*() const { return *value_; }
void operator++() {
++value_;
if (value_ == chunk_->data_ + CHUNK_SIZE) {
chunk_ = chunk_->next_;
value_ = chunk_ ? chunk_->data_ : nullptr;
}
}
private:
const Chunk* chunk_;
const T* value_;
};
SimpleRevFIFO() : chunks_(nullptr), pos_(0) {}
void Push(Solver* const s, T val) {
if (pos_.Value() == 0) {
Chunk* const chunk = s->UnsafeRevAlloc(new Chunk(chunks_));
s->SaveAndSetValue(reinterpret_cast<void**>(&chunks_),
reinterpret_cast<void*>(chunk));
pos_.SetValue(s, CHUNK_SIZE - 1);
} else {
pos_.Decr(s);
}
chunks_->data_[pos_.Value()] = val;
}
/// Pushes the var on top if is not a duplicate of the current top object.
void PushIfNotTop(Solver* const s, T val) {
if (chunks_ == nullptr || LastValue() != val) {
Push(s, val);
}
}
/// Returns the last item of the FIFO.
const T* Last() const {
return chunks_ ? &chunks_->data_[pos_.Value()] : nullptr;
}
T* MutableLast() { return chunks_ ? &chunks_->data_[pos_.Value()] : nullptr; }
/// Returns the last value in the FIFO.
const T& LastValue() const {
DCHECK(chunks_);
return chunks_->data_[pos_.Value()];
}
/// Sets the last value in the FIFO.
void SetLastValue(const T& v) {
DCHECK(Last());
chunks_->data_[pos_.Value()] = v;
}
private:
Chunk* chunks_;
NumericalRev<int> pos_;
};
/// Hash functions
// TODO(user): use murmurhash.
inline uint64_t Hash1(uint64_t value) {
value = (~value) + (value << 21); /// value = (value << 21) - value - 1;
value ^= value >> 24;
value += (value << 3) + (value << 8); /// value * 265
value ^= value >> 14;
value += (value << 2) + (value << 4); /// value * 21
value ^= value >> 28;
value += (value << 31);
return value;
}
inline uint64_t Hash1(uint32_t value) {
uint64_t a = value;
a = (a + 0x7ed55d16) + (a << 12);
a = (a ^ 0xc761c23c) ^ (a >> 19);
a = (a + 0x165667b1) + (a << 5);
a = (a + 0xd3a2646c) ^ (a << 9);
a = (a + 0xfd7046c5) + (a << 3);
a = (a ^ 0xb55a4f09) ^ (a >> 16);
return a;
}
inline uint64_t Hash1(int64_t value) {
return Hash1(static_cast<uint64_t>(value));
}
inline uint64_t Hash1(int value) { return Hash1(static_cast<uint32_t>(value)); }
inline uint64_t Hash1(void* const ptr) {
#if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || \
defined(__aarch64__)
return Hash1(reinterpret_cast<uint64_t>(ptr));
#else
return Hash1(reinterpret_cast<uint32_t>(ptr));
#endif
}
template <class T>
uint64_t Hash1(const std::vector<T*>& ptrs) {
if (ptrs.empty()) return 0;
if (ptrs.size() == 1) return Hash1(ptrs[0]);
uint64_t hash = Hash1(ptrs[0]);
for (int i = 1; i < ptrs.size(); ++i) {
hash = hash * i + Hash1(ptrs[i]);
}
return hash;
}
inline uint64_t Hash1(const std::vector<int64_t>& ptrs) {
if (ptrs.empty()) return 0;
if (ptrs.size() == 1) return Hash1(ptrs[0]);
uint64_t hash = Hash1(ptrs[0]);
for (int i = 1; i < ptrs.size(); ++i) {
hash = hash * i + Hash1(ptrs[i]);
}
return hash;
}
/// Reversible Immutable MultiMap class.
/// Represents an immutable multi-map that backtracks with the solver.
template <class K, class V>
class RevImmutableMultiMap {
public:
RevImmutableMultiMap(Solver* const solver, int initial_size)
: solver_(solver),
array_(solver->UnsafeRevAllocArray(new Cell*[initial_size])),
size_(initial_size),
num_items_(0) {
memset(array_, 0, sizeof(*array_) * size_.Value());
}
~RevImmutableMultiMap() {}
int num_items() const { return num_items_.Value(); }
/// Returns true if the multi-map contains at least one instance of 'key'.
bool ContainsKey(const K& key) const {
uint64_t code = Hash1(key) % size_.Value();
Cell* tmp = array_[code];
while (tmp) {
if (tmp->key() == key) {
return true;
}
tmp = tmp->next();
}
return false;
}
/// Returns one value attached to 'key', or 'default_value' if 'key'
/// is not in the multi-map. The actual value returned if more than one
/// values is attached to the same key is not specified.
const V& FindWithDefault(const K& key, const V& default_value) const {
uint64_t code = Hash1(key) % size_.Value();
Cell* tmp = array_[code];
while (tmp) {
if (tmp->key() == key) {
return tmp->value();
}
tmp = tmp->next();
}
return default_value;
}
/// Inserts (key, value) in the multi-map.
void Insert(const K& key, const V& value) {
const int position = Hash1(key) % size_.Value();
Cell* const cell =
solver_->UnsafeRevAlloc(new Cell(key, value, array_[position]));
solver_->SaveAndSetValue(reinterpret_cast<void**>(&array_[position]),
reinterpret_cast<void*>(cell));
num_items_.Incr(solver_);
if (num_items_.Value() > 2 * size_.Value()) {
Double();
}
}
private:
class Cell {
public:
Cell(const K& key, const V& value, Cell* const next)
: key_(key), value_(value), next_(next) {}
void SetRevNext(Solver* const solver, Cell* const next) {
solver->SaveAndSetValue(reinterpret_cast<void**>(&next_),
reinterpret_cast<void*>(next));
}
Cell* next() const { return next_; }
const K& key() const { return key_; }
const V& value() const { return value_; }
private:
const K key_;
const V value_;
Cell* next_;
};
void Double() {
Cell** const old_cell_array = array_;
const int old_size = size_.Value();
size_.SetValue(solver_, size_.Value() * 2);
solver_->SaveAndSetValue(
reinterpret_cast<void**>(&array_),
reinterpret_cast<void*>(
solver_->UnsafeRevAllocArray(new Cell*[size_.Value()])));
memset(array_, 0, size_.Value() * sizeof(*array_));
for (int i = 0; i < old_size; ++i) {
Cell* tmp = old_cell_array[i];
while (tmp != nullptr) {
Cell* const to_reinsert = tmp;
tmp = tmp->next();
const uint64_t new_position = Hash1(to_reinsert->key()) % size_.Value();
to_reinsert->SetRevNext(solver_, array_[new_position]);
solver_->SaveAndSetValue(
reinterpret_cast<void**>(&array_[new_position]),
reinterpret_cast<void*>(to_reinsert));
}
}
}
Solver* const solver_;
Cell** array_;
NumericalRev<int> size_;
NumericalRev<int> num_items_;
};
/// A reversible switch that can switch once from false to true.
class RevSwitch {
public:
RevSwitch() : value_(false) {}
bool Switched() const { return value_; }
void Switch(Solver* const solver) { solver->SaveAndSetValue(&value_, true); }
private:
bool value_;
};
/// This class represents a small reversible bitset (size <= 64).
/// This class is useful to maintain supports.
class SmallRevBitSet {
public:
explicit SmallRevBitSet(int64_t size);
/// Sets the 'pos' bit.
void SetToOne(Solver* const solver, int64_t pos);
/// Erases the 'pos' bit.
void SetToZero(Solver* const solver, int64_t pos);
/// Returns the number of bits set to one.
int64_t Cardinality() const;
/// Is bitset null?
bool IsCardinalityZero() const { return bits_.Value() == uint64_t{0}; }
/// Does it contains only one bit set?
bool IsCardinalityOne() const {
return (bits_.Value() != 0) && !(bits_.Value() & (bits_.Value() - 1));
}
/// Gets the index of the first bit set starting from 0.
/// It returns -1 if the bitset is empty.
int64_t GetFirstOne() const;
private:
Rev<uint64_t> bits_;
};
/// This class represents a reversible bitset.
/// This class is useful to maintain supports.
class RevBitSet {
public:
explicit RevBitSet(int64_t size);
~RevBitSet();
/// Sets the 'index' bit.
void SetToOne(Solver* const solver, int64_t index);
/// Erases the 'index' bit.
void SetToZero(Solver* const solver, int64_t index);
/// Returns whether the 'index' bit is set.
bool IsSet(int64_t index) const;
/// Returns the number of bits set to one.
int64_t Cardinality() const;
/// Is bitset null?
bool IsCardinalityZero() const;
/// Does it contains only one bit set?
bool IsCardinalityOne() const;
/// Gets the index of the first bit set starting from start.
/// It returns -1 if the bitset is empty after start.
int64_t GetFirstBit(int start) const;
/// Cleans all bits.
void ClearAll(Solver* const solver);
friend class RevBitMatrix;
private:
/// Save the offset's part of the bitset.
void Save(Solver* const solver, int offset);
const int64_t size_;
const int64_t length_;
uint64_t* bits_;
uint64_t* stamps_;
};
/// Matrix version of the RevBitSet class.
class RevBitMatrix : private RevBitSet {
public:
RevBitMatrix(int64_t rows, int64_t columns);
~RevBitMatrix();
/// Sets the 'column' bit in the 'row' row.
void SetToOne(Solver* const solver, int64_t row, int64_t column);
/// Erases the 'column' bit in the 'row' row.
void SetToZero(Solver* const solver, int64_t row, int64_t column);
/// Returns whether the 'column' bit in the 'row' row is set.
bool IsSet(int64_t row, int64_t column) const {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_GE(column, 0);
DCHECK_LT(column, columns_);
return RevBitSet::IsSet(row * columns_ + column);
}
/// Returns the number of bits set to one in the 'row' row.
int64_t Cardinality(int row) const;
/// Is bitset of row 'row' null?
bool IsCardinalityZero(int row) const;
/// Does the 'row' bitset contains only one bit set?
bool IsCardinalityOne(int row) const;
/// Returns the first bit in the row 'row' which position is >= 'start'.
/// It returns -1 if there are none.
int64_t GetFirstBit(int row, int start) const;
/// Cleans all bits.
void ClearAll(Solver* const solver);
private:
const int64_t rows_;
const int64_t columns_;
};
/// @{
/// These methods represent generic demons that will call back a
/// method on the constraint during their Run method.
/// This way, all propagation methods are members of the constraint class,
/// and demons are just proxies with a priority of NORMAL_PRIORITY.
/// Demon proxy to a method on the constraint with no arguments.
template <class T>
class CallMethod0 : public Demon {
public:
CallMethod0(T* const ct, void (T::*method)(), const std::string& name)
: constraint_(ct), method_(method), name_(name) {}
~CallMethod0() override {}
void Run(Solver* const s) override { (constraint_->*method_)(); }
std::string DebugString() const override {
return "CallMethod_" + name_ + "(" + constraint_->DebugString() + ")";
}
private:
T* const constraint_;
void (T::*const method_)();
const std::string name_;
};
template <class T>
Demon* MakeConstraintDemon0(Solver* const s, T* const ct, void (T::*method)(),
const std::string& name) {
return s->RevAlloc(new CallMethod0<T>(ct, method, name));
}
template <class P>
std::string ParameterDebugString(P param) {
return absl::StrCat(param);
}
/// Support limited to pointers to classes which define DebugString().
template <class P>
std::string ParameterDebugString(P* param) {
return param->DebugString();
}
/// Demon proxy to a method on the constraint with one argument.
template <class T, class P>
class CallMethod1 : public Demon {
public:
CallMethod1(T* const ct, void (T::*method)(P), const std::string& name,
P param1)
: constraint_(ct), method_(method), name_(name), param1_(param1) {}
~CallMethod1() override {}
void Run(Solver* const s) override { (constraint_->*method_)(param1_); }
std::string DebugString() const override {
return absl::StrCat("CallMethod_", name_, "(", constraint_->DebugString(),
", ", ParameterDebugString(param1_), ")");
}
private:
T* const constraint_;
void (T::*const method_)(P);
const std::string name_;
P param1_;
};
template <class T, class P>
Demon* MakeConstraintDemon1(Solver* const s, T* const ct, void (T::*method)(P),
const std::string& name, P param1) {
return s->RevAlloc(new CallMethod1<T, P>(ct, method, name, param1));
}
/// Demon proxy to a method on the constraint with two arguments.
template <class T, class P, class Q>
class CallMethod2 : public Demon {
public:
CallMethod2(T* const ct, void (T::*method)(P, Q), const std::string& name,
P param1, Q param2)
: constraint_(ct),
method_(method),
name_(name),
param1_(param1),
param2_(param2) {}
~CallMethod2() override {}
void Run(Solver* const s) override {
(constraint_->*method_)(param1_, param2_);
}
std::string DebugString() const override {
return absl::StrCat(absl::StrCat("CallMethod_", name_),
absl::StrCat("(", constraint_->DebugString()),
absl::StrCat(", ", ParameterDebugString(param1_)),
absl::StrCat(", ", ParameterDebugString(param2_), ")"));
}
private:
T* const constraint_;
void (T::*const method_)(P, Q);
const std::string name_;
P param1_;
Q param2_;
};
template <class T, class P, class Q>
Demon* MakeConstraintDemon2(Solver* const s, T* const ct,
void (T::*method)(P, Q), const std::string& name,
P param1, Q param2) {
return s->RevAlloc(
new CallMethod2<T, P, Q>(ct, method, name, param1, param2));
}
/// Demon proxy to a method on the constraint with three arguments.
template <class T, class P, class Q, class R>
class CallMethod3 : public Demon {
public:
CallMethod3(T* const ct, void (T::*method)(P, Q, R), const std::string& name,
P param1, Q param2, R param3)
: constraint_(ct),
method_(method),
name_(name),
param1_(param1),
param2_(param2),
param3_(param3) {}
~CallMethod3() override {}
void Run(Solver* const s) override {
(constraint_->*method_)(param1_, param2_, param3_);
}
std::string DebugString() const override {
return absl::StrCat(absl::StrCat("CallMethod_", name_),
absl::StrCat("(", constraint_->DebugString()),
absl::StrCat(", ", ParameterDebugString(param1_)),
absl::StrCat(", ", ParameterDebugString(param2_)),
absl::StrCat(", ", ParameterDebugString(param3_), ")"));
}
private:
T* const constraint_;
void (T::*const method_)(P, Q, R);
const std::string name_;
P param1_;
Q param2_;
R param3_;
};
template <class T, class P, class Q, class R>
Demon* MakeConstraintDemon3(Solver* const s, T* const ct,
void (T::*method)(P, Q, R), const std::string& name,
P param1, Q param2, R param3) {
return s->RevAlloc(
new CallMethod3<T, P, Q, R>(ct, method, name, param1, param2, param3));
}
/// @}
/// @{
/// These methods represents generic demons that will call back a
/// method on the constraint during their Run method. This demon will
/// have a priority DELAYED_PRIORITY.
/// Low-priority demon proxy to a method on the constraint with no arguments.
template <class T>
class DelayedCallMethod0 : public Demon {
public:
DelayedCallMethod0(T* const ct, void (T::*method)(), const std::string& name)
: constraint_(ct), method_(method), name_(name) {}
~DelayedCallMethod0() override {}
void Run(Solver* const s) override { (constraint_->*method_)(); }
Solver::DemonPriority priority() const override {
return Solver::DELAYED_PRIORITY;
}
std::string DebugString() const override {
return "DelayedCallMethod_" + name_ + "(" + constraint_->DebugString() +
")";
}
private:
T* const constraint_;
void (T::*const method_)();
const std::string name_;
};
template <class T>
Demon* MakeDelayedConstraintDemon0(Solver* const s, T* const ct,
void (T::*method)(),
const std::string& name) {
return s->RevAlloc(new DelayedCallMethod0<T>(ct, method, name));
}
/// Low-priority demon proxy to a method on the constraint with one argument.
template <class T, class P>
class DelayedCallMethod1 : public Demon {
public:
DelayedCallMethod1(T* const ct, void (T::*method)(P), const std::string& name,
P param1)
: constraint_(ct), method_(method), name_(name), param1_(param1) {}
~DelayedCallMethod1() override {}
void Run(Solver* const s) override { (constraint_->*method_)(param1_); }
Solver::DemonPriority priority() const override {
return Solver::DELAYED_PRIORITY;
}
std::string DebugString() const override {
return absl::StrCat("DelayedCallMethod_", name_, "(",
constraint_->DebugString(), ", ",
ParameterDebugString(param1_), ")");
}
private:
T* const constraint_;
void (T::*const method_)(P);
const std::string name_;
P param1_;
};
template <class T, class P>
Demon* MakeDelayedConstraintDemon1(Solver* const s, T* const ct,
void (T::*method)(P),
const std::string& name, P param1) {
return s->RevAlloc(new DelayedCallMethod1<T, P>(ct, method, name, param1));
}
/// Low-priority demon proxy to a method on the constraint with two arguments.
template <class T, class P, class Q>
class DelayedCallMethod2 : public Demon {
public:
DelayedCallMethod2(T* const ct, void (T::*method)(P, Q),
const std::string& name, P param1, Q param2)
: constraint_(ct),
method_(method),
name_(name),
param1_(param1),
param2_(param2) {}
~DelayedCallMethod2() override {}
void Run(Solver* const s) override {
(constraint_->*method_)(param1_, param2_);
}
Solver::DemonPriority priority() const override {
return Solver::DELAYED_PRIORITY;
}
std::string DebugString() const override {
return absl::StrCat(absl::StrCat("DelayedCallMethod_", name_),
absl::StrCat("(", constraint_->DebugString()),
absl::StrCat(", ", ParameterDebugString(param1_)),
absl::StrCat(", ", ParameterDebugString(param2_), ")"));
}
private:
T* const constraint_;
void (T::*const method_)(P, Q);
const std::string name_;
P param1_;
Q param2_;
};
template <class T, class P, class Q>
Demon* MakeDelayedConstraintDemon2(Solver* const s, T* const ct,
void (T::*method)(P, Q),
const std::string& name, P param1,
Q param2) {
return s->RevAlloc(
new DelayedCallMethod2<T, P, Q>(ct, method, name, param1, param2));
}
/// @}
#endif // !defined(SWIG)
/// The base class for all local search operators.
///
/// A local search operator is an object that defines the neighborhood of a
/// solution. In other words, a neighborhood is the set of solutions which can
/// be reached from a given solution using an operator.
///
/// The behavior of the LocalSearchOperator class is similar to iterators.
/// The operator is synchronized with an assignment (gives the
/// current values of the variables); this is done in the Start() method.
///
/// Then one can iterate over the neighbors using the MakeNextNeighbor method.
/// This method returns an assignment which represents the incremental changes
/// to the current solution. It also returns a second assignment representing
/// the changes to the last solution defined by the neighborhood operator; this
/// assignment is empty if the neighborhood operator cannot track this
/// information.
///
// TODO(user): rename Start to Synchronize ?
// TODO(user): decouple the iterating from the defining of a neighbor.
class LocalSearchOperator : public BaseObject {
public:
LocalSearchOperator() {}
~LocalSearchOperator() override {}
virtual bool MakeNextNeighbor(Assignment* delta, Assignment* deltadelta) = 0;
virtual void Start(const Assignment* assignment) = 0;
virtual void Reset() {}
#ifndef SWIG
virtual const LocalSearchOperator* Self() const { return this; }
#endif // SWIG
virtual bool HasFragments() const { return false; }
virtual bool HoldsDelta() const { return false; }
};
/// Base operator class for operators manipulating variables.
template <class V, class Val, class Handler>
class VarLocalSearchOperator : public LocalSearchOperator {
public:
VarLocalSearchOperator() : activated_(), was_activated_(), cleared_(true) {}
explicit VarLocalSearchOperator(Handler var_handler)
: activated_(),
was_activated_(),
cleared_(true),
var_handler_(var_handler) {}
~VarLocalSearchOperator() override {}
bool HoldsDelta() const override { return true; }
/// This method should not be overridden. Override OnStart() instead which is
/// called before exiting this method.
void Start(const Assignment* assignment) override {
const int size = Size();
CHECK_LE(size, assignment->Size())
<< "Assignment contains fewer variables than operator";
for (int i = 0; i < size; ++i) {
activated_.Set(i, var_handler_.ValueFromAssignment(*assignment, vars_[i],
i, &values_[i]));
}
prev_values_ = old_values_;
old_values_ = values_;
was_activated_.SetContentFromBitsetOfSameSize(activated_);
OnStart();
}
virtual bool IsIncremental() const { return false; }
int Size() const { return vars_.size(); }
/// Returns the value in the current assignment of the variable of given
/// index.
const Val& Value(int64_t index) const {
DCHECK_LT(index, vars_.size());
return values_[index];
}
/// Returns the variable of given index.
V* Var(int64_t index) const { return vars_[index]; }
virtual bool SkipUnchanged(int index) const { return false; }
const Val& OldValue(int64_t index) const { return old_values_[index]; }
void SetValue(int64_t index, const Val& value) {
values_[index] = value;
MarkChange(index);
}
bool Activated(int64_t index) const { return activated_[index]; }
void Activate(int64_t index) {
activated_.Set(index);
MarkChange(index);
}
void Deactivate(int64_t index) {
activated_.Clear(index);
MarkChange(index);
}
bool ApplyChanges(Assignment* delta, Assignment* deltadelta) const {
if (IsIncremental() && !cleared_) {
for (const int64_t index : delta_changes_.PositionsSetAtLeastOnce()) {
V* var = Var(index);
const Val& value = Value(index);
const bool activated = activated_[index];
var_handler_.AddToAssignment(var, value, activated, nullptr, index,
deltadelta);
var_handler_.AddToAssignment(var, value, activated,
&assignment_indices_, index, delta);
}
} else {
delta->Clear();
for (const int64_t index : changes_.PositionsSetAtLeastOnce()) {
const Val& value = Value(index);
const bool activated = activated_[index];
if (!activated || value != OldValue(index) || !SkipUnchanged(index)) {
var_handler_.AddToAssignment(Var(index), value, activated_[index],
&assignment_indices_, index, delta);
}
}
}
return true;
}
void RevertChanges(bool incremental) {
cleared_ = false;
delta_changes_.SparseClearAll();
if (incremental && IsIncremental()) return;
cleared_ = true;
for (const int64_t index : changes_.PositionsSetAtLeastOnce()) {
values_[index] = old_values_[index];
var_handler_.OnRevertChanges(index, values_[index]);
activated_.CopyBucket(was_activated_, index);
assignment_indices_[index] = -1;
}
changes_.SparseClearAll();
}
void AddVars(const std::vector<V*>& vars) {
if (!vars.empty()) {
vars_.insert(vars_.end(), vars.begin(), vars.end());
const int64_t size = Size();
values_.resize(size);
old_values_.resize(size);
prev_values_.resize(size);
assignment_indices_.resize(size, -1);
activated_.Resize(size);
was_activated_.Resize(size);
changes_.ClearAndResize(size);
delta_changes_.ClearAndResize(size);
var_handler_.OnAddVars();
}
}
/// Called by Start() after synchronizing the operator with the current
/// assignment. Should be overridden instead of Start() to avoid calling
/// VarLocalSearchOperator::Start explicitly.
virtual void OnStart() {}
/// OnStart() should really be protected, but then SWIG doesn't see it. So we
/// make it public, but only subclasses should access to it (to override it).
protected:
void MarkChange(int64_t index) {
delta_changes_.Set(index);
changes_.Set(index);
}
std::vector<V*> vars_;
std::vector<Val> values_;
std::vector<Val> old_values_;
std::vector<Val> prev_values_;
mutable std::vector<int> assignment_indices_;
Bitset64<> activated_;
Bitset64<> was_activated_;
SparseBitset<> changes_;
SparseBitset<> delta_changes_;
bool cleared_;
Handler var_handler_;
};
/// Base operator class for operators manipulating IntVars.
class IntVarLocalSearchOperator;
class IntVarLocalSearchHandler {
public:
IntVarLocalSearchHandler() : op_(nullptr) {}
IntVarLocalSearchHandler(const IntVarLocalSearchHandler& other)
: op_(other.op_) {}
explicit IntVarLocalSearchHandler(IntVarLocalSearchOperator* op) : op_(op) {}
void AddToAssignment(IntVar* var, int64_t value, bool active,
std::vector<int>* assignment_indices, int64_t index,
Assignment* assignment) const {
Assignment::IntContainer* const container =
assignment->MutableIntVarContainer();
IntVarElement* element = nullptr;
if (assignment_indices != nullptr) {
if ((*assignment_indices)[index] == -1) {
(*assignment_indices)[index] = container->Size();
element = assignment->FastAdd(var);
} else {
element = container->MutableElement((*assignment_indices)[index]);
}
} else {
element = assignment->FastAdd(var);
}
if (active) {
element->SetValue(value);
element->Activate();
} else {
element->Deactivate();
}
}
bool ValueFromAssignment(const Assignment& assignment, IntVar* var,
int64_t index, int64_t* value);
void OnRevertChanges(int64_t index, int64_t value);
void OnAddVars() {}
private:
IntVarLocalSearchOperator* const op_;
};
/// Specialization of LocalSearchOperator built from an array of IntVars
/// which specifies the scope of the operator.
/// This class also takes care of storing current variable values in Start(),
/// keeps track of changes done by the operator and builds the delta.
/// The Deactivate() method can be used to perform Large Neighborhood Search.
#ifdef SWIG
/// Unfortunately, we must put this code here and not in
/// */constraint_solver.i, because it must be parsed by SWIG before the
/// derived C++ class.
// TODO(user): find a way to move this code back to the .i file, where it
/// belongs.
/// In python, we use an allow-list to expose the API. This list must also
/// be extended here.
#if defined(SWIGPYTHON)
// clang-format off
%unignore VarLocalSearchOperator<IntVar, int64_t,
IntVarLocalSearchHandler>::Size;
%unignore VarLocalSearchOperator<IntVar, int64_t,
IntVarLocalSearchHandler>::Value;
%unignore VarLocalSearchOperator<IntVar, int64_t,
IntVarLocalSearchHandler>::OldValue;
%unignore VarLocalSearchOperator<IntVar, int64_t,