forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.cc
4727 lines (4136 loc) · 150 KB
/
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 <functional>
#include <list>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/casts.h"
#include "absl/container/flat_hash_map.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/time/time.h"
#include "ortools/base/bitmap.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/macros.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/timer.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/search_limit.pb.h"
#include "ortools/util/string_array.h"
DEFINE_bool(cp_use_sparse_gls_penalties, false,
"Use sparse implementation to store Guided Local Search penalties");
DEFINE_bool(cp_log_to_vlog, false,
"Whether search related logging should be "
"vlog or info.");
DEFINE_int64(cp_large_domain_no_splitting_limit, 0xFFFFF,
"Size limit to allow holes in variables from the strategy.");
namespace operations_research {
// ---------- Search Log ---------
SearchLog::SearchLog(Solver* const s, OptimizeVar* const obj, IntVar* const var,
double scaling_factor, double offset,
std::function<std::string()> display_callback, int period)
: SearchMonitor(s),
period_(period),
timer_(new WallTimer),
var_(var),
obj_(obj),
scaling_factor_(scaling_factor),
offset_(offset),
display_callback_(std::move(display_callback)),
nsol_(0),
tick_(0),
objective_min_(kint64max),
objective_max_(kint64min),
min_right_depth_(kint32max),
max_depth_(0),
sliding_min_depth_(0),
sliding_max_depth_(0) {
CHECK(obj == nullptr || var == nullptr)
<< "Either var or obj need to be nullptr.";
}
SearchLog::~SearchLog() {}
std::string SearchLog::DebugString() const { return "SearchLog"; }
void SearchLog::EnterSearch() {
const std::string buffer =
absl::StrFormat("Start search (%s)", MemoryUsage());
OutputLine(buffer);
timer_->Restart();
min_right_depth_ = kint32max;
}
void SearchLog::ExitSearch() {
const int64 branches = solver()->branches();
int64 ms = timer_->GetInMs();
if (ms == 0) {
ms = 1;
}
const std::string buffer = absl::StrFormat(
"End search (time = %d ms, branches = %d, failures = %d, %s, speed = %d "
"branches/s)",
ms, branches, solver()->failures(), MemoryUsage(), branches * 1000 / ms);
OutputLine(buffer);
}
bool SearchLog::AtSolution() {
Maintain();
const int depth = solver()->SearchDepth();
std::string obj_str = "";
int64 current = 0;
bool objective_updated = false;
const auto scaled_str = [this](int64 value) {
if (scaling_factor_ != 1.0 || offset_ != 0.0) {
return absl::StrFormat("%d (%.8lf)", value,
scaling_factor_ * (value + offset_));
} else {
return absl::StrCat(value);
}
};
if (obj_ != nullptr && obj_->Var()->Bound()) {
current = obj_->Var()->Value();
obj_str = obj_->Print();
objective_updated = true;
} else if (var_ != nullptr && var_->Bound()) {
current = var_->Value();
absl::StrAppend(&obj_str, scaled_str(current), ", ");
objective_updated = true;
} else {
current = solver()->GetOrCreateLocalSearchState()->ObjectiveMin();
absl::StrAppend(&obj_str, scaled_str(current), ", ");
objective_updated = true;
}
if (objective_updated) {
if (current > objective_min_) {
absl::StrAppend(&obj_str,
"objective minimum = ", scaled_str(objective_min_), ", ");
} else {
objective_min_ = current;
}
if (current < objective_max_) {
absl::StrAppend(&obj_str,
"objective maximum = ", scaled_str(objective_max_), ", ");
} else {
objective_max_ = current;
}
}
std::string log;
absl::StrAppendFormat(&log,
"Solution #%d (%stime = %d ms, branches = %d,"
" failures = %d, depth = %d",
nsol_++, obj_str, timer_->GetInMs(),
solver()->branches(), solver()->failures(), depth);
if (!solver()->SearchContext().empty()) {
absl::StrAppendFormat(&log, ", %s", solver()->SearchContext());
}
if (solver()->neighbors() != 0) {
absl::StrAppendFormat(&log,
", neighbors = %d, filtered neighbors = %d,"
" accepted neighbors = %d",
solver()->neighbors(), solver()->filtered_neighbors(),
solver()->accepted_neighbors());
}
absl::StrAppendFormat(&log, ", %s", MemoryUsage());
const int progress = solver()->TopProgressPercent();
if (progress != SearchMonitor::kNoProgress) {
absl::StrAppendFormat(&log, ", limit = %d%%", progress);
}
log.append(")");
OutputLine(log);
if (display_callback_) {
LOG(INFO) << display_callback_();
}
return false;
}
void SearchLog::AcceptUncheckedNeighbor() { AtSolution(); }
void SearchLog::BeginFail() { Maintain(); }
void SearchLog::NoMoreSolutions() {
std::string buffer = absl::StrFormat(
"Finished search tree (time = %d ms, branches = %d,"
" failures = %d",
timer_->GetInMs(), solver()->branches(), solver()->failures());
if (solver()->neighbors() != 0) {
absl::StrAppendFormat(&buffer,
", neighbors = %d, filtered neighbors = %d,"
" accepted neigbors = %d",
solver()->neighbors(), solver()->filtered_neighbors(),
solver()->accepted_neighbors());
}
absl::StrAppendFormat(&buffer, ", %s)", MemoryUsage());
OutputLine(buffer);
}
void SearchLog::ApplyDecision(Decision* const decision) {
Maintain();
const int64 b = solver()->branches();
if (b % period_ == 0 && b > 0) {
OutputDecision();
}
}
void SearchLog::RefuteDecision(Decision* const decision) {
min_right_depth_ = std::min(min_right_depth_, solver()->SearchDepth());
ApplyDecision(decision);
}
void SearchLog::OutputDecision() {
std::string buffer =
absl::StrFormat("%d branches, %d ms, %d failures", solver()->branches(),
timer_->GetInMs(), solver()->failures());
if (min_right_depth_ != kint32max && max_depth_ != 0) {
const int depth = solver()->SearchDepth();
absl::StrAppendFormat(&buffer, ", tree pos=%d/%d/%d minref=%d max=%d",
sliding_min_depth_, depth, sliding_max_depth_,
min_right_depth_, max_depth_);
sliding_min_depth_ = depth;
sliding_max_depth_ = depth;
}
if (obj_ != nullptr && objective_min_ != kint64max &&
objective_max_ != kint64min) {
absl::StrAppendFormat(&buffer,
", objective minimum = %d"
", objective maximum = %d",
objective_min_, objective_max_);
}
const int progress = solver()->TopProgressPercent();
if (progress != SearchMonitor::kNoProgress) {
absl::StrAppendFormat(&buffer, ", limit = %d%%", progress);
}
OutputLine(buffer);
}
void SearchLog::Maintain() {
const int current_depth = solver()->SearchDepth();
sliding_min_depth_ = std::min(current_depth, sliding_min_depth_);
sliding_max_depth_ = std::max(current_depth, sliding_max_depth_);
max_depth_ = std::max(current_depth, max_depth_);
}
void SearchLog::BeginInitialPropagation() { tick_ = timer_->GetInMs(); }
void SearchLog::EndInitialPropagation() {
const int64 delta = std::max<int64>(timer_->GetInMs() - tick_, 0);
const std::string buffer = absl::StrFormat(
"Root node processed (time = %d ms, constraints = %d, %s)", delta,
solver()->constraints(), MemoryUsage());
OutputLine(buffer);
}
void SearchLog::OutputLine(const std::string& line) {
if (FLAGS_cp_log_to_vlog) {
VLOG(1) << line;
} else {
LOG(INFO) << line;
}
}
std::string SearchLog::MemoryUsage() {
static const int64 kDisplayThreshold = 2;
static const int64 kKiloByte = 1024;
static const int64 kMegaByte = kKiloByte * kKiloByte;
static const int64 kGigaByte = kMegaByte * kKiloByte;
const int64 memory_usage = Solver::MemoryUsage();
if (memory_usage > kDisplayThreshold * kGigaByte) {
return absl::StrFormat("memory used = %.2lf GB",
memory_usage * 1.0 / kGigaByte);
} else if (memory_usage > kDisplayThreshold * kMegaByte) {
return absl::StrFormat("memory used = %.2lf MB",
memory_usage * 1.0 / kMegaByte);
} else if (memory_usage > kDisplayThreshold * kKiloByte) {
return absl::StrFormat("memory used = %2lf KB",
memory_usage * 1.0 / kKiloByte);
} else {
return absl::StrFormat("memory used = %d", memory_usage);
}
}
SearchMonitor* Solver::MakeSearchLog(int branch_period) {
return RevAlloc(
new SearchLog(this, nullptr, nullptr, 1.0, 0.0, nullptr, branch_period));
}
SearchMonitor* Solver::MakeSearchLog(int branch_period, IntVar* const var) {
return RevAlloc(
new SearchLog(this, nullptr, var, 1.0, 0.0, nullptr, branch_period));
}
SearchMonitor* Solver::MakeSearchLog(
int branch_period, std::function<std::string()> display_callback) {
return RevAlloc(new SearchLog(this, nullptr, nullptr, 1.0, 0.0,
std::move(display_callback), branch_period));
}
SearchMonitor* Solver::MakeSearchLog(
int branch_period, IntVar* const var,
std::function<std::string()> display_callback) {
return RevAlloc(new SearchLog(this, nullptr, var, 1.0, 0.0,
std::move(display_callback), branch_period));
}
SearchMonitor* Solver::MakeSearchLog(int branch_period,
OptimizeVar* const opt_var) {
return RevAlloc(
new SearchLog(this, opt_var, nullptr, 1.0, 0.0, nullptr, branch_period));
}
SearchMonitor* Solver::MakeSearchLog(
int branch_period, OptimizeVar* const opt_var,
std::function<std::string()> display_callback) {
return RevAlloc(new SearchLog(this, opt_var, nullptr, 1.0, 0.0,
std::move(display_callback), branch_period));
}
SearchMonitor* Solver::MakeSearchLog(SearchLogParameters parameters) {
return RevAlloc(new SearchLog(this, parameters.objective, parameters.variable,
parameters.scaling_factor, parameters.offset,
std::move(parameters.display_callback),
parameters.branch_period));
}
// ---------- Search Trace ----------
namespace {
class SearchTrace : public SearchMonitor {
public:
SearchTrace(Solver* const s, const std::string& prefix)
: SearchMonitor(s), prefix_(prefix) {}
~SearchTrace() override {}
void EnterSearch() override {
LOG(INFO) << prefix_ << " EnterSearch(" << solver()->SolveDepth() << ")";
}
void RestartSearch() override {
LOG(INFO) << prefix_ << " RestartSearch(" << solver()->SolveDepth() << ")";
}
void ExitSearch() override {
LOG(INFO) << prefix_ << " ExitSearch(" << solver()->SolveDepth() << ")";
}
void BeginNextDecision(DecisionBuilder* const b) override {
LOG(INFO) << prefix_ << " BeginNextDecision(" << b << ") ";
}
void EndNextDecision(DecisionBuilder* const b, Decision* const d) override {
if (d) {
LOG(INFO) << prefix_ << " EndNextDecision(" << b << ", " << d << ") ";
} else {
LOG(INFO) << prefix_ << " EndNextDecision(" << b << ") ";
}
}
void ApplyDecision(Decision* const d) override {
LOG(INFO) << prefix_ << " ApplyDecision(" << d << ") ";
}
void RefuteDecision(Decision* const d) override {
LOG(INFO) << prefix_ << " RefuteDecision(" << d << ") ";
}
void AfterDecision(Decision* const d, bool apply) override {
LOG(INFO) << prefix_ << " AfterDecision(" << d << ", " << apply << ") ";
}
void BeginFail() override {
LOG(INFO) << prefix_ << " BeginFail(" << solver()->SearchDepth() << ")";
}
void EndFail() override {
LOG(INFO) << prefix_ << " EndFail(" << solver()->SearchDepth() << ")";
}
void BeginInitialPropagation() override {
LOG(INFO) << prefix_ << " BeginInitialPropagation()";
}
void EndInitialPropagation() override {
LOG(INFO) << prefix_ << " EndInitialPropagation()";
}
bool AtSolution() override {
LOG(INFO) << prefix_ << " AtSolution()";
return false;
}
bool AcceptSolution() override {
LOG(INFO) << prefix_ << " AcceptSolution()";
return true;
}
void NoMoreSolutions() override {
LOG(INFO) << prefix_ << " NoMoreSolutions()";
}
std::string DebugString() const override { return "SearchTrace"; }
private:
const std::string prefix_;
};
} // namespace
SearchMonitor* Solver::MakeSearchTrace(const std::string& prefix) {
return RevAlloc(new SearchTrace(this, prefix));
}
// ---------- Callback-based search monitors ----------
namespace {
class AtSolutionCallback : public SearchMonitor {
public:
AtSolutionCallback(Solver* const solver, std::function<void()> callback)
: SearchMonitor(solver), callback_(std::move(callback)) {}
~AtSolutionCallback() override {}
bool AtSolution() override;
private:
const std::function<void()> callback_;
};
bool AtSolutionCallback::AtSolution() {
callback_();
return false;
}
} // namespace
SearchMonitor* Solver::MakeAtSolutionCallback(std::function<void()> callback) {
return RevAlloc(new AtSolutionCallback(this, std::move(callback)));
}
namespace {
class EnterSearchCallback : public SearchMonitor {
public:
EnterSearchCallback(Solver* const solver, std::function<void()> callback)
: SearchMonitor(solver), callback_(std::move(callback)) {}
~EnterSearchCallback() override {}
void EnterSearch() override;
private:
const std::function<void()> callback_;
};
void EnterSearchCallback::EnterSearch() { callback_(); }
} // namespace
SearchMonitor* Solver::MakeEnterSearchCallback(std::function<void()> callback) {
return RevAlloc(new EnterSearchCallback(this, std::move(callback)));
}
namespace {
class ExitSearchCallback : public SearchMonitor {
public:
ExitSearchCallback(Solver* const solver, std::function<void()> callback)
: SearchMonitor(solver), callback_(std::move(callback)) {}
~ExitSearchCallback() override {}
void ExitSearch() override;
private:
const std::function<void()> callback_;
};
void ExitSearchCallback::ExitSearch() { callback_(); }
} // namespace
SearchMonitor* Solver::MakeExitSearchCallback(std::function<void()> callback) {
return RevAlloc(new ExitSearchCallback(this, std::move(callback)));
}
// ---------- Composite Decision Builder --------
namespace {
class CompositeDecisionBuilder : public DecisionBuilder {
public:
CompositeDecisionBuilder();
explicit CompositeDecisionBuilder(const std::vector<DecisionBuilder*>& dbs);
~CompositeDecisionBuilder() override;
void Add(DecisionBuilder* const db);
void AppendMonitors(Solver* const solver,
std::vector<SearchMonitor*>* const monitors) override;
void Accept(ModelVisitor* const visitor) const override;
protected:
std::vector<DecisionBuilder*> builders_;
};
CompositeDecisionBuilder::CompositeDecisionBuilder() {}
CompositeDecisionBuilder::CompositeDecisionBuilder(
const std::vector<DecisionBuilder*>& dbs) {
for (int i = 0; i < dbs.size(); ++i) {
Add(dbs[i]);
}
}
CompositeDecisionBuilder::~CompositeDecisionBuilder() {}
void CompositeDecisionBuilder::Add(DecisionBuilder* const db) {
if (db != nullptr) {
builders_.push_back(db);
}
}
void CompositeDecisionBuilder::AppendMonitors(
Solver* const solver, std::vector<SearchMonitor*>* const monitors) {
for (DecisionBuilder* const db : builders_) {
db->AppendMonitors(solver, monitors);
}
}
void CompositeDecisionBuilder::Accept(ModelVisitor* const visitor) const {
for (DecisionBuilder* const db : builders_) {
db->Accept(visitor);
}
}
} // namespace
// ---------- Compose Decision Builder ----------
namespace {
class ComposeDecisionBuilder : public CompositeDecisionBuilder {
public:
ComposeDecisionBuilder();
explicit ComposeDecisionBuilder(const std::vector<DecisionBuilder*>& dbs);
~ComposeDecisionBuilder() override;
Decision* Next(Solver* const s) override;
std::string DebugString() const override;
private:
int start_index_;
};
ComposeDecisionBuilder::ComposeDecisionBuilder() : start_index_(0) {}
ComposeDecisionBuilder::ComposeDecisionBuilder(
const std::vector<DecisionBuilder*>& dbs)
: CompositeDecisionBuilder(dbs), start_index_(0) {}
ComposeDecisionBuilder::~ComposeDecisionBuilder() {}
Decision* ComposeDecisionBuilder::Next(Solver* const s) {
const int size = builders_.size();
for (int i = start_index_; i < size; ++i) {
Decision* d = builders_[i]->Next(s);
if (d != nullptr) {
s->SaveAndSetValue(&start_index_, i);
return d;
}
}
s->SaveAndSetValue(&start_index_, size);
return nullptr;
}
std::string ComposeDecisionBuilder::DebugString() const {
return absl::StrFormat("ComposeDecisionBuilder(%s)",
JoinDebugStringPtr(builders_, ", "));
}
} // namespace
DecisionBuilder* Solver::Compose(DecisionBuilder* const db1,
DecisionBuilder* const db2) {
ComposeDecisionBuilder* c = RevAlloc(new ComposeDecisionBuilder());
c->Add(db1);
c->Add(db2);
return c;
}
DecisionBuilder* Solver::Compose(DecisionBuilder* const db1,
DecisionBuilder* const db2,
DecisionBuilder* const db3) {
ComposeDecisionBuilder* c = RevAlloc(new ComposeDecisionBuilder());
c->Add(db1);
c->Add(db2);
c->Add(db3);
return c;
}
DecisionBuilder* Solver::Compose(DecisionBuilder* const db1,
DecisionBuilder* const db2,
DecisionBuilder* const db3,
DecisionBuilder* const db4) {
ComposeDecisionBuilder* c = RevAlloc(new ComposeDecisionBuilder());
c->Add(db1);
c->Add(db2);
c->Add(db3);
c->Add(db4);
return c;
}
DecisionBuilder* Solver::Compose(const std::vector<DecisionBuilder*>& dbs) {
if (dbs.size() == 1) {
return dbs[0];
}
return RevAlloc(new ComposeDecisionBuilder(dbs));
}
// ---------- ClosureDecision ---------
namespace {
class ClosureDecision : public Decision {
public:
ClosureDecision(Solver::Action apply, Solver::Action refute)
: apply_(std::move(apply)), refute_(std::move(refute)) {}
~ClosureDecision() override {}
void Apply(Solver* const s) override { apply_(s); }
void Refute(Solver* const s) override { refute_(s); }
std::string DebugString() const override { return "ClosureDecision"; }
private:
Solver::Action apply_;
Solver::Action refute_;
};
} // namespace
Decision* Solver::MakeDecision(Action apply, Action refute) {
return RevAlloc(new ClosureDecision(std::move(apply), std::move(refute)));
}
// ---------- Try Decision Builder ----------
namespace {
class TryDecisionBuilder;
class TryDecision : public Decision {
public:
explicit TryDecision(TryDecisionBuilder* const try_builder);
~TryDecision() override;
void Apply(Solver* const solver) override;
void Refute(Solver* const solver) override;
std::string DebugString() const override { return "TryDecision"; }
private:
TryDecisionBuilder* const try_builder_;
};
class TryDecisionBuilder : public CompositeDecisionBuilder {
public:
TryDecisionBuilder();
explicit TryDecisionBuilder(const std::vector<DecisionBuilder*>& dbs);
~TryDecisionBuilder() override;
Decision* Next(Solver* const solver) override;
std::string DebugString() const override;
void AdvanceToNextBuilder(Solver* const solver);
private:
TryDecision try_decision_;
int current_builder_;
bool start_new_builder_;
};
TryDecision::TryDecision(TryDecisionBuilder* const try_builder)
: try_builder_(try_builder) {}
TryDecision::~TryDecision() {}
void TryDecision::Apply(Solver* const solver) {}
void TryDecision::Refute(Solver* const solver) {
try_builder_->AdvanceToNextBuilder(solver);
}
TryDecisionBuilder::TryDecisionBuilder()
: CompositeDecisionBuilder(),
try_decision_(this),
current_builder_(-1),
start_new_builder_(true) {}
TryDecisionBuilder::TryDecisionBuilder(const std::vector<DecisionBuilder*>& dbs)
: CompositeDecisionBuilder(dbs),
try_decision_(this),
current_builder_(-1),
start_new_builder_(true) {}
TryDecisionBuilder::~TryDecisionBuilder() {}
Decision* TryDecisionBuilder::Next(Solver* const solver) {
if (current_builder_ < 0) {
solver->SaveAndSetValue(¤t_builder_, 0);
start_new_builder_ = true;
}
if (start_new_builder_) {
start_new_builder_ = false;
return &try_decision_;
} else {
return builders_[current_builder_]->Next(solver);
}
}
std::string TryDecisionBuilder::DebugString() const {
return absl::StrFormat("TryDecisionBuilder(%s)",
JoinDebugStringPtr(builders_, ", "));
}
void TryDecisionBuilder::AdvanceToNextBuilder(Solver* const solver) {
++current_builder_;
start_new_builder_ = true;
if (current_builder_ >= builders_.size()) {
solver->Fail();
}
}
} // namespace
DecisionBuilder* Solver::Try(DecisionBuilder* const db1,
DecisionBuilder* const db2) {
TryDecisionBuilder* try_db = RevAlloc(new TryDecisionBuilder());
try_db->Add(db1);
try_db->Add(db2);
return try_db;
}
DecisionBuilder* Solver::Try(DecisionBuilder* const db1,
DecisionBuilder* const db2,
DecisionBuilder* const db3) {
TryDecisionBuilder* try_db = RevAlloc(new TryDecisionBuilder());
try_db->Add(db1);
try_db->Add(db2);
try_db->Add(db3);
return try_db;
}
DecisionBuilder* Solver::Try(DecisionBuilder* const db1,
DecisionBuilder* const db2,
DecisionBuilder* const db3,
DecisionBuilder* const db4) {
TryDecisionBuilder* try_db = RevAlloc(new TryDecisionBuilder());
try_db->Add(db1);
try_db->Add(db2);
try_db->Add(db3);
try_db->Add(db4);
return try_db;
}
DecisionBuilder* Solver::Try(const std::vector<DecisionBuilder*>& dbs) {
return RevAlloc(new TryDecisionBuilder(dbs));
}
// ---------- Variable Assignments ----------
// ----- BaseAssignmentSelector -----
namespace {
class BaseVariableAssignmentSelector : public BaseObject {
public:
BaseVariableAssignmentSelector(Solver* solver,
const std::vector<IntVar*>& vars)
: solver_(solver),
vars_(vars),
first_unbound_(0),
last_unbound_(vars.size() - 1) {}
~BaseVariableAssignmentSelector() override {}
virtual int64 SelectValue(const IntVar* v, int64 id) = 0;
// Returns -1 if no variable are suitable.
virtual int64 ChooseVariable() = 0;
int64 ChooseVariableWrapper() {
int64 i;
for (i = first_unbound_.Value(); i <= last_unbound_.Value(); ++i) {
if (!vars_[i]->Bound()) {
break;
}
}
first_unbound_.SetValue(solver_, i);
if (i > last_unbound_.Value()) {
return -1;
}
for (i = last_unbound_.Value(); i >= first_unbound_.Value(); --i) {
if (!vars_[i]->Bound()) {
break;
}
}
last_unbound_.SetValue(solver_, i);
return ChooseVariable();
}
void Accept(ModelVisitor* const visitor) const {
visitor->BeginVisitExtension(ModelVisitor::kVariableGroupExtension);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
vars_);
visitor->EndVisitExtension(ModelVisitor::kVariableGroupExtension);
}
const std::vector<IntVar*>& vars() const { return vars_; }
protected:
Solver* const solver_;
std::vector<IntVar*> vars_;
Rev<int64> first_unbound_;
Rev<int64> last_unbound_;
};
// ----- Choose first unbound --
int64 ChooseFirstUnbound(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
for (int64 i = first_unbound; i <= last_unbound; ++i) {
if (!vars[i]->Bound()) {
return i;
}
}
return -1;
}
// ----- Choose Min Size Lowest Min -----
int64 ChooseMinSizeLowestMin(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = kuint64max;
int64 best_min = kint64max;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() < best_size ||
(var->Size() == best_size && var->Min() < best_min)) {
best_size = var->Size();
best_min = var->Min();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Min Size Highest Min -----
int64 ChooseMinSizeHighestMin(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = kuint64max;
int64 best_min = kint64min;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() < best_size ||
(var->Size() == best_size && var->Min() > best_min)) {
best_size = var->Size();
best_min = var->Min();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Min Size Lowest Max -----
int64 ChooseMinSizeLowestMax(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = kuint64max;
int64 best_max = kint64max;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() < best_size ||
(var->Size() == best_size && var->Max() < best_max)) {
best_size = var->Size();
best_max = var->Max();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Min Size Highest Max -----
int64 ChooseMinSizeHighestMax(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = kuint64max;
int64 best_max = kint64min;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() < best_size ||
(var->Size() == best_size && var->Max() > best_max)) {
best_size = var->Size();
best_max = var->Max();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Lowest Min --
int64 ChooseLowestMin(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
int64 best_min = kint64max;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Min() < best_min) {
best_min = var->Min();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Highest Max -----
int64 ChooseHighestMax(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
int64 best_max = kint64min;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Max() > best_max) {
best_max = var->Max();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Lowest Size --
int64 ChooseMinSize(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = kuint64max;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() < best_size) {
best_size = var->Size();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Highest Size -----
int64 ChooseMaxSize(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound) {
uint64 best_size = 0;
int64 best_index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
if (var->Size() > best_size) {
best_size = var->Size();
best_index = i;
}
}
}
return best_index;
}
// ----- Choose Highest Regret -----
class HighestRegretSelectorOnMin : public BaseObject {
public:
explicit HighestRegretSelectorOnMin(const std::vector<IntVar*>& vars)
: iterators_(vars.size()) {
for (int64 i = 0; i < vars.size(); ++i) {
iterators_[i] = vars[i]->MakeDomainIterator(true);
}
}
~HighestRegretSelectorOnMin() override {}
int64 Choose(Solver* const s, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound);
std::string DebugString() const override { return "MaxRegretSelector"; }
int64 ComputeRegret(IntVar* var, int64 index) const {
DCHECK(!var->Bound());
const int64 vmin = var->Min();
IntVarIterator* const iterator = iterators_[index];
iterator->Init();
iterator->Next();
return iterator->Value() - vmin;
}
private:
std::vector<IntVarIterator*> iterators_;
};
int64 HighestRegretSelectorOnMin::Choose(Solver* const s,
const std::vector<IntVar*>& vars,
int64 first_unbound,
int64 last_unbound) {
int64 best_regret = 0;
int64 index = -1;
for (int64 i = first_unbound; i <= last_unbound; ++i) {
IntVar* const var = vars[i];
if (!var->Bound()) {
const int64 regret = ComputeRegret(var, i);
if (regret > best_regret) {
best_regret = regret;
index = i;
}
}
}
return index;
}
// ----- Choose random unbound --