forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteger_search.cc
1976 lines (1763 loc) · 78.3 KB
/
integer_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-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/integer_search.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <random>
#include <tuple>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/meta/type_traits.h"
#include "absl/random/distributions.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/sat/clause.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_mapping.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/intervals.h"
#include "ortools/sat/linear_constraint_manager.h"
#include "ortools/sat/linear_programming_constraint.h"
#include "ortools/sat/model.h"
#include "ortools/sat/probing.h"
#include "ortools/sat/pseudo_costs.h"
#include "ortools/sat/restart.h"
#include "ortools/sat/rins.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_decision.h"
#include "ortools/sat/sat_inprocessing.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/synchronization.h"
#include "ortools/sat/util.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
IntegerLiteral AtMinValue(IntegerVariable var, IntegerTrail* integer_trail) {
const IntegerValue lb = integer_trail->LowerBound(var);
DCHECK_LE(lb, integer_trail->UpperBound(var));
if (lb == integer_trail->UpperBound(var)) return IntegerLiteral();
return IntegerLiteral::LowerOrEqual(var, lb);
}
IntegerLiteral ChooseBestObjectiveValue(IntegerVariable var, Model* model) {
const auto& variables =
model->GetOrCreate<ObjectiveDefinition>()->objective_impacting_variables;
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
if (variables.contains(var)) {
return AtMinValue(var, integer_trail);
} else if (variables.contains(NegationOf(var))) {
return AtMinValue(NegationOf(var), integer_trail);
}
return IntegerLiteral();
}
IntegerLiteral GreaterOrEqualToMiddleValue(IntegerVariable var,
IntegerTrail* integer_trail) {
const IntegerValue var_lb = integer_trail->LowerBound(var);
const IntegerValue var_ub = integer_trail->UpperBound(var);
CHECK_LT(var_lb, var_ub);
const IntegerValue chosen_value =
var_lb + std::max(IntegerValue(1), (var_ub - var_lb) / IntegerValue(2));
return IntegerLiteral::GreaterOrEqual(var, chosen_value);
}
IntegerLiteral SplitAroundGivenValue(IntegerVariable var, IntegerValue value,
Model* model) {
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
const IntegerValue lb = integer_trail->LowerBound(var);
const IntegerValue ub = integer_trail->UpperBound(var);
const absl::flat_hash_set<IntegerVariable>& variables =
model->GetOrCreate<ObjectiveDefinition>()->objective_impacting_variables;
// Heuristic: Prefer the objective direction first. Reference: Conflict-Driven
// Heuristics for Mixed Integer Programming (2019) by Jakob Witzig and Ambros
// Gleixner.
// NOTE: The value might be out of bounds. In that case we return
// kNoLiteralIndex.
const bool branch_down_feasible = value >= lb && value < ub;
const bool branch_up_feasible = value > lb && value <= ub;
if (variables.contains(var) && branch_down_feasible) {
return IntegerLiteral::LowerOrEqual(var, value);
} else if (variables.contains(NegationOf(var)) && branch_up_feasible) {
return IntegerLiteral::GreaterOrEqual(var, value);
} else if (branch_down_feasible) {
return IntegerLiteral::LowerOrEqual(var, value);
} else if (branch_up_feasible) {
return IntegerLiteral::GreaterOrEqual(var, value);
}
return IntegerLiteral();
}
IntegerLiteral SplitAroundLpValue(IntegerVariable var, Model* model) {
auto* parameters = model->GetOrCreate<SatParameters>();
auto* lp_dispatcher = model->GetOrCreate<LinearProgrammingDispatcher>();
const IntegerVariable positive_var = PositiveVariable(var);
const auto& it = lp_dispatcher->find(positive_var);
const LinearProgrammingConstraint* lp =
it == lp_dispatcher->end() ? nullptr : it->second;
// We only use this if the sub-lp has a solution, and depending on the value
// of exploit_all_lp_solution() if it is a pure-integer solution.
if (lp == nullptr || !lp->HasSolution()) return IntegerLiteral();
if (!parameters->exploit_all_lp_solution() && !lp->SolutionIsInteger()) {
return IntegerLiteral();
}
// TODO(user): Depending if we branch up or down, this might not exclude the
// LP value, which is potentially a bad thing.
//
// TODO(user): Why is the reduced cost doing things differently?
const IntegerValue value = IntegerValue(
static_cast<int64_t>(std::round(lp->GetSolutionValue(positive_var))));
// Because our lp solution might be from higher up in the tree, it
// is possible that value is now outside the domain of positive_var.
// In this case, this function will return an invalid literal.
return SplitAroundGivenValue(positive_var, value, model);
}
IntegerLiteral SplitUsingBestSolutionValueInRepository(
IntegerVariable var, const SharedSolutionRepository<int64_t>& solution_repo,
Model* model) {
if (solution_repo.NumSolutions() == 0) {
return IntegerLiteral();
}
const IntegerVariable positive_var = PositiveVariable(var);
const int proto_var =
model->Get<CpModelMapping>()->GetProtoVariableFromIntegerVariable(
positive_var);
if (proto_var < 0) {
return IntegerLiteral();
}
const IntegerValue value(solution_repo.GetVariableValueInSolution(
proto_var, /*solution_index=*/0));
return SplitAroundGivenValue(positive_var, value, model);
}
// TODO(user): the complexity caused by the linear scan in this heuristic and
// the one below is ok when search_branching is set to SAT_SEARCH because it is
// not executed often, but otherwise it is done for each search decision,
// which seems expensive. Improve.
std::function<BooleanOrIntegerLiteral()> FirstUnassignedVarAtItsMinHeuristic(
const std::vector<IntegerVariable>& vars, Model* model) {
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
return [/*copy*/ vars, integer_trail]() {
for (const IntegerVariable var : vars) {
const IntegerLiteral decision = AtMinValue(var, integer_trail);
if (decision.IsValid()) return BooleanOrIntegerLiteral(decision);
}
return BooleanOrIntegerLiteral();
};
}
std::function<BooleanOrIntegerLiteral()> MostFractionalHeuristic(Model* model) {
auto* lp_values = model->GetOrCreate<ModelLpValues>();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
return [lp_values, integer_trail, model]() {
double best_fractionality = 0.0;
BooleanOrIntegerLiteral decision;
for (IntegerVariable var(0); var < lp_values->size(); var += 2) {
if (integer_trail->IsFixed(var)) continue;
const double lp_value = (*lp_values)[var];
const double fractionality = std::abs(lp_value - std::round(lp_value));
if (fractionality > best_fractionality) {
best_fractionality = fractionality;
// This choose <= value if possible.
decision = BooleanOrIntegerLiteral(SplitAroundGivenValue(
var, IntegerValue(std::floor(lp_value)), model));
}
}
return decision;
};
}
std::function<BooleanOrIntegerLiteral()>
UnassignedVarWithLowestMinAtItsMinHeuristic(
const std::vector<IntegerVariable>& vars, Model* model) {
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
return [/*copy */ vars, integer_trail]() {
IntegerVariable candidate = kNoIntegerVariable;
IntegerValue candidate_lb;
for (const IntegerVariable var : vars) {
const IntegerValue lb = integer_trail->LowerBound(var);
if (lb < integer_trail->UpperBound(var) &&
(candidate == kNoIntegerVariable || lb < candidate_lb)) {
candidate = var;
candidate_lb = lb;
}
}
if (candidate == kNoIntegerVariable) return BooleanOrIntegerLiteral();
return BooleanOrIntegerLiteral(AtMinValue(candidate, integer_trail));
};
}
std::function<BooleanOrIntegerLiteral()> SequentialSearch(
std::vector<std::function<BooleanOrIntegerLiteral()>> heuristics) {
return [heuristics]() {
for (const auto& h : heuristics) {
const BooleanOrIntegerLiteral decision = h();
if (decision.HasValue()) return decision;
}
return BooleanOrIntegerLiteral();
};
}
std::function<BooleanOrIntegerLiteral()> SequentialValueSelection(
std::vector<std::function<IntegerLiteral(IntegerVariable)>>
value_selection_heuristics,
std::function<BooleanOrIntegerLiteral()> var_selection_heuristic,
Model* model) {
auto* encoder = model->GetOrCreate<IntegerEncoder>();
auto* sat_policy = model->GetOrCreate<SatDecisionPolicy>();
return [=]() {
// Get the current decision.
const BooleanOrIntegerLiteral current_decision = var_selection_heuristic();
if (!current_decision.HasValue()) return current_decision;
// When we are in the "stable" phase, we prefer to follow the SAT polarity
// heuristic.
if (current_decision.boolean_literal_index != kNoLiteralIndex &&
sat_policy->InStablePhase()) {
return current_decision;
}
// IntegerLiteral case.
if (current_decision.boolean_literal_index == kNoLiteralIndex) {
for (const auto& value_heuristic : value_selection_heuristics) {
const IntegerLiteral decision =
value_heuristic(current_decision.integer_literal.var);
if (decision.IsValid()) return BooleanOrIntegerLiteral(decision);
}
return current_decision;
}
// Boolean case. We try to decode the Boolean decision to see if it is
// associated with an integer variable.
//
// TODO(user): we will likely stop at the first non-fixed variable.
for (const IntegerVariable var : encoder->GetAllAssociatedVariables(
Literal(current_decision.boolean_literal_index))) {
// Sequentially try the value selection heuristics.
for (const auto& value_heuristic : value_selection_heuristics) {
const IntegerLiteral decision = value_heuristic(var);
if (decision.IsValid()) return BooleanOrIntegerLiteral(decision);
}
}
return current_decision;
};
}
bool LinearizedPartIsLarge(Model* model) {
auto* lp_constraints =
model->GetOrCreate<LinearProgrammingConstraintCollection>();
int num_lp_variables = 0;
for (LinearProgrammingConstraint* lp : *lp_constraints) {
num_lp_variables += lp->NumVariables();
}
const int num_integer_variables =
model->GetOrCreate<IntegerTrail>()->NumIntegerVariables().value() / 2;
return (num_integer_variables <= 2 * num_lp_variables);
}
// Note that all these heuristic do not depend on the variable being positive
// or negative.
//
// TODO(user): Experiment more with value selection heuristics.
std::function<BooleanOrIntegerLiteral()> IntegerValueSelectionHeuristic(
std::function<BooleanOrIntegerLiteral()> var_selection_heuristic,
Model* model) {
const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
std::vector<std::function<IntegerLiteral(IntegerVariable)>>
value_selection_heuristics;
// LP based value.
//
// Note that we only do this if a big enough percentage of the problem
// variables appear in the LP relaxation.
if (LinearizedPartIsLarge(model) &&
(parameters.exploit_integer_lp_solution() ||
parameters.exploit_all_lp_solution())) {
value_selection_heuristics.push_back([model](IntegerVariable var) {
return SplitAroundLpValue(PositiveVariable(var), model);
});
}
// Solution based value.
if (parameters.exploit_best_solution()) {
auto* response_manager = model->Get<SharedResponseManager>();
if (response_manager != nullptr) {
VLOG(3) << "Using best solution value selection heuristic.";
value_selection_heuristics.push_back(
[model, response_manager](IntegerVariable var) {
return SplitUsingBestSolutionValueInRepository(
var, response_manager->SolutionsRepository(), model);
});
}
}
// Objective based value.
if (parameters.exploit_objective()) {
value_selection_heuristics.push_back([model](IntegerVariable var) {
return ChooseBestObjectiveValue(var, model);
});
}
return SequentialValueSelection(value_selection_heuristics,
var_selection_heuristic, model);
}
std::function<BooleanOrIntegerLiteral()> SatSolverHeuristic(Model* model) {
SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
Trail* trail = model->GetOrCreate<Trail>();
SatDecisionPolicy* decision_policy = model->GetOrCreate<SatDecisionPolicy>();
return [sat_solver, trail, decision_policy] {
const bool all_assigned = trail->Index() == sat_solver->NumVariables();
if (all_assigned) return BooleanOrIntegerLiteral();
const Literal result = decision_policy->NextBranch();
CHECK(!sat_solver->Assignment().LiteralIsAssigned(result));
return BooleanOrIntegerLiteral(result.Index());
};
}
// TODO(user): Do we need a mechanism to reduce the range of possible gaps
// when nothing gets proven? This could be a parameter or some adaptative code.
std::function<BooleanOrIntegerLiteral()> ShaveObjectiveLb(Model* model) {
auto* objective_definition = model->GetOrCreate<ObjectiveDefinition>();
const IntegerVariable obj_var = objective_definition->objective_var;
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
auto* sat_solver = model->GetOrCreate<SatSolver>();
auto* random = model->GetOrCreate<ModelRandomGenerator>();
return [obj_var, integer_trail, sat_solver, random]() {
BooleanOrIntegerLiteral result;
const int level = sat_solver->CurrentDecisionLevel();
if (level > 0 || obj_var == kNoIntegerVariable) return result;
const IntegerValue obj_lb = integer_trail->LowerBound(obj_var);
const IntegerValue obj_ub = integer_trail->UpperBound(obj_var);
if (obj_lb == obj_ub) return result;
const IntegerValue mid = (obj_ub - obj_lb) / 2;
const IntegerValue new_ub =
obj_lb + absl::LogUniform<int64_t>(*random, 0, mid.value());
result.integer_literal = IntegerLiteral::LowerOrEqual(obj_var, new_ub);
return result;
};
}
std::function<BooleanOrIntegerLiteral()> PseudoCost(Model* model) {
auto* objective = model->Get<ObjectiveDefinition>();
const bool has_objective =
objective != nullptr && objective->objective_var != kNoIntegerVariable;
if (!has_objective) {
return []() { return BooleanOrIntegerLiteral(); };
}
auto* pseudo_costs = model->GetOrCreate<PseudoCosts>();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
return [pseudo_costs, integer_trail]() {
const IntegerVariable chosen_var = pseudo_costs->GetBestDecisionVar();
if (chosen_var == kNoIntegerVariable) return BooleanOrIntegerLiteral();
// TODO(user): This will be overridden by the value decision heuristic in
// almost all cases.
return BooleanOrIntegerLiteral(
GreaterOrEqualToMiddleValue(chosen_var, integer_trail));
};
}
// A simple heuristic for scheduling models.
std::function<BooleanOrIntegerLiteral()> SchedulingSearchHeuristic(
Model* model) {
auto* repo = model->GetOrCreate<IntervalsRepository>();
auto* heuristic = model->GetOrCreate<SearchHeuristics>();
auto* trail = model->GetOrCreate<Trail>();
auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
const int64_t randomization_size = std::max<int64_t>(
1,
model->GetOrCreate<SatParameters>()->search_random_variable_pool_size());
auto* random = model->GetOrCreate<ModelRandomGenerator>();
// To avoid to scan already fixed intervals, we use a simple reversible int.
auto* rev_int_repo = model->GetOrCreate<RevIntRepository>();
const int num_intervals = repo->NumIntervals();
int rev_fixed = 0;
bool rev_is_in_dive = false;
std::vector<IntervalVariable> intervals(num_intervals);
std::vector<IntegerValue> cached_start_mins(num_intervals);
for (IntervalVariable i(0); i < num_intervals; ++i) {
intervals[i.value()] = i;
}
// Note(user): only the model is captured for no reason.
return [=]() mutable {
struct ToSchedule {
// Variable to fix.
LiteralIndex presence = kNoLiteralIndex;
AffineExpression start;
AffineExpression end;
// Information to select best.
IntegerValue size_min = kMaxIntegerValue;
IntegerValue start_min = kMaxIntegerValue;
IntegerValue start_max = kMaxIntegerValue;
double noise = 0.5;
// We want to pack interval to the left. If two have the same start_min,
// we want to choose the one that will likely leave an easier problem for
// the other tasks.
bool operator<(const ToSchedule& other) const {
return std::tie(start_min, start_max, size_min, noise) <
std::tie(other.start_min, other.start_max, other.size_min,
other.noise);
}
// Generating random noise can take time, so we use this function to
// delay it.
bool MightBeBetter(const ToSchedule& other) const {
return std::tie(start_min, start_max) <=
std::tie(other.start_min, other.start_max);
}
};
std::vector<ToSchedule> top_decisions;
top_decisions.reserve(randomization_size);
top_decisions.resize(1);
// Save rev_fixed before we modify it.
rev_int_repo->SaveState(&rev_fixed);
// TODO(user): we should also precompute fixed precedences and only fix
// interval that have all their predecessors fixed.
for (int i = rev_fixed; i < num_intervals; ++i) {
const ToSchedule& worst = top_decisions.back();
if (rev_is_in_dive && cached_start_mins[i] > worst.start_min) {
continue;
}
const IntervalVariable interval = intervals[i];
if (repo->IsAbsent(interval)) {
std::swap(intervals[i], intervals[rev_fixed]);
std::swap(cached_start_mins[i], cached_start_mins[rev_fixed]);
++rev_fixed;
continue;
}
const AffineExpression start = repo->Start(interval);
const AffineExpression end = repo->End(interval);
if (repo->IsPresent(interval) && integer_trail->IsFixed(start) &&
integer_trail->IsFixed(end)) {
std::swap(intervals[i], intervals[rev_fixed]);
std::swap(cached_start_mins[i], cached_start_mins[rev_fixed]);
++rev_fixed;
continue;
}
ToSchedule candidate;
if (repo->IsOptional(interval)) {
// For task whose presence is still unknown, our propagators should
// have propagated the minimum time as if it was present. So this
// should reflect the earliest time at which this interval can be
// scheduled.
const Literal lit = repo->PresenceLiteral(interval);
candidate.start_min = integer_trail->ConditionalLowerBound(lit, start);
candidate.start_max = integer_trail->ConditionalUpperBound(lit, start);
} else {
candidate.start_min = integer_trail->LowerBound(start);
candidate.start_max = integer_trail->UpperBound(start);
}
cached_start_mins[i] = candidate.start_min;
if (top_decisions.size() < randomization_size ||
candidate.MightBeBetter(worst)) {
// Finish filling candidate.
//
// For variable size, we compute the min size once the start is fixed
// to time. This is needed to never pick the "artificial" makespan
// interval at the end in priority compared to intervals that still
// need to be scheduled.
candidate.start = start;
candidate.end = end;
candidate.presence = repo->IsOptional(interval)
? repo->PresenceLiteral(interval).Index()
: kNoLiteralIndex;
candidate.size_min =
std::max(integer_trail->LowerBound(repo->Size(interval)),
integer_trail->LowerBound(end) - candidate.start_min);
candidate.noise = absl::Uniform(*random, 0.0, 1.0);
if (top_decisions.size() == randomization_size) {
// Do not replace if we have a strict inequality now.
if (worst < candidate) continue;
top_decisions.pop_back();
}
top_decisions.push_back(candidate);
if (top_decisions.size() > 1) {
std::sort(top_decisions.begin(), top_decisions.end());
}
}
}
// Setup rev_is_in_dive to be true on the next call only if there was no
// backtrack since the previous call.
watcher->SetUntilNextBacktrack(&rev_is_in_dive);
const ToSchedule best =
top_decisions.size() == 1
? top_decisions.front()
: top_decisions[absl::Uniform(
*random, 0, static_cast<int>(top_decisions.size()))];
if (top_decisions.size() > 1) {
VLOG(2) << "Choose among " << top_decisions.size() << " "
<< best.start_min << " " << best.size_min
<< "[t=" << top_decisions.front().start_min
<< ", s=" << top_decisions.front().size_min
<< ", t=" << top_decisions.back().start_min
<< ", s=" << top_decisions.back().size_min << "]";
}
if (best.start_min == kMaxIntegerValue) return BooleanOrIntegerLiteral();
// Use the next_decision_override to fix in turn all the variables from
// the selected interval.
int num_times = 0;
heuristic->next_decision_override = [trail, integer_trail, best,
num_times]() mutable {
if (++num_times > 5) {
// We have been trying to fix this interval for a while. Do we miss
// some propagation? In any case, try to see if the heuristic above
// would select something else.
VLOG(3) << "Skipping ... ";
return BooleanOrIntegerLiteral();
}
// First make sure the interval is present.
if (best.presence != kNoLiteralIndex) {
if (!trail->Assignment().LiteralIsAssigned(Literal(best.presence))) {
VLOG(3) << "assign " << best.presence;
return BooleanOrIntegerLiteral(best.presence);
}
if (trail->Assignment().LiteralIsFalse(Literal(best.presence))) {
VLOG(2) << "unperformed.";
return BooleanOrIntegerLiteral();
}
}
// We assume that start_min is propagated by now.
if (!integer_trail->IsFixed(best.start)) {
const IntegerValue start_min = integer_trail->LowerBound(best.start);
VLOG(3) << "start == " << start_min;
return BooleanOrIntegerLiteral(best.start.LowerOrEqual(start_min));
}
// We assume that end_min is propagated by now.
if (!integer_trail->IsFixed(best.end)) {
const IntegerValue end_min = integer_trail->LowerBound(best.end);
VLOG(3) << "end == " << end_min;
return BooleanOrIntegerLiteral(best.end.LowerOrEqual(end_min));
}
// Everything is fixed, detach the override.
const IntegerValue start = integer_trail->LowerBound(best.start);
VLOG(2) << "Fixed @[" << start << ","
<< integer_trail->LowerBound(best.end) << "]"
<< (best.presence != kNoLiteralIndex
? absl::StrCat(" presence=",
Literal(best.presence).DebugString())
: "")
<< (best.start_min < start ? absl::StrCat(" start_at_selection=",
best.start_min.value())
: "");
return BooleanOrIntegerLiteral();
};
return heuristic->next_decision_override();
};
}
namespace {
bool PrecedenceIsBetter(SchedulingConstraintHelper* helper, int a,
SchedulingConstraintHelper* other_helper, int other_a) {
return std::make_tuple(helper->StartMin(a), helper->StartMax(a),
helper->SizeMin(a)) <
std::make_tuple(other_helper->StartMin(other_a),
other_helper->StartMax(other_a),
other_helper->SizeMin(other_a));
}
} // namespace
// The algo goes as follow:
// - For each disjunctive, consider the intervals by start time, consider
// adding the first precedence between overlapping interval.
// - Take the smallest start time amongst all disjunctive.
std::function<BooleanOrIntegerLiteral()> DisjunctivePrecedenceSearchHeuristic(
Model* model) {
auto* repo = model->GetOrCreate<IntervalsRepository>();
return [repo]() {
SchedulingConstraintHelper* best_helper = nullptr;
int best_before;
int best_after;
for (SchedulingConstraintHelper* helper : repo->AllDisjunctiveHelpers()) {
if (!helper->SynchronizeAndSetTimeDirection(true)) {
return BooleanOrIntegerLiteral();
}
// TODO(user): tie break by size/start-max
// TODO(user): Use conditional lower bounds? note that in automatic search
// all precedence will be fixed before this is called though. In fixed
// search maybe we should use the other SchedulingSearchHeuristic().
int a = -1;
for (auto [b, time] : helper->TaskByIncreasingStartMin()) {
if (helper->IsAbsent(b)) continue;
if (a == -1 || helper->EndMin(a) <= helper->StartMin(b)) {
a = b;
continue;
}
// Swap (a,b) if they have the same start_min.
if (PrecedenceIsBetter(helper, b, helper, a)) {
std::swap(a, b);
// Corner case in case b can fit before a (size zero)
if (helper->EndMin(a) <= helper->StartMin(b)) {
a = b;
continue;
}
}
// TODO(Fdid): Also compare the second part of the precedence in
// PrecedenceIsBetter() and not just the interval before?
if (best_helper == nullptr ||
PrecedenceIsBetter(helper, a, best_helper, best_before)) {
best_helper = helper;
best_before = a;
best_after = b;
}
break;
}
}
if (best_helper != nullptr) {
VLOG(2) << "New disjunctive precedence: "
<< best_helper->TaskDebugString(best_before) << " "
<< best_helper->TaskDebugString(best_after);
const IntervalVariable a = best_helper->IntervalVariables()[best_before];
const IntervalVariable b = best_helper->IntervalVariables()[best_after];
repo->CreateDisjunctivePrecedenceLiteral(a, b);
return BooleanOrIntegerLiteral(repo->GetPrecedenceLiteral(a, b));
}
return BooleanOrIntegerLiteral();
};
}
// The algo goes as follow:
// - Build a profile of all the tasks packed to the right as long as that is
// feasible.
// - If we can't grow the profile, we have identified a set of tasks that all
// overlap if they are packed on the right, and whose sum of demand exceed
// the capacity.
// - Look for two tasks in that set that can be made non-overlapping, and take
// a "precedence" decision between them.
std::function<BooleanOrIntegerLiteral()> CumulativePrecedenceSearchHeuristic(
Model* model) {
auto* repo = model->GetOrCreate<IntervalsRepository>();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
auto* trail = model->GetOrCreate<Trail>();
auto* search_helper = model->GetOrCreate<IntegerSearchHelper>();
return [repo, integer_trail, trail, search_helper]() {
SchedulingConstraintHelper* best_helper = nullptr;
int best_before = 0;
int best_after = 0;
for (const auto h : repo->AllCumulativeHelpers()) {
auto* helper = h.task_helper;
if (!helper->SynchronizeAndSetTimeDirection(true)) {
return BooleanOrIntegerLiteral();
}
const int num_tasks = helper->NumTasks();
std::vector<IntegerValue> added_demand(num_tasks, 0);
// We use a similar algo as in BuildProfile() in timetable.cc
const auto& by_smin = helper->TaskByIncreasingStartMin();
const auto& by_emin = helper->TaskByIncreasingEndMin();
const IntegerValue capacity_max = integer_trail->UpperBound(h.capacity);
// Start and height of the currently built profile rectangle.
IntegerValue current_height = 0;
int first_skipped_task = -1;
int next_end = 0;
int next_start = 0;
int num_added = 0;
bool found = false;
while (!found && next_end < num_tasks) {
IntegerValue time = by_emin[next_end].time;
if (next_start < num_tasks) {
time = std::min(time, by_smin[next_start].time);
}
// Remove added task ending there.
// Set their demand to zero.
while (next_end < num_tasks && by_emin[next_end].time == time) {
const int t = by_emin[next_end].task_index;
if (!helper->IsPresent(t)) continue;
if (added_demand[t] > 0) {
current_height -= added_demand[t];
added_demand[t] = 0;
} else {
// Corner case if task is of duration zero.
added_demand[t] = -1;
}
++next_end;
}
// Add new task starting here.
// If the task cannot be added we have a candidate for precedence.
// TODO(user): tie-break tasks not fitting in the profile smartly.
while (next_start < num_tasks && by_smin[next_start].time == time) {
const int t = by_smin[next_start].task_index;
if (!helper->IsPresent(t)) continue;
if (added_demand[t] == -1) continue; // Corner case.
const IntegerValue demand_min = h.demand_helper->DemandMin(t);
if (current_height + demand_min <= capacity_max) {
++num_added;
added_demand[t] = demand_min;
current_height += demand_min;
} else if (first_skipped_task == -1) {
// We should have everything needed here to add a new precedence.
first_skipped_task = t;
found = true;
break;
}
++next_start;
}
}
// If packing everything to the left is feasible, continue.
if (first_skipped_task == -1) {
CHECK_EQ(num_added, num_tasks);
continue;
}
// We will use a bunch of heuristic to add a new precedence. All the task
// in open_tasks cannot share a time point since they exceed the capacity.
// Moreover if we pack all to the left, they have an intersecting point.
// So we should be able to make two of them disjoint
std::vector<int> open_tasks;
for (int t = 0; t < num_tasks; ++t) {
if (added_demand[t] <= 0) continue;
open_tasks.push_back(t);
}
open_tasks.push_back(first_skipped_task);
// TODO(user): If the two box cannot overlap because of high demand, use
// repo.CreateDisjunctivePrecedenceLiteral() instead.
//
// TODO(user): Add heuristic ordering for creating interesting precedence
// first.
bool found_precedence_to_add = false;
std::vector<Literal> conflict;
helper->ClearReason();
for (const int s : open_tasks) {
for (const int t : open_tasks) {
if (s == t) continue;
// Can we add s <= t ?
// All the considered tasks are intersecting if on the left.
CHECK_LT(helper->StartMin(s), helper->EndMin(t));
CHECK_LT(helper->StartMin(t), helper->EndMin(s));
// skip if we already have a literal created and assigned to false.
const IntervalVariable a = helper->IntervalVariables()[s];
const IntervalVariable b = helper->IntervalVariables()[t];
const LiteralIndex existing = repo->GetPrecedenceLiteral(a, b);
if (existing != kNoLiteralIndex) {
// It shouldn't be able to be true here otherwise we will have s and
// t disjoint.
CHECK(!trail->Assignment().LiteralIsTrue(Literal(existing)))
<< helper->TaskDebugString(s) << " ( <= ?) "
<< helper->TaskDebugString(t);
// This should always be true in normal usage after SAT search has
// fixed all literal, but if it is not, we can just return this
// decision.
if (trail->Assignment().LiteralIsFalse(Literal(existing))) {
conflict.push_back(Literal(existing));
continue;
}
} else {
// Make sure s could be before t.
if (helper->EndMin(s) > helper->StartMax(t)) {
helper->AddReasonForBeingBefore(t, s);
continue;
}
// It shouldn't be able to fail since s can be before t.
CHECK(repo->CreatePrecedenceLiteral(a, b));
}
// Branch on that precedence.
best_helper = helper;
best_before = s;
best_after = t;
found_precedence_to_add = true;
break;
}
if (found_precedence_to_add) break;
}
if (found_precedence_to_add) break;
// If no precedence can be created, and all precedence are assigned to
// false we have a conflict since all these interval must intersect but
// cannot fit in the capacity!
//
// TODO(user): We need to add the reason for demand_min and capacity_max.
// TODO(user): unfortunately we can't report it from here.
std::vector<IntegerLiteral> integer_reason =
*helper->MutableIntegerReason();
if (!h.capacity.IsConstant()) {
integer_reason.push_back(
integer_trail->UpperBoundAsLiteral(h.capacity));
}
const auto& demands = h.demand_helper->Demands();
for (const int t : open_tasks) {
if (helper->IsOptional(t)) {
CHECK(trail->Assignment().LiteralIsTrue(helper->PresenceLiteral(t)));
conflict.push_back(helper->PresenceLiteral(t).Negated());
}
const AffineExpression d = demands[t];
if (!d.IsConstant()) {
integer_reason.push_back(integer_trail->LowerBoundAsLiteral(d));
}
}
integer_trail->ReportConflict(conflict, integer_reason);
search_helper->NotifyThatConflictWasFoundDuringGetDecision();
if (VLOG_IS_ON(2)) {
LOG(INFO) << "Conflict between precedences !";
for (const int t : open_tasks) LOG(INFO) << helper->TaskDebugString(t);
}
return BooleanOrIntegerLiteral();
}
// TODO(user): add heuristic criteria, right now we stop at first
// one. See above.
if (best_helper != nullptr) {
VLOG(2) << "New precedence: " << best_helper->TaskDebugString(best_before)
<< " " << best_helper->TaskDebugString(best_after);
const IntervalVariable a = best_helper->IntervalVariables()[best_before];
const IntervalVariable b = best_helper->IntervalVariables()[best_after];
repo->CreatePrecedenceLiteral(a, b);
return BooleanOrIntegerLiteral(repo->GetPrecedenceLiteral(a, b));
}
return BooleanOrIntegerLiteral();
};
}
std::function<BooleanOrIntegerLiteral()> RandomizeOnRestartHeuristic(
bool lns_mode, Model* model) {
SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
SatDecisionPolicy* decision_policy = model->GetOrCreate<SatDecisionPolicy>();
SearchHeuristics& heuristics = *model->GetOrCreate<SearchHeuristics>();
// TODO(user): Add other policies and perform more experiments.
std::function<BooleanOrIntegerLiteral()> sat_policy =
SatSolverHeuristic(model);
std::vector<std::function<BooleanOrIntegerLiteral()>> policies;
std::vector<double> weights;
// Add sat search + fixed_search (to complete the search).
policies.push_back(SequentialSearch({sat_policy, heuristics.fixed_search}));
weights.push_back(5);
// Adds user defined search if present.
if (heuristics.user_search != nullptr) {
policies.push_back(SequentialSearch(
{heuristics.user_search, sat_policy, heuristics.fixed_search}));
weights.push_back(1);
}
// Always add heuristic search.
policies.push_back(SequentialSearch({heuristics.heuristic_search, sat_policy,
heuristics.integer_completion_search}));
weights.push_back(1);
// The higher weight for the sat policy is because this policy actually
// contains a lot of variation as we randomize the sat parameters.
// TODO(user): Do more experiments to find better distribution.
std::discrete_distribution<int> var_dist(weights.begin(), weights.end());
// Value selection.
std::vector<std::function<IntegerLiteral(IntegerVariable)>>
value_selection_heuristics;
std::vector<int> value_selection_weight;
// LP Based value.
const int linearization_level =
model->GetOrCreate<SatParameters>()->linearization_level();
if (LinearizedPartIsLarge(model)) {
value_selection_heuristics.push_back([model](IntegerVariable var) {
return SplitAroundLpValue(PositiveVariable(var), model);
});
value_selection_weight.push_back(linearization_level == 2 ? 4 : 2);
}
// Solution based value.
if (!lns_mode) {
auto* response_manager = model->Get<SharedResponseManager>();
CHECK(response_manager != nullptr);
value_selection_heuristics.push_back(
[model, response_manager](IntegerVariable var) {
return SplitUsingBestSolutionValueInRepository(
var, response_manager->SolutionsRepository(), model);
});
value_selection_weight.push_back(5);
}
// Min value.
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
value_selection_heuristics.push_back([integer_trail](IntegerVariable var) {
return AtMinValue(var, integer_trail);
});
value_selection_weight.push_back(1);
// Special case: Don't change the decision value.
value_selection_weight.push_back(10);
// TODO(user): These distribution values are just guessed values. They
// need to be tuned.
std::discrete_distribution<int> val_dist(value_selection_weight.begin(),
value_selection_weight.end());
int policy_index = 0;
int val_policy_index = 0;
auto* encoder = model->GetOrCreate<IntegerEncoder>();
auto* objective = model->Get<ObjectiveDefinition>();
return [=]() mutable {
if (sat_solver->CurrentDecisionLevel() == 0) {
auto* random = model->GetOrCreate<ModelRandomGenerator>();
RandomizeDecisionHeuristic(*random, model->GetOrCreate<SatParameters>());
decision_policy->ResetDecisionHeuristic();
// Set some assignment preference.
// TODO(user): Also use LP value as assignment like in Bop.
if (objective != nullptr && absl::Bernoulli(*random, 0.2)) {
// Use Boolean objective as assignment preference.
IntegerValue max_abs_weight = 0;
for (const IntegerValue coeff : objective->coeffs) {
max_abs_weight = std::max(max_abs_weight, IntTypeAbs(coeff));
}
const double max_abs_weight_double = ToDouble(max_abs_weight);
const int objective_size = objective->vars.size();
for (int i = 0; i < objective_size; ++i) {
const IntegerVariable var = objective->vars[i];
if (integer_trail->LowerBound(var) != 0) continue;
if (integer_trail->UpperBound(var) != 1) continue;
const LiteralIndex index = encoder->GetAssociatedLiteral(
IntegerLiteral::GreaterOrEqual(var, 1));
if (index == kNoLiteralIndex) continue;
const Literal literal(index);
const IntegerValue coeff = objective->coeffs[i];
const double abs_weight =
std::abs(ToDouble(objective->coeffs[i])) / max_abs_weight_double;
// Because this is a minimization problem, we prefer to assign a
// Boolean variable to its "low" objective value. So if a literal
// has a positive weight when true, we want to set it to false.
decision_policy->SetAssignmentPreference(