forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_solver.cc
3034 lines (2727 loc) · 121 KB
/
cp_model_solver.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 "ortools/sat/cp_model_solver.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "ortools/base/cleanup.h"
#include "ortools/sat/feasibility_pump.h"
#if !defined(__PORTABLE_PLATFORM__)
#include "absl/synchronization/notification.h"
#include "google/protobuf/text_format.h"
#include "ortools/base/file.h"
#include "ortools/util/sigint.h"
#endif // __PORTABLE_PLATFORM__
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/synchronization/mutex.h"
#include "glog/vlog_is_on.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/int_type.h"
#include "ortools/base/int_type_indexed_vector.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/threadpool.h"
#include "ortools/base/timer.h"
#include "ortools/graph/connectivity.h"
#include "ortools/port/proto_utils.h"
#include "ortools/sat/circuit.h"
#include "ortools/sat/clause.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_checker.h"
#include "ortools/sat/cp_model_lns.h"
#include "ortools/sat/cp_model_loader.h"
#include "ortools/sat/cp_model_postsolve.h"
#include "ortools/sat/cp_model_presolve.h"
#include "ortools/sat/cp_model_search.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/cuts.h"
#include "ortools/sat/drat_checker.h"
#include "ortools/sat/drat_proof_handler.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_expr.h"
#include "ortools/sat/integer_search.h"
#include "ortools/sat/linear_programming_constraint.h"
#include "ortools/sat/linear_relaxation.h"
#include "ortools/sat/optimization.h"
#include "ortools/sat/precedences.h"
#include "ortools/sat/probing.h"
#include "ortools/sat/rins.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_inprocessing.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/simplification.h"
#include "ortools/sat/subsolver.h"
#include "ortools/sat/synchronization.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/time_limit.h"
DEFINE_string(cp_model_dump_prefix, "/tmp/",
"Prefix filename for all dumped files");
// TODO(user): dump to recordio ?
DEFINE_bool(
cp_model_dump_models, false,
"DEBUG ONLY. When set to true, SolveCpModel() will dump its model "
"protos (original model, presolved model, mapping model) in text "
"format to "
"'FLAGS_cp_model_dump_prefix'{model|presolved_model|mapping_model}.pbtxt.");
DEFINE_string(cp_model_params, "",
"This is interpreted as a text SatParameters proto. The "
"specified fields will override the normal ones for all solves.");
DEFINE_bool(cp_model_dump_lns, false,
"DEBUG ONLY. When set to true, solve will dump all "
"lns models proto in text format to "
"'FLAGS_cp_model_dump_prefix'lns_xxx.pbtxt.");
DEFINE_string(
drat_output, "",
"If non-empty, a proof in DRAT format will be written to this file. "
"This will only be used for pure-SAT problems.");
DEFINE_bool(drat_check, false,
"If true, a proof in DRAT format will be stored in memory and "
"checked if the problem is UNSAT. This will only be used for "
"pure-SAT problems.");
DEFINE_double(max_drat_time_in_seconds, std::numeric_limits<double>::infinity(),
"Maximum time in seconds to check the DRAT proof. This will only "
"be used is the drat_check flag is enabled.");
DEFINE_bool(cp_model_check_intermediate_solutions, false,
"When true, all intermediate solutions found by the solver will be "
"checked. This can be expensive, therefore it is off by default.");
namespace operations_research {
namespace sat {
namespace {
// Makes the string fit in one line by cutting it in the middle if necessary.
std::string Summarize(const std::string& input) {
if (input.size() < 105) return input;
const int half = 50;
return absl::StrCat(input.substr(0, half), " ... ",
input.substr(input.size() - half, half));
}
} // namespace.
// =============================================================================
// Public API.
// =============================================================================
std::string CpModelStats(const CpModelProto& model_proto) {
std::map<std::string, int> num_constraints_by_name;
std::map<std::string, int> num_reif_constraints_by_name;
std::map<std::string, int> name_to_num_literals;
for (const ConstraintProto& ct : model_proto.constraints()) {
std::string name = ConstraintCaseName(ct.constraint_case());
// We split the linear constraints into 3 buckets has it gives more insight
// on the type of problem we are facing.
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kLinear) {
if (ct.linear().vars_size() == 1) name += "1";
if (ct.linear().vars_size() == 2) name += "2";
if (ct.linear().vars_size() == 3) name += "3";
if (ct.linear().vars_size() > 3) name += "N";
}
num_constraints_by_name[name]++;
if (!ct.enforcement_literal().empty()) {
num_reif_constraints_by_name[name]++;
}
// For pure Boolean constraints, we also display the total number of literal
// involved as this gives a good idea of the problem size.
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kBoolOr) {
name_to_num_literals[name] += ct.bool_or().literals().size();
} else if (ct.constraint_case() ==
ConstraintProto::ConstraintCase::kBoolAnd) {
name_to_num_literals[name] += ct.bool_and().literals().size();
} else if (ct.constraint_case() ==
ConstraintProto::ConstraintCase::kAtMostOne) {
name_to_num_literals[name] += ct.at_most_one().literals().size();
}
}
int num_constants = 0;
std::set<int64> constant_values;
std::map<Domain, int> num_vars_per_domains;
for (const IntegerVariableProto& var : model_proto.variables()) {
if (var.domain_size() == 2 && var.domain(0) == var.domain(1)) {
++num_constants;
constant_values.insert(var.domain(0));
} else {
num_vars_per_domains[ReadDomainFromProto(var)]++;
}
}
std::string result;
if (model_proto.has_objective()) {
absl::StrAppend(&result, "Optimization model '", model_proto.name(),
"':\n");
} else {
absl::StrAppend(&result, "Satisfaction model '", model_proto.name(),
"':\n");
}
for (const DecisionStrategyProto& strategy : model_proto.search_strategy()) {
absl::StrAppend(
&result, "Search strategy: on ", strategy.variables_size(),
" variables, ",
ProtoEnumToString<DecisionStrategyProto::VariableSelectionStrategy>(
strategy.variable_selection_strategy()),
", ",
ProtoEnumToString<DecisionStrategyProto::DomainReductionStrategy>(
strategy.domain_reduction_strategy()),
"\n");
}
const std::string objective_string =
model_proto.has_objective()
? absl::StrCat(" (", model_proto.objective().vars_size(),
" in objective)")
: "";
absl::StrAppend(&result, "#Variables: ", model_proto.variables_size(),
objective_string, "\n");
if (num_vars_per_domains.size() < 100) {
for (const auto& entry : num_vars_per_domains) {
const std::string temp = absl::StrCat(" - ", entry.second, " in ",
entry.first.ToString(), "\n");
absl::StrAppend(&result, Summarize(temp));
}
} else {
int64 max_complexity = 0;
int64 min = kint64max;
int64 max = kint64min;
for (const auto& entry : num_vars_per_domains) {
min = std::min(min, entry.first.Min());
max = std::max(max, entry.first.Max());
max_complexity = std::max(max_complexity,
static_cast<int64>(entry.first.NumIntervals()));
}
absl::StrAppend(&result, " - ", num_vars_per_domains.size(),
" different domains in [", min, ",", max,
"] with a largest complexity of ", max_complexity, ".\n");
}
if (num_constants > 0) {
const std::string temp =
absl::StrCat(" - ", num_constants, " constants in {",
absl::StrJoin(constant_values, ","), "} \n");
absl::StrAppend(&result, Summarize(temp));
}
std::vector<std::string> constraints;
constraints.reserve(num_constraints_by_name.size());
for (const auto& entry : num_constraints_by_name) {
const std::string& name = entry.first;
constraints.push_back(absl::StrCat("#", name, ": ", entry.second));
if (gtl::ContainsKey(num_reif_constraints_by_name, name)) {
absl::StrAppend(&constraints.back(),
" (#enforced: ", num_reif_constraints_by_name[name], ")");
}
if (gtl::ContainsKey(name_to_num_literals, name)) {
absl::StrAppend(&constraints.back(),
" (#literals: ", name_to_num_literals[name], ")");
}
}
std::sort(constraints.begin(), constraints.end());
absl::StrAppend(&result, absl::StrJoin(constraints, "\n"));
return result;
}
std::string CpSolverResponseStats(const CpSolverResponse& response,
bool has_objective) {
std::string result;
absl::StrAppend(&result, "CpSolverResponse:");
absl::StrAppend(&result, "\nstatus: ",
ProtoEnumToString<CpSolverStatus>(response.status()));
if (has_objective && response.status() != CpSolverStatus::INFEASIBLE) {
absl::StrAppendFormat(&result, "\nobjective: %.9g",
response.objective_value());
absl::StrAppendFormat(&result, "\nbest_bound: %.9g",
response.best_objective_bound());
} else {
absl::StrAppend(&result, "\nobjective: NA");
absl::StrAppend(&result, "\nbest_bound: NA");
}
absl::StrAppend(&result, "\nbooleans: ", response.num_booleans());
absl::StrAppend(&result, "\nconflicts: ", response.num_conflicts());
absl::StrAppend(&result, "\nbranches: ", response.num_branches());
// TODO(user): This is probably better named "binary_propagation", but we just
// output "propagations" to be consistent with sat/analyze.sh.
absl::StrAppend(&result,
"\npropagations: ", response.num_binary_propagations());
absl::StrAppend(
&result, "\ninteger_propagations: ", response.num_integer_propagations());
absl::StrAppend(&result, "\nwalltime: ", response.wall_time());
absl::StrAppend(&result, "\nusertime: ", response.user_time());
absl::StrAppend(&result,
"\ndeterministic_time: ", response.deterministic_time());
absl::StrAppend(&result, "\nprimal_integral: ", response.primal_integral());
absl::StrAppend(&result, "\n");
return result;
}
namespace {
void FillSolutionInResponse(const CpModelProto& model_proto, const Model& model,
CpSolverResponse* response) {
response->clear_solution();
response->clear_solution_lower_bounds();
response->clear_solution_upper_bounds();
auto* mapping = model.Get<CpModelMapping>();
auto* trail = model.Get<Trail>();
auto* integer_trail = model.Get<IntegerTrail>();
std::vector<int64> solution;
for (int i = 0; i < model_proto.variables_size(); ++i) {
if (mapping->IsInteger(i)) {
const IntegerVariable var = mapping->Integer(i);
if (integer_trail->IsCurrentlyIgnored(var)) {
// This variable is "ignored" so it may not be fixed, simply use
// the current lower bound. Any value in its domain should lead to
// a feasible solution.
solution.push_back(model.Get(LowerBound(var)));
} else {
if (model.Get(LowerBound(var)) != model.Get(UpperBound(var))) {
solution.clear();
break;
}
solution.push_back(model.Get(Value(var)));
}
} else {
DCHECK(mapping->IsBoolean(i));
const Literal literal = mapping->Literal(i);
if (trail->Assignment().LiteralIsAssigned(literal)) {
solution.push_back(model.Get(Value(literal)));
} else {
solution.clear();
break;
}
}
}
if (!solution.empty()) {
if (DEBUG_MODE || FLAGS_cp_model_check_intermediate_solutions) {
// TODO(user): Checks against initial model.
CHECK(SolutionIsFeasible(model_proto, solution));
}
for (const int64 value : solution) response->add_solution(value);
} else {
// Not all variables are fixed.
// We fill instead the lb/ub of each variables.
const auto& assignment = trail->Assignment();
for (int i = 0; i < model_proto.variables_size(); ++i) {
if (mapping->IsBoolean(i)) {
if (assignment.VariableIsAssigned(mapping->Literal(i).Variable())) {
const int value = model.Get(Value(mapping->Literal(i)));
response->add_solution_lower_bounds(value);
response->add_solution_upper_bounds(value);
} else {
response->add_solution_lower_bounds(0);
response->add_solution_upper_bounds(1);
}
} else {
response->add_solution_lower_bounds(
model.Get(LowerBound(mapping->Integer(i))));
response->add_solution_upper_bounds(
model.Get(UpperBound(mapping->Integer(i))));
}
}
}
}
namespace {
IntegerVariable GetOrCreateVariableWithTightBound(
const std::vector<std::pair<IntegerVariable, int64>>& terms, Model* model) {
if (terms.empty()) return model->Add(ConstantIntegerVariable(0));
if (terms.size() == 1 && terms.front().second == 1) {
return terms.front().first;
}
if (terms.size() == 1 && terms.front().second == -1) {
return NegationOf(terms.front().first);
}
int64 sum_min = 0;
int64 sum_max = 0;
for (const std::pair<IntegerVariable, int64> var_coeff : terms) {
const int64 min_domain = model->Get(LowerBound(var_coeff.first));
const int64 max_domain = model->Get(UpperBound(var_coeff.first));
const int64 coeff = var_coeff.second;
const int64 prod1 = min_domain * coeff;
const int64 prod2 = max_domain * coeff;
sum_min += std::min(prod1, prod2);
sum_max += std::max(prod1, prod2);
}
return model->Add(NewIntegerVariable(sum_min, sum_max));
}
IntegerVariable GetOrCreateVariableGreaterOrEqualToSumOf(
const std::vector<std::pair<IntegerVariable, int64>>& terms, Model* model) {
if (terms.empty()) return model->Add(ConstantIntegerVariable(0));
if (terms.size() == 1 && terms.front().second == 1) {
return terms.front().first;
}
if (terms.size() == 1 && terms.front().second == -1) {
return NegationOf(terms.front().first);
}
// Create a new variable and link it with the linear terms.
const IntegerVariable new_var =
GetOrCreateVariableWithTightBound(terms, model);
std::vector<IntegerVariable> vars;
std::vector<int64> coeffs;
for (const auto& term : terms) {
vars.push_back(term.first);
coeffs.push_back(term.second);
}
vars.push_back(new_var);
coeffs.push_back(-1);
model->Add(WeightedSumLowerOrEqual(vars, coeffs, 0));
return new_var;
}
void TryToAddCutGenerators(const CpModelProto& model_proto,
const ConstraintProto& ct, Model* m,
LinearRelaxation* relaxation) {
const int linearization_level =
m->GetOrCreate<SatParameters>()->linearization_level();
auto* mapping = m->GetOrCreate<CpModelMapping>();
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kCircuit &&
linearization_level > 1) {
std::vector<int> tails(ct.circuit().tails().begin(),
ct.circuit().tails().end());
std::vector<int> heads(ct.circuit().heads().begin(),
ct.circuit().heads().end());
std::vector<Literal> literals = mapping->Literals(ct.circuit().literals());
const int num_nodes = ReindexArcs(&tails, &heads, &literals);
relaxation->cut_generators.push_back(
CreateStronglyConnectedGraphCutGenerator(num_nodes, tails, heads,
literals, m));
}
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kRoutes &&
linearization_level > 1) {
std::vector<int> tails(ct.routes().tails().begin(),
ct.routes().tails().end());
std::vector<int> heads(ct.routes().heads().begin(),
ct.routes().heads().end());
std::vector<Literal> literals = mapping->Literals(ct.routes().literals());
int num_nodes = 0;
for (int i = 0; i < ct.routes().tails_size(); ++i) {
num_nodes = std::max(num_nodes, 1 + ct.routes().tails(i));
num_nodes = std::max(num_nodes, 1 + ct.routes().heads(i));
}
if (ct.routes().demands().empty() || ct.routes().capacity() == 0) {
relaxation->cut_generators.push_back(
CreateStronglyConnectedGraphCutGenerator(num_nodes, tails, heads,
literals, m));
} else {
const std::vector<int64> demands(ct.routes().demands().begin(),
ct.routes().demands().end());
relaxation->cut_generators.push_back(
CreateCVRPCutGenerator(num_nodes, tails, heads, literals, demands,
ct.routes().capacity(), m));
}
}
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kIntProd) {
if (HasEnforcementLiteral(ct)) return;
if (ct.int_prod().vars_size() != 2) return;
// Constraint is z == x * y.
IntegerVariable z = mapping->Integer(ct.int_prod().target());
IntegerVariable x = mapping->Integer(ct.int_prod().vars(0));
IntegerVariable y = mapping->Integer(ct.int_prod().vars(1));
IntegerTrail* const integer_trail = m->GetOrCreate<IntegerTrail>();
IntegerValue x_lb = integer_trail->LowerBound(x);
IntegerValue x_ub = integer_trail->UpperBound(x);
IntegerValue y_lb = integer_trail->LowerBound(y);
IntegerValue y_ub = integer_trail->UpperBound(y);
if (x == y) {
// We currently only support variables with non-negative domains.
if (x_lb < 0 && x_ub > 0) return;
// Change the sigh of x if its domain is non-positive.
if (x_ub <= 0) {
x = NegationOf(x);
}
relaxation->cut_generators.push_back(CreateSquareCutGenerator(z, x, m));
} else {
// We currently only support variables with non-negative domains.
if (x_lb < 0 && x_ub > 0) return;
if (y_lb < 0 && y_ub > 0) return;
// Change signs to return to the case where all variables are a domain
// with non negative values only.
if (x_ub <= 0) {
x = NegationOf(x);
z = NegationOf(z);
}
if (y_ub <= 0) {
y = NegationOf(y);
z = NegationOf(z);
}
relaxation->cut_generators.push_back(
CreatePositiveMultiplicationCutGenerator(z, x, y, m));
}
}
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kAllDiff) {
if (linearization_level < 2) return;
if (HasEnforcementLiteral(ct)) return;
const int num_vars = ct.all_diff().vars_size();
if (num_vars <= m->GetOrCreate<SatParameters>()->max_all_diff_cut_size()) {
std::vector<IntegerVariable> vars =
mapping->Integers(ct.all_diff().vars());
relaxation->cut_generators.push_back(
CreateAllDifferentCutGenerator(vars, m));
}
}
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kLinMax) {
if (!m->GetOrCreate<SatParameters>()->add_lin_max_cuts()) return;
if (HasEnforcementLiteral(ct)) return;
// TODO(user): Support linearization of general target expression.
if (ct.lin_max().target().vars_size() != 1) return;
if (ct.lin_max().target().coeffs(0) != 1) return;
const IntegerVariable target =
mapping->Integer(ct.lin_max().target().vars(0));
std::vector<LinearExpression> exprs;
exprs.reserve(ct.lin_max().exprs_size());
for (int i = 0; i < ct.lin_max().exprs_size(); ++i) {
// Note: Cut generator requires all expressions to contain only positive
// vars.
exprs.push_back(
PositiveVarExpr(GetExprFromProto(ct.lin_max().exprs(i), *mapping)));
}
// Add initial big-M linear relaxation.
// z_vars[i] == 1 <=> target = exprs[i].
const std::vector<IntegerVariable> z_vars =
AppendLinMaxRelaxation(target, exprs, m, relaxation);
if (linearization_level >= 2) {
relaxation->cut_generators.push_back(
CreateLinMaxCutGenerator(target, exprs, z_vars, m));
}
}
}
} // namespace
LinearRelaxation ComputeLinearRelaxation(const CpModelProto& model_proto,
int linearization_level, Model* m) {
LinearRelaxation relaxation;
// Linearize the constraints.
absl::flat_hash_set<int> used_integer_variable;
auto* mapping = m->GetOrCreate<CpModelMapping>();
auto* encoder = m->GetOrCreate<IntegerEncoder>();
auto* trail = m->GetOrCreate<Trail>();
for (const auto& ct : model_proto.constraints()) {
// Make sure the literals from a circuit constraint always have a view.
if (ct.constraint_case() == ConstraintProto::ConstraintCase::kCircuit) {
for (const int ref : ct.circuit().literals()) {
const Literal l = mapping->Literal(ref);
if (encoder->GetLiteralView(l) == kNoIntegerVariable &&
encoder->GetLiteralView(l.Negated()) == kNoIntegerVariable) {
m->Add(NewIntegerVariableFromLiteral(l));
}
}
}
// For now, we skip any constraint with literals that do not have an integer
// view. Ideally it should be up to the constraint to decide if creating a
// view is worth it.
//
// TODO(user): It should be possible to speed this up if needed.
const IndexReferences refs = GetReferencesUsedByConstraint(ct);
bool ok = true;
for (const int literal_ref : refs.literals) {
const Literal literal = mapping->Literal(literal_ref);
if (trail->Assignment().LiteralIsAssigned(literal)) {
// Create a view to the constant 0 or 1.
m->Add(NewIntegerVariableFromLiteral(literal));
} else if (encoder->GetLiteralView(literal) == kNoIntegerVariable &&
encoder->GetLiteralView(literal.Negated()) ==
kNoIntegerVariable) {
ok = false;
break;
}
}
if (!ok) continue;
TryToLinearizeConstraint(model_proto, ct, m, linearization_level,
&relaxation);
TryToAddCutGenerators(model_proto, ct, m, &relaxation);
}
// Linearize the encoding of variable that are fully encoded in the proto.
int num_full_encoding_relaxations = 0;
int num_partial_encoding_relaxations = 0;
for (int i = 0; i < model_proto.variables_size(); ++i) {
if (mapping->IsBoolean(i)) continue;
const IntegerVariable var = mapping->Integer(i);
if (m->Get(IsFixed(var))) continue;
// TODO(user): This different encoding for the partial variable might be
// better (less LP constraints), but we do need more investigation to
// decide.
if (/* DISABLES CODE */ (false)) {
AppendPartialEncodingRelaxation(var, *m, &relaxation);
continue;
}
if (encoder->VariableIsFullyEncoded(var)) {
if (AppendFullEncodingRelaxation(var, *m, &relaxation)) {
++num_full_encoding_relaxations;
continue;
}
}
// Even if the variable is fully encoded, sometimes not all its associated
// literal have a view (if they are not part of the original model for
// instance).
//
// TODO(user): Should we add them to the LP anyway? this isn't clear as
// we can sometimes create a lot of Booleans like this.
const int old = relaxation.linear_constraints.size();
AppendPartialGreaterThanEncodingRelaxation(var, *m, &relaxation);
if (relaxation.linear_constraints.size() > old) {
++num_partial_encoding_relaxations;
}
}
// Linearize the at most one constraints. Note that we transform them
// into maximum "at most one" first and we removes redundant ones.
m->GetOrCreate<BinaryImplicationGraph>()->TransformIntoMaxCliques(
&relaxation.at_most_ones);
for (const std::vector<Literal>& at_most_one : relaxation.at_most_ones) {
if (at_most_one.empty()) continue;
LinearConstraintBuilder lc(m, kMinIntegerValue, IntegerValue(1));
for (const Literal literal : at_most_one) {
// Note that it is okay to simply ignore the literal if it has no
// integer view.
const bool unused ABSL_ATTRIBUTE_UNUSED =
lc.AddLiteralTerm(literal, IntegerValue(1));
}
relaxation.linear_constraints.push_back(lc.Build());
}
// Remove size one LP constraints, they are not useful.
{
int new_size = 0;
for (int i = 0; i < relaxation.linear_constraints.size(); ++i) {
if (relaxation.linear_constraints[i].vars.size() <= 1) continue;
std::swap(relaxation.linear_constraints[new_size++],
relaxation.linear_constraints[i]);
}
relaxation.linear_constraints.resize(new_size);
}
VLOG(3) << "num_full_encoding_relaxations: " << num_full_encoding_relaxations;
VLOG(3) << "num_partial_encoding_relaxations: "
<< num_partial_encoding_relaxations;
VLOG(3) << relaxation.linear_constraints.size()
<< " constraints in the LP relaxation.";
VLOG(3) << relaxation.cut_generators.size() << " cuts generators.";
return relaxation;
}
// Adds one LinearProgrammingConstraint per connected component of the model.
IntegerVariable AddLPConstraints(const CpModelProto& model_proto,
int linearization_level, Model* m) {
const LinearRelaxation relaxation =
ComputeLinearRelaxation(model_proto, linearization_level, m);
// The bipartite graph of LP constraints might be disconnected:
// make a partition of the variables into connected components.
// Constraint nodes are indexed by [0..num_lp_constraints),
// variable nodes by [num_lp_constraints..num_lp_constraints+num_variables).
//
// TODO(user): look into biconnected components.
const int num_lp_constraints = relaxation.linear_constraints.size();
const int num_lp_cut_generators = relaxation.cut_generators.size();
const int num_integer_variables =
m->GetOrCreate<IntegerTrail>()->NumIntegerVariables().value();
ConnectedComponents<int, int> components;
components.Init(num_lp_constraints + num_lp_cut_generators +
num_integer_variables);
auto get_constraint_index = [](int ct_index) { return ct_index; };
auto get_cut_generator_index = [num_lp_constraints](int cut_index) {
return num_lp_constraints + cut_index;
};
auto get_var_index = [num_lp_constraints,
num_lp_cut_generators](IntegerVariable var) {
return num_lp_constraints + num_lp_cut_generators + var.value();
};
for (int i = 0; i < num_lp_constraints; i++) {
for (const IntegerVariable var : relaxation.linear_constraints[i].vars) {
components.AddArc(get_constraint_index(i), get_var_index(var));
}
}
for (int i = 0; i < num_lp_cut_generators; ++i) {
for (const IntegerVariable var : relaxation.cut_generators[i].vars) {
components.AddArc(get_cut_generator_index(i), get_var_index(var));
}
}
std::map<int, int> components_to_size;
for (int i = 0; i < num_lp_constraints; i++) {
const int id = components.GetClassRepresentative(get_constraint_index(i));
components_to_size[id] += 1;
}
for (int i = 0; i < num_lp_cut_generators; i++) {
const int id =
components.GetClassRepresentative(get_cut_generator_index(i));
components_to_size[id] += 1;
}
// Make sure any constraint that touch the objective is not discarded even
// if it is the only one in its component. This is important to propagate
// as much as possible the objective bound by using any bounds the LP give
// us on one of its components. This is critical on the zephyrus problems for
// instance.
auto* mapping = m->GetOrCreate<CpModelMapping>();
for (int i = 0; i < model_proto.objective().coeffs_size(); ++i) {
const IntegerVariable var =
mapping->Integer(model_proto.objective().vars(i));
const int id = components.GetClassRepresentative(get_var_index(var));
components_to_size[id] += 1;
}
// Dispatch every constraint to its LinearProgrammingConstraint.
std::map<int, LinearProgrammingConstraint*> representative_to_lp_constraint;
std::vector<LinearProgrammingConstraint*> lp_constraints;
std::map<int, std::vector<LinearConstraint>> id_to_constraints;
for (int i = 0; i < num_lp_constraints; i++) {
const int id = components.GetClassRepresentative(get_constraint_index(i));
if (components_to_size[id] <= 1) continue;
id_to_constraints[id].push_back(relaxation.linear_constraints[i]);
if (!gtl::ContainsKey(representative_to_lp_constraint, id)) {
auto* lp = m->Create<LinearProgrammingConstraint>();
representative_to_lp_constraint[id] = lp;
lp_constraints.push_back(lp);
}
// Load the constraint.
gtl::FindOrDie(representative_to_lp_constraint, id)
->AddLinearConstraint(relaxation.linear_constraints[i]);
}
// Dispatch every cut generator to its LinearProgrammingConstraint.
for (int i = 0; i < num_lp_cut_generators; i++) {
const int id =
components.GetClassRepresentative(get_cut_generator_index(i));
if (!gtl::ContainsKey(representative_to_lp_constraint, id)) {
auto* lp = m->Create<LinearProgrammingConstraint>();
representative_to_lp_constraint[id] = lp;
lp_constraints.push_back(lp);
}
LinearProgrammingConstraint* lp = representative_to_lp_constraint[id];
lp->AddCutGenerator(std::move(relaxation.cut_generators[i]));
}
const SatParameters& params = *(m->GetOrCreate<SatParameters>());
if (params.add_knapsack_cuts()) {
for (const auto& entry : id_to_constraints) {
const int id = entry.first;
LinearProgrammingConstraint* lp =
gtl::FindOrDie(representative_to_lp_constraint, id);
lp->AddCutGenerator(CreateKnapsackCoverCutGenerator(
id_to_constraints[id], lp->integer_variables(), m));
}
}
// Add the objective.
std::map<int, std::vector<std::pair<IntegerVariable, int64>>>
representative_to_cp_terms;
std::vector<std::pair<IntegerVariable, int64>> top_level_cp_terms;
int num_components_containing_objective = 0;
if (model_proto.has_objective()) {
// First pass: set objective coefficients on the lp constraints, and store
// the cp terms in one vector per component.
for (int i = 0; i < model_proto.objective().coeffs_size(); ++i) {
const IntegerVariable var =
mapping->Integer(model_proto.objective().vars(i));
const int64 coeff = model_proto.objective().coeffs(i);
const int id = components.GetClassRepresentative(get_var_index(var));
if (gtl::ContainsKey(representative_to_lp_constraint, id)) {
representative_to_lp_constraint[id]->SetObjectiveCoefficient(
var, IntegerValue(coeff));
representative_to_cp_terms[id].push_back(std::make_pair(var, coeff));
} else {
// Component is too small. We still need to store the objective term.
top_level_cp_terms.push_back(std::make_pair(var, coeff));
}
}
// Second pass: Build the cp sub-objectives per component.
for (const auto& it : representative_to_cp_terms) {
const int id = it.first;
LinearProgrammingConstraint* lp =
gtl::FindOrDie(representative_to_lp_constraint, id);
const std::vector<std::pair<IntegerVariable, int64>>& terms = it.second;
const IntegerVariable sub_obj_var =
GetOrCreateVariableGreaterOrEqualToSumOf(terms, m);
top_level_cp_terms.push_back(std::make_pair(sub_obj_var, 1));
lp->SetMainObjectiveVariable(sub_obj_var);
num_components_containing_objective++;
}
}
const IntegerVariable main_objective_var =
model_proto.has_objective()
? GetOrCreateVariableGreaterOrEqualToSumOf(top_level_cp_terms, m)
: kNoIntegerVariable;
// Register LP constraints. Note that this needs to be done after all the
// constraints have been added.
for (auto* lp_constraint : lp_constraints) {
lp_constraint->RegisterWith(m);
VLOG(3) << "LP constraint: " << lp_constraint->DimensionString() << ".";
}
VLOG(3) << top_level_cp_terms.size()
<< " terms in the main objective linear equation ("
<< num_components_containing_objective << " from LP constraints).";
return main_objective_var;
}
} // namespace
// Used by NewFeasibleSolutionObserver to register observers.
struct SolutionObservers {
explicit SolutionObservers(Model* model) {}
std::vector<std::function<void(const CpSolverResponse& response)>> observers;
};
std::function<void(Model*)> NewFeasibleSolutionObserver(
const std::function<void(const CpSolverResponse& response)>& observer) {
return [=](Model* model) {
model->GetOrCreate<SolutionObservers>()->observers.push_back(observer);
};
}
#if !defined(__PORTABLE_PLATFORM__)
// TODO(user): Support it on android.
std::function<SatParameters(Model*)> NewSatParameters(
const std::string& params) {
sat::SatParameters parameters;
if (!params.empty()) {
CHECK(google::protobuf::TextFormat::ParseFromString(params, ¶meters))
<< params;
}
return NewSatParameters(parameters);
}
#endif // __PORTABLE_PLATFORM__
std::function<SatParameters(Model*)> NewSatParameters(
const sat::SatParameters& parameters) {
return [=](Model* model) {
// Tricky: It is important to initialize the model parameters before any
// of the solver object are created, so that by default they use the given
// parameters.
*model->GetOrCreate<SatParameters>() = parameters;
model->GetOrCreate<SatSolver>()->SetParameters(parameters);
return parameters;
};
}
namespace {
// Registers a callback that will export variables bounds fixed at level 0 of
// the search. This should not be registered to a LNS search.
void RegisterVariableBoundsLevelZeroExport(
const CpModelProto& model_proto, SharedBoundsManager* shared_bounds_manager,
Model* model) {
CHECK(shared_bounds_manager != nullptr);
int saved_trail_index = 0;
const auto broadcast_level_zero_bounds =
[&model_proto, saved_trail_index, model, shared_bounds_manager](
const std::vector<IntegerVariable>& modified_vars) mutable {
CpModelMapping* const mapping = model->GetOrCreate<CpModelMapping>();
std::vector<int> model_variables;
std::vector<int64> new_lower_bounds;
std::vector<int64> new_upper_bounds;
absl::flat_hash_set<int> visited_variables;
// Inspect the modified IntegerVariables.
auto* integer_trail = model->Get<IntegerTrail>();
for (const IntegerVariable& var : modified_vars) {
const IntegerVariable positive_var = PositiveVariable(var);
const int model_var =
mapping->GetProtoVariableFromIntegerVariable(positive_var);
if (model_var == -1 || visited_variables.contains(model_var)) {
// TODO(user): I don't think we should see the same model_var twice
// here so maybe we don't need the visited_variables.contains()
// part.
continue;
}
visited_variables.insert(model_var);
const int64 new_lb =
integer_trail->LevelZeroLowerBound(positive_var).value();
const int64 new_ub =
integer_trail->LevelZeroUpperBound(positive_var).value();
// TODO(user): We could imagine an API based on atomic<int64>
// that could preemptively check if this new bounds are improving.
model_variables.push_back(model_var);
new_lower_bounds.push_back(new_lb);
new_upper_bounds.push_back(new_ub);
}
// Inspect the newly modified Booleans.
auto* trail = model->Get<Trail>();
for (; saved_trail_index < trail->Index(); ++saved_trail_index) {
const Literal fixed_literal = (*trail)[saved_trail_index];
const int model_var = mapping->GetProtoVariableFromBooleanVariable(
fixed_literal.Variable());
if (model_var == -1 || visited_variables.contains(model_var)) {
// If the variable is already visited, it should mean that this
// Boolean also has an IntegerVariable view, and we should already
// have set its bound correctly.
continue;
}
visited_variables.insert(model_var);
model_variables.push_back(model_var);
if (fixed_literal.IsPositive()) {
new_lower_bounds.push_back(1);
new_upper_bounds.push_back(1);
} else {
new_lower_bounds.push_back(0);
new_upper_bounds.push_back(0);
}
}
if (!model_variables.empty()) {
const WorkerInfo* const worker_info =
model->GetOrCreate<WorkerInfo>();
shared_bounds_manager->ReportPotentialNewBounds(
model_proto, worker_info->worker_name, model_variables,
new_lower_bounds, new_upper_bounds);
}
// If we are not in interleave_search we synchronize right away.
if (!model->Get<SatParameters>()->interleave_search()) {
shared_bounds_manager->Synchronize();
}
};
model->GetOrCreate<GenericLiteralWatcher>()
->RegisterLevelZeroModifiedVariablesCallback(broadcast_level_zero_bounds);
}
// Registers a callback to import new variables bounds stored in the
// shared_bounds_manager. These bounds are imported at level 0 of the search
// in the linear scan minimize function.
void RegisterVariableBoundsLevelZeroImport(
const CpModelProto& model_proto, SharedBoundsManager* shared_bounds_manager,
Model* model) {
CHECK(shared_bounds_manager != nullptr);
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
const WorkerInfo* const worker_info = model->GetOrCreate<WorkerInfo>();
CpModelMapping* const mapping = model->GetOrCreate<CpModelMapping>();
const auto& import_level_zero_bounds = [&model_proto, shared_bounds_manager,
model, integer_trail, worker_info,
mapping]() {
std::vector<int> model_variables;
std::vector<int64> new_lower_bounds;
std::vector<int64> new_upper_bounds;
shared_bounds_manager->GetChangedBounds(worker_info->worker_id,
&model_variables, &new_lower_bounds,
&new_upper_bounds);
bool new_bounds_have_been_imported = false;
for (int i = 0; i < model_variables.size(); ++i) {
const int model_var = model_variables[i];
// This can happen if a boolean variables is forced to have an
// integer view in one thread, and not in another thread.
if (!mapping->IsInteger(model_var)) continue;
const IntegerVariable var = mapping->Integer(model_var);
const IntegerValue new_lb(new_lower_bounds[i]);
const IntegerValue new_ub(new_upper_bounds[i]);
const IntegerValue old_lb = integer_trail->LowerBound(var);
const IntegerValue old_ub = integer_trail->UpperBound(var);
const bool changed_lb = new_lb > old_lb;
const bool changed_ub = new_ub < old_ub;
if (!changed_lb && !changed_ub) continue;
new_bounds_have_been_imported = true;
if (VLOG_IS_ON(3)) {
const IntegerVariableProto& var_proto =
model_proto.variables(model_var);
const std::string& var_name =
var_proto.name().empty()