forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimization.cc
1978 lines (1757 loc) · 78.2 KB
/
optimization.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/optimization.h"
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "ortools/base/cleanup.h"
#include "ortools/base/int_type.h"
#include "ortools/base/logging.h"
#include "ortools/base/macros.h"
#include "ortools/base/map_util.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/timer.h"
#if !defined(__PORTABLE_PLATFORM__) && defined(USE_SCIP)
#include "ortools/linear_solver/linear_solver.h"
#include "ortools/linear_solver/linear_solver.pb.h"
#endif // __PORTABLE_PLATFORM__
#include "ortools/base/random.h"
#include "ortools/port/proto_utils.h"
#include "ortools/sat/boolean_problem.h"
#include "ortools/sat/encoding.h"
#include "ortools/sat/integer_expr.h"
#include "ortools/sat/pb_constraint.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/util.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
namespace {
// Used to log messages to stdout or to the normal logging framework according
// to the given LogBehavior value.
class Logger {
public:
explicit Logger(LogBehavior v) : use_stdout_(v == STDOUT_LOG) {}
void Log(const std::string& message) {
if (use_stdout_) {
absl::PrintF("%s\n", message);
} else {
LOG(INFO) << message;
}
}
private:
bool use_stdout_;
};
// Outputs the current objective value in the cnf output format.
// Note that this function scale the given objective.
std::string CnfObjectiveLine(const LinearBooleanProblem& problem,
Coefficient objective) {
const double scaled_objective =
AddOffsetAndScaleObjectiveValue(problem, objective);
return absl::StrFormat("o %d", static_cast<int64_t>(scaled_objective));
}
struct LiteralWithCoreIndex {
LiteralWithCoreIndex(Literal l, int i) : literal(l), core_index(i) {}
Literal literal;
int core_index;
};
// Deletes the given indices from a vector. The given indices must be sorted in
// increasing order. The order of the non-deleted entries in the vector is
// preserved.
template <typename Vector>
void DeleteVectorIndices(const std::vector<int>& indices, Vector* v) {
int new_size = 0;
int indices_index = 0;
for (int i = 0; i < v->size(); ++i) {
if (indices_index < indices.size() && i == indices[indices_index]) {
++indices_index;
} else {
(*v)[new_size] = (*v)[i];
++new_size;
}
}
v->resize(new_size);
}
// In the Fu & Malik algorithm (or in WPM1), when two cores overlap, we
// artificially introduce symmetries. More precisely:
//
// The picture below shows two cores with index 0 and 1, with one blocking
// variable per '-' and with the variables ordered from left to right (by their
// assumptions index). The blocking variables will be the one added to "relax"
// the core for the next iteration.
//
// 1: -------------------------------
// 0: ------------------------------------
//
// The 2 following assignment of the blocking variables are equivalent.
// Remember that exactly one blocking variable per core must be assigned to 1.
//
// 1: ----------------------1--------
// 0: --------1---------------------------
//
// and
//
// 1: ---------------------------1---
// 0: ---1--------------------------------
//
// This class allows to add binary constraints excluding the second possibility.
// Basically, each time a new core is added, if two of its blocking variables
// (b1, b2) have the same assumption index of two blocking variables from
// another core (c1, c2), then we forbid the assignment c1 true and b2 true.
//
// Reference: C Ansótegui, ML Bonet, J Levy, "Sat-based maxsat algorithms",
// Artificial Intelligence, 2013 - Elsevier.
class FuMalikSymmetryBreaker {
public:
FuMalikSymmetryBreaker() {}
// Must be called before a new core is processed.
void StartResolvingNewCore(int new_core_index) {
literal_by_core_.resize(new_core_index);
for (int i = 0; i < new_core_index; ++i) {
literal_by_core_[i].clear();
}
}
// This should be called for each blocking literal b of the new core. The
// assumption_index identify the soft clause associated to the given blocking
// literal. Note that between two StartResolvingNewCore() calls,
// ProcessLiteral() is assumed to be called with different assumption_index.
//
// Changing the order of the calls will not change the correctness, but will
// change the symmetry-breaking clause produced.
//
// Returns a set of literals which can't be true at the same time as b (under
// symmetry breaking).
std::vector<Literal> ProcessLiteral(int assumption_index, Literal b) {
if (assumption_index >= info_by_assumption_index_.size()) {
info_by_assumption_index_.resize(assumption_index + 1);
}
// Compute the function result.
// info_by_assumption_index_[assumption_index] will contain all the pairs
// (blocking_literal, core) of the previous resolved cores at the same
// assumption index as b.
std::vector<Literal> result;
for (LiteralWithCoreIndex data :
info_by_assumption_index_[assumption_index]) {
// literal_by_core_ will contain all the blocking literal of a given core
// with an assumption_index that was used in one of the ProcessLiteral()
// calls since the last StartResolvingNewCore().
//
// Note that there can be only one such literal by core, so we will not
// add duplicates.
result.insert(result.end(), literal_by_core_[data.core_index].begin(),
literal_by_core_[data.core_index].end());
}
// Update the internal data structure.
for (LiteralWithCoreIndex data :
info_by_assumption_index_[assumption_index]) {
literal_by_core_[data.core_index].push_back(data.literal);
}
info_by_assumption_index_[assumption_index].push_back(
LiteralWithCoreIndex(b, literal_by_core_.size()));
return result;
}
// Deletes the given assumption indices.
void DeleteIndices(const std::vector<int>& indices) {
DeleteVectorIndices(indices, &info_by_assumption_index_);
}
// This is only used in WPM1 to forget all the information related to a given
// assumption_index.
void ClearInfo(int assumption_index) {
CHECK_LE(assumption_index, info_by_assumption_index_.size());
info_by_assumption_index_[assumption_index].clear();
}
// This is only used in WPM1 when a new assumption_index is created.
void AddInfo(int assumption_index, Literal b) {
CHECK_GE(assumption_index, info_by_assumption_index_.size());
info_by_assumption_index_.resize(assumption_index + 1);
info_by_assumption_index_[assumption_index].push_back(
LiteralWithCoreIndex(b, literal_by_core_.size()));
}
private:
std::vector<std::vector<LiteralWithCoreIndex>> info_by_assumption_index_;
std::vector<std::vector<Literal>> literal_by_core_;
DISALLOW_COPY_AND_ASSIGN(FuMalikSymmetryBreaker);
};
} // namespace
void MinimizeCoreWithPropagation(TimeLimit* limit, SatSolver* solver,
std::vector<Literal>* core) {
if (solver->IsModelUnsat()) return;
std::set<LiteralIndex> moved_last;
std::vector<Literal> candidate(core->begin(), core->end());
solver->Backtrack(0);
solver->SetAssumptionLevel(0);
if (!solver->FinishPropagation()) return;
while (!limit->LimitReached()) {
// We want each literal in candidate to appear last once in our propagation
// order. We want to do that while maximizing the reutilization of the
// current assignment prefix, that is minimizing the number of
// decision/progagation we need to perform.
const int target_level = MoveOneUnprocessedLiteralLast(
moved_last, solver->CurrentDecisionLevel(), &candidate);
if (target_level == -1) break;
solver->Backtrack(target_level);
while (!solver->IsModelUnsat() && !limit->LimitReached() &&
solver->CurrentDecisionLevel() < candidate.size()) {
const Literal decision = candidate[solver->CurrentDecisionLevel()];
if (solver->Assignment().LiteralIsTrue(decision)) {
candidate.erase(candidate.begin() + solver->CurrentDecisionLevel());
continue;
} else if (solver->Assignment().LiteralIsFalse(decision)) {
// This is a "weird" API to get the subset of decisions that caused
// this literal to be false with reason analysis.
solver->EnqueueDecisionAndBacktrackOnConflict(decision);
candidate = solver->GetLastIncompatibleDecisions();
break;
} else {
solver->EnqueueDecisionAndBackjumpOnConflict(decision);
}
}
if (candidate.empty() || solver->IsModelUnsat()) return;
moved_last.insert(candidate.back().Index());
}
solver->Backtrack(0);
solver->SetAssumptionLevel(0);
if (candidate.size() < core->size()) {
VLOG(1) << "minimization " << core->size() << " -> " << candidate.size();
core->assign(candidate.begin(), candidate.end());
}
}
// This algorithm works by exploiting the unsat core returned by the SAT solver
// when the problem is UNSAT. It starts by trying to solve the decision problem
// where all the objective variables are set to their value with minimal cost,
// and relax in each step some of these fixed variables until the problem
// becomes satisfiable.
SatSolver::Status SolveWithFuMalik(LogBehavior log,
const LinearBooleanProblem& problem,
SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
FuMalikSymmetryBreaker symmetry;
// blocking_clauses will contains a set of clauses that are currently added to
// the initial problem.
//
// Initially, each clause just contains a literal associated to an objective
// variable with non-zero cost. Setting all these literals to true will lead
// to the lowest possible objective.
//
// During the algorithm, "blocking" literals will be added to each clause.
// Moreover each clause will contain an extra "assumption" literal stored in
// the separate assumptions vector (in its negated form).
//
// The meaning of a given clause will always be:
// If the assumption literal and all blocking literals are false, then the
// "objective" literal (which is the first one in the clause) must be true.
// When the "objective" literal is true, its variable (which have a non-zero
// cost) is set to the value that minimize the objective cost.
//
// ex: If a variable "x" as a cost of 3, its cost contribution is smaller when
// it is set to false (since it will contribute to zero instead of 3).
std::vector<std::vector<Literal>> blocking_clauses;
std::vector<Literal> assumptions;
// Initialize blocking_clauses and assumptions.
const LinearObjective& objective = problem.objective();
CHECK_GT(objective.coefficients_size(), 0);
const Coefficient unique_objective_coeff(std::abs(objective.coefficients(0)));
for (int i = 0; i < objective.literals_size(); ++i) {
CHECK_EQ(std::abs(objective.coefficients(i)), unique_objective_coeff)
<< "The basic Fu & Malik algorithm needs constant objective coeffs.";
const Literal literal(objective.literals(i));
// We want to minimize the cost when this literal is true.
const Literal min_literal =
objective.coefficients(i) > 0 ? literal.Negated() : literal;
blocking_clauses.push_back(std::vector<Literal>(1, min_literal));
// Note that initialy, we do not create any extra variables.
assumptions.push_back(min_literal);
}
// Print the number of variable with a non-zero cost.
logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
assumptions.size(), problem.num_variables(),
problem.constraints_size()));
// Starts the algorithm. Each loop will solve the problem under the given
// assumptions, and if unsat, will relax exactly one of the objective
// variables (from the unsat core) to be in its "costly" state. When the
// algorithm terminates, the number of iterations is exactly the minimal
// objective value.
for (int iter = 0;; ++iter) {
const SatSolver::Status result =
solver->ResetAndSolveWithGivenAssumptions(assumptions);
if (result == SatSolver::FEASIBLE) {
ExtractAssignment(problem, *solver, solution);
Coefficient objective = ComputeObjectiveValue(problem, *solution);
logger.Log(CnfObjectiveLine(problem, objective));
return SatSolver::FEASIBLE;
}
if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
// The interesting case: we have an unsat core.
//
// We need to add new "blocking" variables b_i for all the objective
// variable appearing in the core. Moreover, we will only relax as little
// as possible (to not miss the optimal), so we will enforce that the sum
// of the b_i is exactly one.
std::vector<Literal> core = solver->GetLastIncompatibleDecisions();
MinimizeCore(solver, &core);
solver->Backtrack(0);
// Print the search progress.
logger.Log(absl::StrFormat("c iter:%d core:%u", iter, core.size()));
// Special case for a singleton core.
if (core.size() == 1) {
// Find the index of the "objective" variable that need to be fixed in
// its "costly" state.
const int index =
std::find(assumptions.begin(), assumptions.end(), core[0]) -
assumptions.begin();
CHECK_LT(index, assumptions.size());
// Fix it. We also fix all the associated blocking variables if any.
if (!solver->AddUnitClause(core[0].Negated())) {
return SatSolver::INFEASIBLE;
}
for (Literal b : blocking_clauses[index]) {
if (!solver->AddUnitClause(b.Negated())) return SatSolver::INFEASIBLE;
}
// Erase this entry from the current "objective"
std::vector<int> to_delete(1, index);
DeleteVectorIndices(to_delete, &assumptions);
DeleteVectorIndices(to_delete, &blocking_clauses);
symmetry.DeleteIndices(to_delete);
} else {
symmetry.StartResolvingNewCore(iter);
// We will add 2 * |core.size()| variables.
const int old_num_variables = solver->NumVariables();
if (core.size() == 2) {
// Special case. If core.size() == 2, we can use only one blocking
// variable (the other one beeing its negation). This actually do happen
// quite often in practice, so it is worth it.
solver->SetNumVariables(old_num_variables + 3);
} else {
solver->SetNumVariables(old_num_variables + 2 * core.size());
}
// Temporary vectors for the constraint (sum new blocking variable == 1).
std::vector<LiteralWithCoeff> at_most_one_constraint;
std::vector<Literal> at_least_one_constraint;
// This will be set to false if the problem becomes unsat while adding a
// new clause. This is unlikely, but may be possible.
bool ok = true;
// Loop over the core.
int index = 0;
for (int i = 0; i < core.size(); ++i) {
// Since the assumptions appear in order in the core, we can find the
// relevant "objective" variable efficiently with a simple linear scan
// in the assumptions vector (done with index).
index =
std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
assumptions.begin();
CHECK_LT(index, assumptions.size());
// The new blocking and assumption variables for this core entry.
const Literal a(BooleanVariable(old_num_variables + i), true);
Literal b(BooleanVariable(old_num_variables + core.size() + i), true);
if (core.size() == 2) {
b = Literal(BooleanVariable(old_num_variables + 2), true);
if (i == 1) b = b.Negated();
}
// Symmetry breaking clauses.
for (Literal l : symmetry.ProcessLiteral(index, b)) {
ok &= solver->AddBinaryClause(l.Negated(), b.Negated());
}
// Note(user): There is more than one way to encode the algorithm in
// SAT. Here we "delete" the old blocking clause and add a new one. In
// the WPM1 algorithm below, the blocking clause is decomposed into
// 3-SAT and we don't need to delete anything.
// First, fix the old "assumption" variable to false, which has the
// effect of deleting the old clause from the solver.
if (assumptions[index].Variable() >= problem.num_variables()) {
CHECK(solver->AddUnitClause(assumptions[index].Negated()));
}
// Add the new blocking variable.
blocking_clauses[index].push_back(b);
// Add the new clause to the solver. Temporary including the
// assumption, but removing it right afterwards.
blocking_clauses[index].push_back(a);
ok &= solver->AddProblemClause(blocking_clauses[index]);
blocking_clauses[index].pop_back();
// For the "== 1" constraint on the blocking literals.
at_most_one_constraint.push_back(LiteralWithCoeff(b, 1.0));
at_least_one_constraint.push_back(b);
// The new assumption variable replace the old one.
assumptions[index] = a.Negated();
}
// Add the "<= 1" side of the "== 1" constraint.
ok &= solver->AddLinearConstraint(false, Coefficient(0), true,
Coefficient(1.0),
&at_most_one_constraint);
// TODO(user): The algorithm does not really need the >= 1 side of this
// constraint. Initial investigation shows that it doesn't really help,
// but investigate more.
if (/* DISABLES CODE */ (false)) {
ok &= solver->AddProblemClause(at_least_one_constraint);
}
if (!ok) {
LOG(INFO) << "Infeasible while adding a clause.";
return SatSolver::INFEASIBLE;
}
}
}
}
SatSolver::Status SolveWithWPM1(LogBehavior log,
const LinearBooleanProblem& problem,
SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
FuMalikSymmetryBreaker symmetry;
// The current lower_bound on the cost.
// It will be correct after the initialization.
Coefficient lower_bound(static_cast<int64_t>(problem.objective().offset()));
Coefficient upper_bound(std::numeric_limits<int64_t>::max());
// The assumption literals and their associated cost.
std::vector<Literal> assumptions;
std::vector<Coefficient> costs;
std::vector<Literal> reference;
// Initialization.
const LinearObjective& objective = problem.objective();
CHECK_GT(objective.coefficients_size(), 0);
for (int i = 0; i < objective.literals_size(); ++i) {
const Literal literal(objective.literals(i));
const Coefficient coeff(objective.coefficients(i));
// We want to minimize the cost when the assumption is true.
// Note that initially, we do not create any extra variables.
if (coeff > 0) {
assumptions.push_back(literal.Negated());
costs.push_back(coeff);
} else {
assumptions.push_back(literal);
costs.push_back(-coeff);
lower_bound += coeff;
}
}
reference = assumptions;
// This is used by the "stratified" approach.
Coefficient stratified_lower_bound =
*std::max_element(costs.begin(), costs.end());
// Print the number of variables with a non-zero cost.
logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
assumptions.size(), problem.num_variables(),
problem.constraints_size()));
for (int iter = 0;; ++iter) {
// This is called "hardening" in the literature.
// Basically, we know that there is only hardening_threshold weight left
// to distribute, so any assumption with a greater cost than this can never
// be false. We fix it instead of treating it as an assumption.
solver->Backtrack(0);
const Coefficient hardening_threshold = upper_bound - lower_bound;
CHECK_GE(hardening_threshold, 0);
std::vector<int> to_delete;
int num_above_threshold = 0;
for (int i = 0; i < assumptions.size(); ++i) {
if (costs[i] > hardening_threshold) {
if (!solver->AddUnitClause(assumptions[i])) {
return SatSolver::INFEASIBLE;
}
to_delete.push_back(i);
++num_above_threshold;
} else {
// This impact the stratification heuristic.
if (solver->Assignment().LiteralIsTrue(assumptions[i])) {
to_delete.push_back(i);
}
}
}
if (!to_delete.empty()) {
logger.Log(absl::StrFormat("c fixed %u assumptions, %d with cost > %d",
to_delete.size(), num_above_threshold,
hardening_threshold.value()));
DeleteVectorIndices(to_delete, &assumptions);
DeleteVectorIndices(to_delete, &costs);
DeleteVectorIndices(to_delete, &reference);
symmetry.DeleteIndices(to_delete);
}
// This is the "stratification" part.
// Extract the assumptions with a cost >= stratified_lower_bound.
std::vector<Literal> assumptions_subset;
for (int i = 0; i < assumptions.size(); ++i) {
if (costs[i] >= stratified_lower_bound) {
assumptions_subset.push_back(assumptions[i]);
}
}
const SatSolver::Status result =
solver->ResetAndSolveWithGivenAssumptions(assumptions_subset);
if (result == SatSolver::FEASIBLE) {
// If not all assumptions were taken, continue with a lower stratified
// bound. Otherwise we have an optimal solution!
//
// TODO(user): Try more advanced variant where the bound is lowered by
// more than this minimal amount.
const Coefficient old_lower_bound = stratified_lower_bound;
for (Coefficient cost : costs) {
if (cost < old_lower_bound) {
if (stratified_lower_bound == old_lower_bound ||
cost > stratified_lower_bound) {
stratified_lower_bound = cost;
}
}
}
ExtractAssignment(problem, *solver, solution);
DCHECK(IsAssignmentValid(problem, *solution));
const Coefficient objective_offset(
static_cast<int64_t>(problem.objective().offset()));
const Coefficient objective = ComputeObjectiveValue(problem, *solution);
if (objective + objective_offset < upper_bound) {
logger.Log(CnfObjectiveLine(problem, objective));
upper_bound = objective + objective_offset;
}
if (stratified_lower_bound < old_lower_bound) continue;
return SatSolver::FEASIBLE;
}
if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
// The interesting case: we have an unsat core.
//
// We need to add new "blocking" variables b_i for all the objective
// variables appearing in the core. Moreover, we will only relax as little
// as possible (to not miss the optimal), so we will enforce that the sum
// of the b_i is exactly one.
std::vector<Literal> core = solver->GetLastIncompatibleDecisions();
MinimizeCore(solver, &core);
solver->Backtrack(0);
// Compute the min cost of all the assertions in the core.
// The lower bound will be updated by that much.
Coefficient min_cost = kCoefficientMax;
{
int index = 0;
for (int i = 0; i < core.size(); ++i) {
index =
std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
assumptions.begin();
CHECK_LT(index, assumptions.size());
min_cost = std::min(min_cost, costs[index]);
}
}
lower_bound += min_cost;
// Print the search progress.
logger.Log(absl::StrFormat(
"c iter:%d core:%u lb:%d min_cost:%d strat:%d", iter, core.size(),
lower_bound.value(), min_cost.value(), stratified_lower_bound.value()));
// This simple line helps a lot on the packup-wpms instances!
//
// TODO(user): That was because of a bug before in the way
// stratified_lower_bound was decremented, not sure it helps that much now.
if (min_cost > stratified_lower_bound) {
stratified_lower_bound = min_cost;
}
// Special case for a singleton core.
if (core.size() == 1) {
// Find the index of the "objective" variable that need to be fixed in
// its "costly" state.
const int index =
std::find(assumptions.begin(), assumptions.end(), core[0]) -
assumptions.begin();
CHECK_LT(index, assumptions.size());
// Fix it.
if (!solver->AddUnitClause(core[0].Negated())) {
return SatSolver::INFEASIBLE;
}
// Erase this entry from the current "objective".
std::vector<int> to_delete(1, index);
DeleteVectorIndices(to_delete, &assumptions);
DeleteVectorIndices(to_delete, &costs);
DeleteVectorIndices(to_delete, &reference);
symmetry.DeleteIndices(to_delete);
} else {
symmetry.StartResolvingNewCore(iter);
// We will add 2 * |core.size()| variables.
const int old_num_variables = solver->NumVariables();
if (core.size() == 2) {
// Special case. If core.size() == 2, we can use only one blocking
// variable (the other one beeing its negation). This actually do happen
// quite often in practice, so it is worth it.
solver->SetNumVariables(old_num_variables + 3);
} else {
solver->SetNumVariables(old_num_variables + 2 * core.size());
}
// Temporary vectors for the constraint (sum new blocking variable == 1).
std::vector<LiteralWithCoeff> at_most_one_constraint;
std::vector<Literal> at_least_one_constraint;
// This will be set to false if the problem becomes unsat while adding a
// new clause. This is unlikely, but may be possible.
bool ok = true;
// Loop over the core.
int index = 0;
for (int i = 0; i < core.size(); ++i) {
// Since the assumptions appear in order in the core, we can find the
// relevant "objective" variable efficiently with a simple linear scan
// in the assumptions vector (done with index).
index =
std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
assumptions.begin();
CHECK_LT(index, assumptions.size());
// The new blocking and assumption variables for this core entry.
const Literal a(BooleanVariable(old_num_variables + i), true);
Literal b(BooleanVariable(old_num_variables + core.size() + i), true);
if (core.size() == 2) {
b = Literal(BooleanVariable(old_num_variables + 2), true);
if (i == 1) b = b.Negated();
}
// a false & b false => previous assumptions (which was false).
const Literal old_a = assumptions[index];
ok &= solver->AddTernaryClause(a, b, old_a);
// Optional. Also add the two implications a => x and b => x where x is
// the negation of the previous assumption variable.
ok &= solver->AddBinaryClause(a.Negated(), old_a.Negated());
ok &= solver->AddBinaryClause(b.Negated(), old_a.Negated());
// Optional. Also add the implication a => not(b).
ok &= solver->AddBinaryClause(a.Negated(), b.Negated());
// This is the difference with the Fu & Malik algorithm.
// If the soft clause protected by old_a has a cost greater than
// min_cost then:
// - its cost is disminished by min_cost.
// - an identical clause with cost min_cost is artificially added to
// the problem.
CHECK_GE(costs[index], min_cost);
if (costs[index] == min_cost) {
// The new assumption variable replaces the old one.
assumptions[index] = a.Negated();
// Symmetry breaking clauses.
for (Literal l : symmetry.ProcessLiteral(index, b)) {
ok &= solver->AddBinaryClause(l.Negated(), b.Negated());
}
} else {
// Since the cost of the given index changes, we need to start a new
// "equivalence" class for the symmetry breaking algo and clear the
// old one.
symmetry.AddInfo(assumptions.size(), b);
symmetry.ClearInfo(index);
// Reduce the cost of the old assumption.
costs[index] -= min_cost;
// We add the new assumption with a cost of min_cost.
//
// Note(user): I think it is nice that these are added after old_a
// because assuming old_a will implies all the derived assumptions to
// true, and thus they will never appear in a core until old_a is not
// an assumption anymore.
assumptions.push_back(a.Negated());
costs.push_back(min_cost);
reference.push_back(reference[index]);
}
// For the "<= 1" constraint on the blocking literals.
// Note(user): we don't add the ">= 1" side because it is not needed for
// the correctness and it doesn't seems to help.
at_most_one_constraint.push_back(LiteralWithCoeff(b, 1.0));
// Because we have a core, we know that at least one of the initial
// problem variables must be true. This seems to help a bit.
//
// TODO(user): Experiment more.
at_least_one_constraint.push_back(reference[index].Negated());
}
// Add the "<= 1" side of the "== 1" constraint.
ok &= solver->AddLinearConstraint(false, Coefficient(0), true,
Coefficient(1.0),
&at_most_one_constraint);
// Optional. Add the ">= 1" constraint on the initial problem variables.
ok &= solver->AddProblemClause(at_least_one_constraint);
if (!ok) {
LOG(INFO) << "Unsat while adding a clause.";
return SatSolver::INFEASIBLE;
}
}
}
}
SatSolver::Status SolveWithRandomParameters(LogBehavior log,
const LinearBooleanProblem& problem,
int num_times, SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
const SatParameters initial_parameters = solver->parameters();
MTRandom random("A random seed.");
SatParameters parameters = initial_parameters;
TimeLimit time_limit(parameters.max_time_in_seconds());
// We start with a low conflict limit and increase it until we are able to
// solve the problem at least once. After this, the limit stays the same.
int max_number_of_conflicts = 5;
parameters.set_log_search_progress(false);
Coefficient min_seen(std::numeric_limits<int64_t>::max());
Coefficient max_seen(std::numeric_limits<int64_t>::min());
Coefficient best(min_seen);
for (int i = 0; i < num_times; ++i) {
solver->Backtrack(0);
RandomizeDecisionHeuristic(&random, ¶meters);
parameters.set_max_number_of_conflicts(max_number_of_conflicts);
parameters.set_max_time_in_seconds(time_limit.GetTimeLeft());
parameters.set_random_seed(i);
solver->SetParameters(parameters);
solver->ResetDecisionHeuristic();
const bool use_obj = absl::Bernoulli(random, 1.0 / 4);
if (use_obj) UseObjectiveForSatAssignmentPreference(problem, solver);
const SatSolver::Status result = solver->Solve();
if (result == SatSolver::INFEASIBLE) {
// If the problem is INFEASIBLE after we over-constrained the objective,
// then we found an optimal solution, otherwise, even the decision problem
// is INFEASIBLE.
if (best == kCoefficientMax) return SatSolver::INFEASIBLE;
return SatSolver::FEASIBLE;
}
if (result == SatSolver::LIMIT_REACHED) {
// We augment the number of conflict until we have one feasible solution.
if (best == kCoefficientMax) ++max_number_of_conflicts;
if (time_limit.LimitReached()) return SatSolver::LIMIT_REACHED;
continue;
}
CHECK_EQ(result, SatSolver::FEASIBLE);
std::vector<bool> candidate;
ExtractAssignment(problem, *solver, &candidate);
CHECK(IsAssignmentValid(problem, candidate));
const Coefficient objective = ComputeObjectiveValue(problem, candidate);
if (objective < best) {
*solution = candidate;
best = objective;
logger.Log(CnfObjectiveLine(problem, objective));
// Overconstrain the objective.
solver->Backtrack(0);
if (!AddObjectiveConstraint(problem, false, Coefficient(0), true,
objective - 1, solver)) {
return SatSolver::FEASIBLE;
}
}
min_seen = std::min(min_seen, objective);
max_seen = std::max(max_seen, objective);
logger.Log(absl::StrCat(
"c ", objective.value(), " [", min_seen.value(), ", ", max_seen.value(),
"] objective_preference: ", use_obj ? "true" : "false", " ",
ProtobufShortDebugString(parameters)));
}
// Retore the initial parameter (with an updated time limit).
parameters = initial_parameters;
parameters.set_max_time_in_seconds(time_limit.GetTimeLeft());
solver->SetParameters(parameters);
return SatSolver::LIMIT_REACHED;
}
SatSolver::Status SolveWithLinearScan(LogBehavior log,
const LinearBooleanProblem& problem,
SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
// This has a big positive impact on most problems.
UseObjectiveForSatAssignmentPreference(problem, solver);
Coefficient objective = kCoefficientMax;
if (!solution->empty()) {
CHECK(IsAssignmentValid(problem, *solution));
objective = ComputeObjectiveValue(problem, *solution);
}
while (true) {
if (objective != kCoefficientMax) {
// Over constrain the objective.
solver->Backtrack(0);
if (!AddObjectiveConstraint(problem, false, Coefficient(0), true,
objective - 1, solver)) {
return SatSolver::FEASIBLE;
}
}
// Solve the problem.
const SatSolver::Status result = solver->Solve();
CHECK_NE(result, SatSolver::ASSUMPTIONS_UNSAT);
if (result == SatSolver::INFEASIBLE) {
if (objective == kCoefficientMax) return SatSolver::INFEASIBLE;
return SatSolver::FEASIBLE;
}
if (result == SatSolver::LIMIT_REACHED) {
return SatSolver::LIMIT_REACHED;
}
// Extract the new best solution.
CHECK_EQ(result, SatSolver::FEASIBLE);
ExtractAssignment(problem, *solver, solution);
CHECK(IsAssignmentValid(problem, *solution));
const Coefficient old_objective = objective;
objective = ComputeObjectiveValue(problem, *solution);
CHECK_LT(objective, old_objective);
logger.Log(CnfObjectiveLine(problem, objective));
}
}
SatSolver::Status SolveWithCardinalityEncoding(
LogBehavior log, const LinearBooleanProblem& problem, SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
std::deque<EncodingNode> repository;
// Create one initial node per variables with cost.
Coefficient offset(0);
std::vector<EncodingNode*> nodes =
CreateInitialEncodingNodes(problem.objective(), &offset, &repository);
// This algorithm only work with weights of the same magnitude.
CHECK(!nodes.empty());
const Coefficient reference = nodes.front()->weight();
for (const EncodingNode* n : nodes) CHECK_EQ(n->weight(), reference);
// Initialize the current objective.
Coefficient objective = kCoefficientMax;
Coefficient upper_bound = kCoefficientMax;
if (!solution->empty()) {
CHECK(IsAssignmentValid(problem, *solution));
objective = ComputeObjectiveValue(problem, *solution);
upper_bound = objective + offset;
}
// Print the number of variables with a non-zero cost.
logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
nodes.size(), problem.num_variables(),
problem.constraints_size()));
// Create the sorter network.
solver->Backtrack(0);
EncodingNode* root =
MergeAllNodesWithDeque(upper_bound, nodes, solver, &repository);
logger.Log(absl::StrFormat("c encoding depth:%d", root->depth()));
while (true) {
if (objective != kCoefficientMax) {
// Over constrain the objective by fixing the variable index - 1 of the
// root node to 0.
const int index = offset.value() + objective.value();
if (index == 0) return SatSolver::FEASIBLE;
solver->Backtrack(0);
if (!solver->AddUnitClause(root->literal(index - 1).Negated())) {
return SatSolver::FEASIBLE;
}
}
// Solve the problem.
const SatSolver::Status result = solver->Solve();
CHECK_NE(result, SatSolver::ASSUMPTIONS_UNSAT);
if (result == SatSolver::INFEASIBLE) {
if (objective == kCoefficientMax) return SatSolver::INFEASIBLE;
return SatSolver::FEASIBLE;
}
if (result == SatSolver::LIMIT_REACHED) return SatSolver::LIMIT_REACHED;
// Extract the new best solution.
CHECK_EQ(result, SatSolver::FEASIBLE);
ExtractAssignment(problem, *solver, solution);
CHECK(IsAssignmentValid(problem, *solution));
const Coefficient old_objective = objective;
objective = ComputeObjectiveValue(problem, *solution);
CHECK_LT(objective, old_objective);
logger.Log(CnfObjectiveLine(problem, objective));
}
}
SatSolver::Status SolveWithCardinalityEncodingAndCore(
LogBehavior log, const LinearBooleanProblem& problem, SatSolver* solver,
std::vector<bool>* solution) {
Logger logger(log);
SatParameters parameters = solver->parameters();
// Create one initial nodes per variables with cost.
Coefficient offset(0);
std::deque<EncodingNode> repository;
std::vector<EncodingNode*> nodes =
CreateInitialEncodingNodes(problem.objective(), &offset, &repository);
// Initialize the bounds.
// This is in term of number of variables not at their minimal value.
Coefficient lower_bound(0);
Coefficient upper_bound(std::numeric_limits<int64_t>::max());
if (!solution->empty()) {
CHECK(IsAssignmentValid(problem, *solution));
upper_bound = ComputeObjectiveValue(problem, *solution) + offset;
}
// Print the number of variables with a non-zero cost.
logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
nodes.size(), problem.num_variables(),
problem.constraints_size()));
// This is used by the "stratified" approach.
Coefficient stratified_lower_bound(0);
if (parameters.max_sat_stratification() ==
SatParameters::STRATIFICATION_DESCENT) {
// In this case, we initialize it to the maximum assumption weights.
for (EncodingNode* n : nodes) {
stratified_lower_bound = std::max(stratified_lower_bound, n->weight());
}
}
// Start the algorithm.
int max_depth = 0;
std::string previous_core_info = "";
for (int iter = 0;; ++iter) {
const std::vector<Literal> assumptions = ReduceNodesAndExtractAssumptions(
upper_bound, stratified_lower_bound, &lower_bound, &nodes, solver);
if (assumptions.empty()) return SatSolver::FEASIBLE;