forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_solver_helpers.cc
1823 lines (1638 loc) · 74.1 KB
/
cp_model_solver_helpers.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/cp_model_solver_helpers.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <string>
#include <thread>
#include <tuple>
#include <utility>
#include <vector>
#include "ortools/base/logging.h"
#include "ortools/base/timer.h"
#if !defined(__PORTABLE_PLATFORM__)
#include "ortools/base/helpers.h"
#include "ortools/base/options.h"
#endif // __PORTABLE_PLATFORM__
#include "absl/cleanup/cleanup.h"
#include "absl/container/flat_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/log/check.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "google/protobuf/arena.h"
#include "ortools/base/logging.h"
#include "ortools/base/strong_vector.h"
#include "ortools/graph/connected_components.h"
#include "ortools/port/proto_utils.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_loader.h"
#include "ortools/sat/cp_model_mapping.h"
#include "ortools/sat/cp_model_postsolve.h"
#include "ortools/sat/cp_model_search.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/cuts.h"
#include "ortools/sat/feasibility_pump.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_expr.h"
#include "ortools/sat/integer_search.h"
#include "ortools/sat/intervals.h"
#include "ortools/sat/lb_tree_search.h"
#include "ortools/sat/linear_constraint.h"
#include "ortools/sat/linear_programming_constraint.h"
#include "ortools/sat/linear_relaxation.h"
#include "ortools/sat/max_hs.h"
#include "ortools/sat/model.h"
#include "ortools/sat/optimization.h"
#include "ortools/sat/precedences.h"
#include "ortools/sat/probing.h"
#include "ortools/sat/sat_base.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/sat/work_assignment.h"
#include "ortools/util/logging.h"
#if !defined(__PORTABLE_PLATFORM__)
#endif // __PORTABLE_PLATFORM__
#include "ortools/base/version.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
ABSL_FLAG(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}.pb.txt.");
#if defined(_MSC_VER)
ABSL_FLAG(std::string, cp_model_dump_prefix, ".\\",
"Prefix filename for all dumped files");
#else
ABSL_FLAG(std::string, cp_model_dump_prefix, "/tmp/",
"Prefix filename for all dumped files");
#endif
ABSL_FLAG(bool, cp_model_dump_submodels, false,
"DEBUG ONLY. When set to true, solve will dump all "
"lns or objective_shaving submodels proto in text format to "
"'FLAGS_cp_model_dump_prefix'xxx.pb.txt.");
ABSL_FLAG(
std::string, cp_model_load_debug_solution, "",
"DEBUG ONLY. When this is set to a non-empty file name, "
"we will interpret this as an internal solution which can be used for "
"debugging. For instance we use it to identify wrong cuts/reasons.");
ABSL_FLAG(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 {
// This should be called on the presolved model. It will read the file
// specified by --cp_model_load_debug_solution and properly fill the
// model->Get<DebugSolution>() proto vector.
void LoadDebugSolution(const CpModelProto& model_proto, Model* model) {
#if !defined(__PORTABLE_PLATFORM__)
if (absl::GetFlag(FLAGS_cp_model_load_debug_solution).empty()) return;
CpSolverResponse response;
SOLVER_LOG(model->GetOrCreate<SolverLogger>(),
"Reading debug solution from '",
absl::GetFlag(FLAGS_cp_model_load_debug_solution), "'.");
CHECK_OK(file::GetTextProto(absl::GetFlag(FLAGS_cp_model_load_debug_solution),
&response, file::Defaults()));
// Make sure we load a solution with the same number of variable has in the
// presolved model.
CHECK_EQ(response.solution().size(), model_proto.variables().size());
model->GetOrCreate<SharedResponseManager>()->LoadDebugSolution(
response.solution());
#endif // __PORTABLE_PLATFORM__
}
// This both copy the "main" DebugSolution to a local_model and also cache
// the value of the integer variables in that solution.
void InitializeDebugSolution(const CpModelProto& model_proto, Model* model) {
auto* shared_response = model->Get<SharedResponseManager>();
if (shared_response == nullptr) return;
if (shared_response->DebugSolution().empty()) return;
// Copy the proto values.
DebugSolution& debug_sol = *model->GetOrCreate<DebugSolution>();
debug_sol.proto_values = shared_response->DebugSolution();
// Fill the values by integer variable.
const int num_integers =
model->GetOrCreate<IntegerTrail>()->NumIntegerVariables().value();
debug_sol.ivar_has_value.assign(num_integers, false);
debug_sol.ivar_values.assign(num_integers, 0);
std::vector<Literal> boolean_solution;
const auto& mapping = *model->GetOrCreate<CpModelMapping>();
for (int i = 0; i < debug_sol.proto_values.size(); ++i) {
if (mapping.IsBoolean(i)) {
Literal l = mapping.Literal(i);
if (debug_sol.proto_values[i] == 0) {
l = l.Negated();
}
boolean_solution.push_back(l);
}
if (!mapping.IsInteger(i)) continue;
const IntegerVariable var = mapping.Integer(i);
debug_sol.ivar_has_value[var] = true;
debug_sol.ivar_has_value[NegationOf(var)] = true;
debug_sol.ivar_values[var] = debug_sol.proto_values[i];
debug_sol.ivar_values[NegationOf(var)] = -debug_sol.proto_values[i];
}
// If the solution is fully boolean (there is no integer variable), and
// we have a decision problem (so no new boolean should be created), we load
// it in the sat solver for debugging too.
if (boolean_solution.size() == debug_sol.proto_values.size() &&
!model_proto.has_objective()) {
LOG(INFO) << "Loaded pure Boolean debugging solution.";
model->GetOrCreate<SatSolver>()->LoadDebugSolution(boolean_solution);
}
// The objective variable is usually not part of the proto, but it is still
// nice to have it, so we recompute it here.
auto* objective_def = model->Get<ObjectiveDefinition>();
if (objective_def != nullptr) {
const IntegerVariable objective_var = objective_def->objective_var;
const int64_t objective_value =
ComputeInnerObjective(model_proto.objective(), debug_sol.proto_values);
debug_sol.ivar_has_value[objective_var] = true;
debug_sol.ivar_has_value[NegationOf(objective_var)] = true;
debug_sol.ivar_values[objective_var] = objective_value;
debug_sol.ivar_values[NegationOf(objective_var)] = -objective_value;
}
// We also register a DEBUG callback to check our reasons.
auto* encoder = model->GetOrCreate<IntegerEncoder>();
const auto checker = [mapping, encoder, debug_sol, model](
absl::Span<const Literal> clause,
absl::Span<const IntegerLiteral> integers) {
bool is_satisfied = false;
int num_bools = 0;
int num_ints = 0;
std::vector<std::tuple<Literal, IntegerLiteral, int>> to_print;
for (const Literal l : clause) {
// First case, this Boolean is mapped.
{
const int proto_var =
mapping.GetProtoVariableFromBooleanVariable(l.Variable());
if (proto_var != -1) {
to_print.push_back({l, IntegerLiteral(), proto_var});
if (debug_sol.proto_values[proto_var] == (l.IsPositive() ? 1 : 0)) {
is_satisfied = true;
break;
}
++num_bools;
continue;
}
}
// Second case, it is associated to IntVar >= value.
// We can use any of them, so if one is false, we use this one.
bool all_true = true;
for (const IntegerLiteral associated : encoder->GetIntegerLiterals(l)) {
const int proto_var = mapping.GetProtoVariableFromIntegerVariable(
PositiveVariable(associated.var));
if (proto_var == -1) break;
int64_t value = debug_sol.proto_values[proto_var];
to_print.push_back({l, associated, proto_var});
if (!VariableIsPositive(associated.var)) value = -value;
if (value < associated.bound) {
++num_ints;
all_true = false;
break;
}
}
if (all_true) {
is_satisfied = true;
break;
}
}
for (const IntegerLiteral i_lit : integers) {
const int proto_var = mapping.GetProtoVariableFromIntegerVariable(
PositiveVariable(i_lit.var));
if (proto_var == -1) {
is_satisfied = true;
break;
}
int64_t value = debug_sol.proto_values[proto_var];
to_print.push_back({Literal(kNoLiteralIndex), i_lit, proto_var});
if (!VariableIsPositive(i_lit.var)) value = -value;
// Note the sign is inversed, we cannot have all literal false and all
// integer literal true.
if (value >= i_lit.bound) {
is_satisfied = true;
break;
}
}
if (!is_satisfied) {
LOG(INFO) << "Reason clause is not satisfied by loaded solution:";
LOG(INFO) << "Worker '" << model->Name() << "', level="
<< model->GetOrCreate<SatSolver>()->CurrentDecisionLevel();
LOG(INFO) << "literals (neg): " << clause;
LOG(INFO) << "integer literals: " << integers;
for (const auto [l, i_lit, proto_var] : to_print) {
LOG(INFO) << l << " " << i_lit << " var=" << proto_var
<< " value_in_sol=" << debug_sol.proto_values[proto_var];
}
}
return is_satisfied;
};
const auto lit_checker = [checker](absl::Span<const Literal> clause) {
return checker(clause, {});
};
model->GetOrCreate<Trail>()->RegisterDebugChecker(lit_checker);
model->GetOrCreate<IntegerTrail>()->RegisterDebugChecker(checker);
}
std::vector<int64_t> GetSolutionValues(const CpModelProto& model_proto,
const Model& model) {
auto* mapping = model.Get<CpModelMapping>();
auto* trail = model.Get<Trail>();
std::vector<int64_t> solution;
for (int i = 0; i < model_proto.variables_size(); ++i) {
if (mapping->IsInteger(i)) {
const IntegerVariable var = mapping->Integer(i);
// For ignored or not fully instantiated variable, we just use the
// lower bound.
solution.push_back(model.Get(LowerBound(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 {
// Just use the lower bound if the variable is not fully instantiated.
solution.push_back(0);
}
}
}
if (DEBUG_MODE ||
absl::GetFlag(FLAGS_cp_model_check_intermediate_solutions)) {
// TODO(user): Checks against initial model.
CHECK(SolutionIsFeasible(model_proto, solution));
}
return solution;
}
namespace {
IntegerVariable GetOrCreateVariableWithTightBound(
const std::vector<std::pair<IntegerVariable, int64_t>>& 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_t sum_min = 0;
int64_t sum_max = 0;
for (const std::pair<IntegerVariable, int64_t>& var_coeff : terms) {
const int64_t min_domain = model->Get(LowerBound(var_coeff.first));
const int64_t max_domain = model->Get(UpperBound(var_coeff.first));
const int64_t coeff = var_coeff.second;
const int64_t prod1 = min_domain * coeff;
const int64_t 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 GetOrCreateVariableLinkedToSumOf(
const std::vector<std::pair<IntegerVariable, int64_t>>& terms,
bool lb_required, bool ub_required, 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);
}
const IntegerVariable new_var =
GetOrCreateVariableWithTightBound(terms, model);
// TODO(user): use the same format, i.e. LinearExpression in both code!
std::vector<IntegerVariable> vars;
std::vector<int64_t> coeffs;
for (const auto [var, coeff] : terms) {
vars.push_back(var);
coeffs.push_back(coeff);
}
vars.push_back(new_var);
coeffs.push_back(-1);
// Split if linear is large.
if (vars.size() > model->GetOrCreate<SatParameters>()->linear_split_size()) {
SplitAndLoadIntermediateConstraints(lb_required, ub_required, &vars,
&coeffs, model);
}
// Load the top-level constraint with the required sides.
if (lb_required) {
model->Add(WeightedSumGreaterOrEqual(vars, coeffs, 0));
}
if (ub_required) {
model->Add(WeightedSumLowerOrEqual(vars, coeffs, 0));
}
return new_var;
}
} // namespace
// Adds one LinearProgrammingConstraint per connected component of the model.
IntegerVariable AddLPConstraints(bool objective_need_to_be_tight,
const CpModelProto& model_proto, Model* m) {
// Non const as we will std::move() stuff out of there.
LinearRelaxation relaxation = ComputeLinearRelaxation(model_proto, m);
if (m->GetOrCreate<SatSolver>()->ModelIsUnsat()) return kNoIntegerVariable;
// 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 =
static_cast<int>(relaxation.linear_constraints.size());
const int num_lp_cut_generators =
static_cast<int>(relaxation.cut_generators.size());
const int num_integer_variables =
m->GetOrCreate<IntegerTrail>()->NumIntegerVariables().value();
DenseConnectedComponentsFinder components;
components.SetNumberOfNodes(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 +
PositiveVariable(var).value();
};
for (int i = 0; i < num_lp_constraints; i++) {
for (const IntegerVariable var :
relaxation.linear_constraints[i].VarsAsSpan()) {
components.AddEdge(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.AddEdge(get_cut_generator_index(i), get_var_index(var));
}
}
const int num_components = components.GetNumberOfComponents();
std::vector<int> component_sizes(num_components, 0);
const std::vector<int> index_to_component = components.GetComponentIds();
for (int i = 0; i < num_lp_constraints; i++) {
++component_sizes[index_to_component[get_constraint_index(i)]];
}
for (int i = 0; i < num_lp_cut_generators; i++) {
++component_sizes[index_to_component[get_cut_generator_index(i)]];
}
// TODO(user): Optimize memory layout.
std::vector<std::vector<IntegerVariable>> component_to_var(num_components);
for (IntegerVariable var(0); var < num_integer_variables; var += 2) {
DCHECK(VariableIsPositive(var));
component_to_var[index_to_component[get_var_index(var)]].push_back(var);
}
// 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));
++component_sizes[index_to_component[get_var_index(var)]];
}
// Dispatch every constraint to its LinearProgrammingConstraint.
std::vector<LinearProgrammingConstraint*> lp_constraints(num_components,
nullptr);
for (int i = 0; i < num_lp_constraints; i++) {
const int c = index_to_component[get_constraint_index(i)];
if (component_sizes[c] <= 1) continue;
if (lp_constraints[c] == nullptr) {
lp_constraints[c] =
new LinearProgrammingConstraint(m, component_to_var[c]);
m->TakeOwnership(lp_constraints[c]);
}
// Load the constraint.
lp_constraints[c]->AddLinearConstraint(
std::move(relaxation.linear_constraints[i]));
}
// Dispatch every cut generator to its LinearProgrammingConstraint.
for (int i = 0; i < num_lp_cut_generators; i++) {
const int c = index_to_component[get_cut_generator_index(i)];
if (lp_constraints[c] == nullptr) {
lp_constraints[c] =
new LinearProgrammingConstraint(m, component_to_var[c]);
m->TakeOwnership(lp_constraints[c]);
}
lp_constraints[c]->AddCutGenerator(std::move(relaxation.cut_generators[i]));
}
// Add the objective.
std::vector<std::vector<std::pair<IntegerVariable, int64_t>>>
component_to_cp_terms(num_components);
std::vector<std::pair<IntegerVariable, int64_t>> 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_t coeff = model_proto.objective().coeffs(i);
const int c = index_to_component[get_var_index(var)];
if (lp_constraints[c] != nullptr) {
lp_constraints[c]->SetObjectiveCoefficient(var, IntegerValue(coeff));
component_to_cp_terms[c].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 (int c = 0; c < num_components; ++c) {
if (component_to_cp_terms[c].empty()) continue;
const IntegerVariable sub_obj_var = GetOrCreateVariableLinkedToSumOf(
component_to_cp_terms[c], objective_need_to_be_tight, true, m);
top_level_cp_terms.push_back(std::make_pair(sub_obj_var, 1));
lp_constraints[c]->SetMainObjectiveVariable(sub_obj_var);
num_components_containing_objective++;
}
}
const IntegerVariable main_objective_var =
model_proto.has_objective()
? GetOrCreateVariableLinkedToSumOf(
top_level_cp_terms, objective_need_to_be_tight, true, m)
: kNoIntegerVariable;
// Register LP constraints. Note that this needs to be done after all the
// constraints have been added.
for (LinearProgrammingConstraint* lp_constraint : lp_constraints) {
if (lp_constraint == nullptr) continue;
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;
}
// 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);
auto* mapping = model->GetOrCreate<CpModelMapping>();
auto* trail = model->Get<Trail>();
auto* integer_trail = model->Get<IntegerTrail>();
int saved_trail_index = 0;
std::vector<int> model_variables;
std::vector<int64_t> new_lower_bounds;
std::vector<int64_t> new_upper_bounds;
absl::flat_hash_set<int> visited_variables;
const std::string name = model->Name();
auto broadcast_level_zero_bounds =
[=](const std::vector<IntegerVariable>& modified_vars) mutable {
// Inspect the modified IntegerVariables.
for (const IntegerVariable& var : modified_vars) {
const IntegerVariable positive_var = PositiveVariable(var);
const int model_var =
mapping->GetProtoVariableFromIntegerVariable(positive_var);
if (model_var == -1) continue;
const auto [_, inserted] = visited_variables.insert(model_var);
if (!inserted) continue;
const int64_t new_lb =
integer_trail->LevelZeroLowerBound(positive_var).value();
const int64_t new_ub =
integer_trail->LevelZeroUpperBound(positive_var).value();
// TODO(user): We could imagine an API based on atomic<int64_t>
// 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.
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) continue;
const auto [_, inserted] = visited_variables.insert(model_var);
if (!inserted) continue;
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()) {
shared_bounds_manager->ReportPotentialNewBounds(
model->Name(), model_variables, new_lower_bounds,
new_upper_bounds);
// Clear for next call.
model_variables.clear();
new_lower_bounds.clear();
new_upper_bounds.clear();
visited_variables.clear();
// If we are not in interleave_search we synchronize right away.
if (!model->Get<SatParameters>()->interleave_search()) {
shared_bounds_manager->Synchronize();
}
}
};
// The callback will just be called on NEWLY modified var. So initially,
// we do want to read all variables.
//
// TODO(user): Find a better way? It seems nicer to register this before
// any variable is modified. But then we don't want to call it each time
// we reach level zero during probing. It should be better to only call
// it when a new variable has been fixed.
const IntegerVariable num_vars =
model->GetOrCreate<IntegerTrail>()->NumIntegerVariables();
std::vector<IntegerVariable> all_variables;
all_variables.reserve(num_vars.value());
for (IntegerVariable var(0); var < num_vars; ++var) {
all_variables.push_back(var);
}
broadcast_level_zero_bounds(all_variables);
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);
const std::string name = model->Name();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
auto* trail = model->GetOrCreate<Trail>();
auto* sat_solver = model->GetOrCreate<SatSolver>();
auto* mapping = model->GetOrCreate<CpModelMapping>();
const int id = shared_bounds_manager->RegisterNewId();
const auto& import_level_zero_bounds = [&model_proto, shared_bounds_manager,
name, sat_solver, integer_trail,
trail, id, mapping]() {
std::vector<int> model_variables;
std::vector<int64_t> new_lower_bounds;
std::vector<int64_t> new_upper_bounds;
shared_bounds_manager->GetChangedBounds(
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];
// If this is a Boolean, fix it if not already done.
// Note that it is important not to use AddUnitClause() as we do not
// want to propagate after each addition.
if (mapping->IsBoolean(model_var)) {
Literal lit = mapping->Literal(model_var);
if (new_upper_bounds[i] == 0) lit = lit.Negated();
if (trail->Assignment().LiteralIsTrue(lit)) continue;
if (trail->Assignment().LiteralIsFalse(lit)) {
sat_solver->NotifyThatModelIsUnsat();
return false;
}
new_bounds_have_been_imported = true;
trail->EnqueueWithUnitReason(lit);
continue;
}
// Deal with integer.
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()
? absl::StrCat("anonymous_var(", model_var, ")")
: var_proto.name();
LOG(INFO) << " '" << name << "' imports new bounds for " << var_name
<< ": from [" << old_lb << ", " << old_ub << "] to ["
<< new_lb << ", " << new_ub << "]";
}
if (changed_lb &&
!integer_trail->Enqueue(IntegerLiteral::GreaterOrEqual(var, new_lb),
{}, {})) {
return false;
}
if (changed_ub &&
!integer_trail->Enqueue(IntegerLiteral::LowerOrEqual(var, new_ub), {},
{})) {
return false;
}
}
if (new_bounds_have_been_imported && !sat_solver->FinishPropagation()) {
return false;
}
return true;
};
model->GetOrCreate<LevelZeroCallbackHelper>()->callbacks.push_back(
import_level_zero_bounds);
}
// Registers a callback that will report improving objective best bound.
// It will be called each time new objective bound are propagated at level zero.
void RegisterObjectiveBestBoundExport(
IntegerVariable objective_var,
SharedResponseManager* shared_response_manager, Model* model) {
auto* integer_trail = model->Get<IntegerTrail>();
const auto broadcast_objective_lower_bound =
[objective_var, integer_trail, shared_response_manager, model,
best_obj_lb =
kMinIntegerValue](const std::vector<IntegerVariable>&) mutable {
const IntegerValue objective_lb =
integer_trail->LevelZeroLowerBound(objective_var);
if (objective_lb > best_obj_lb) {
best_obj_lb = objective_lb;
shared_response_manager->UpdateInnerObjectiveBounds(
model->Name(), objective_lb,
integer_trail->LevelZeroUpperBound(objective_var));
// If we are not in interleave_search we synchronize right away.
if (!model->Get<SatParameters>()->interleave_search()) {
shared_response_manager->Synchronize();
}
}
};
model->GetOrCreate<GenericLiteralWatcher>()
->RegisterLevelZeroModifiedVariablesCallback(
broadcast_objective_lower_bound);
}
// Registers a callback to import new objective bounds. It will be called each
// time the search main loop is back to level zero. Note that it the presence of
// assumptions, this will not happen until the set of assumptions is changed.
void RegisterObjectiveBoundsImport(
SharedResponseManager* shared_response_manager, Model* model) {
auto* solver = model->GetOrCreate<SatSolver>();
auto* integer_trail = model->GetOrCreate<IntegerTrail>();
auto* objective = model->GetOrCreate<ObjectiveDefinition>();
const std::string name = model->Name();
const auto import_objective_bounds = [name, solver, integer_trail, objective,
shared_response_manager]() {
if (solver->AssumptionLevel() != 0) return true;
bool propagate = false;
const IntegerValue external_lb =
shared_response_manager->GetInnerObjectiveLowerBound();
const IntegerValue current_lb =
integer_trail->LowerBound(objective->objective_var);
if (external_lb > current_lb) {
if (!integer_trail->Enqueue(IntegerLiteral::GreaterOrEqual(
objective->objective_var, external_lb),
{}, {})) {
return false;
}
propagate = true;
}
const IntegerValue external_ub =
shared_response_manager->GetInnerObjectiveUpperBound();
const IntegerValue current_ub =
integer_trail->UpperBound(objective->objective_var);
if (external_ub < current_ub) {
if (!integer_trail->Enqueue(IntegerLiteral::LowerOrEqual(
objective->objective_var, external_ub),
{}, {})) {
return false;
}
propagate = true;
}
if (!propagate) return true;
VLOG(3) << "'" << name << "' imports objective bounds: external ["
<< objective->ScaleIntegerObjective(external_lb) << ", "
<< objective->ScaleIntegerObjective(external_ub) << "], current ["
<< objective->ScaleIntegerObjective(current_lb) << ", "
<< objective->ScaleIntegerObjective(current_ub) << "]";
return solver->FinishPropagation();
};
model->GetOrCreate<LevelZeroCallbackHelper>()->callbacks.push_back(
import_objective_bounds);
}
// Registers a callback that will export good clauses discovered during search.
void RegisterClausesExport(int id, SharedClausesManager* shared_clauses_manager,
Model* model) {
auto* mapping = model->GetOrCreate<CpModelMapping>();
const auto& share_binary_clause = [mapping, id, shared_clauses_manager](
Literal l1, Literal l2) {
const int var1 =
mapping->GetProtoVariableFromBooleanVariable(l1.Variable());
if (var1 == -1) return;
const int var2 =
mapping->GetProtoVariableFromBooleanVariable(l2.Variable());
if (var2 == -1) return;
const int lit1 = l1.IsPositive() ? var1 : NegatedRef(var1);
const int lit2 = l2.IsPositive() ? var2 : NegatedRef(var2);
shared_clauses_manager->AddBinaryClause(id, lit1, lit2);
};
model->GetOrCreate<BinaryImplicationGraph>()->SetAdditionCallback(
share_binary_clause);
if (!model->GetOrCreate<SatParameters>()->share_glue_clauses()) {
return;
}
auto* clause_stream = shared_clauses_manager->GetClauseStream(id);
const int max_lbd =
model->GetOrCreate<SatParameters>()->clause_cleanup_lbd_bound();
// Note that this callback takes no global locks, everything operates on this
// worker's own clause stream, whose lock is only used by this worker, and
// briefly when generating a batch in SharedClausesManager::Synchronize().
auto share_clause = [mapping, clause_stream, max_lbd,
clause = std::vector<int>()](
int lbd, absl::Span<const Literal> literals) mutable {
if (lbd <= 0 || lbd > max_lbd ||
!clause_stream->CanAccept(literals.size(), lbd)) {
return;
}
clause.clear();
for (const Literal& lit : literals) {
const int var =
mapping->GetProtoVariableFromBooleanVariable(lit.Variable());
if (var == -1) return;
clause.push_back(lit.IsPositive() ? var : NegatedRef(var));
}
clause_stream->Add(clause);
};
model->GetOrCreate<ClauseManager>()->SetAddClauseCallback(
std::move(share_clause));
}
// Registers a callback to import new clauses stored in the
// shared_clausess_manager. These clauses are imported at level 0 of the search
// in the linear scan minimize function.
// it returns the id of the worker in the shared clause manager.
//
// TODO(user): Can we import them in the core worker ?
int RegisterClausesLevelZeroImport(int id,
SharedClausesManager* shared_clauses_manager,
Model* model) {
CHECK(shared_clauses_manager != nullptr);
CpModelMapping* const mapping = model->GetOrCreate<CpModelMapping>();
auto* sat_solver = model->GetOrCreate<SatSolver>();
auto* implications = model->GetOrCreate<BinaryImplicationGraph>();
bool share_glue_clauses =
model->GetOrCreate<SatParameters>()->share_glue_clauses();
auto* clause_stream = share_glue_clauses
? shared_clauses_manager->GetClauseStream(id)
: nullptr;
const auto& import_level_zero_clauses = [shared_clauses_manager, id, mapping,
sat_solver, implications,
clause_stream]() {
std::vector<std::pair<int, int>> new_binary_clauses;
shared_clauses_manager->GetUnseenBinaryClauses(id, &new_binary_clauses);
implications->EnableSharing(false);
for (const auto& [ref1, ref2] : new_binary_clauses) {
const Literal l1 = mapping->Literal(ref1);
const Literal l2 = mapping->Literal(ref2);
if (!sat_solver->AddBinaryClause(l1, l2)) {
return false;
}
}
implications->EnableSharing(true);
if (clause_stream == nullptr) return true;
std::array<Literal, UniqueClauseStream::kMaxClauseSize> local_clause;
for (const absl::Span<const int> shared_clause :
shared_clauses_manager->GetUnseenClauses(id)) {
// Check this clause was not already learned by this worker.
// We can delete the fingerprint because we should not learn an identical
// clause, and the global stream will not emit the same clause while any
// worker hasn't consumed this clause (and thus also shouldn't relearn the
// clause).
if (clause_stream->Delete(shared_clause)) continue;
for (int i = 0; i < shared_clause.size(); ++i) {
local_clause[i] = mapping->Literal(shared_clause[i]);
}
if (!sat_solver->AddProblemClause(
absl::MakeSpan(local_clause).subspan(0, shared_clause.size()))) {
return false;
}
}
clause_stream->RemoveWorstClauses();
return true;
};
model->GetOrCreate<LevelZeroCallbackHelper>()->callbacks.push_back(
import_level_zero_clauses);
return id;
}
void LoadBaseModel(const CpModelProto& model_proto, Model* model) {
auto* shared_response_manager = model->GetOrCreate<SharedResponseManager>();
CHECK(shared_response_manager != nullptr);
auto* sat_solver = model->GetOrCreate<SatSolver>();
// Simple function for the few places where we do "return unsat()".
const auto unsat = [shared_response_manager, sat_solver, model] {
sat_solver->NotifyThatModelIsUnsat();
shared_response_manager->NotifyThatImprovingProblemIsInfeasible(
absl::StrCat(model->Name(), " [loading]"));
};
// We will add them all at once after model_proto is loaded.
model->GetOrCreate<IntegerEncoder>()->DisableImplicationBetweenLiteral();
auto* mapping = model->GetOrCreate<CpModelMapping>();
const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
const bool view_all_booleans_as_integers =
(parameters.linearization_level() >= 2) ||
(parameters.search_branching() == SatParameters::FIXED_SEARCH &&
model_proto.search_strategy().empty()) ||
parameters.optimize_with_max_hs();
LoadVariables(model_proto, view_all_booleans_as_integers, model);
DetectOptionalVariables(model_proto, model);
// TODO(user): The core algo and symmetries seems to be problematic in some
// cases. See for instance: neos-691058.mps.gz. This is probably because as
// we modify the model, our symmetry might be wrong? investigate.
//
// TODO(user): More generally, we cannot load the symmetry if we create
// new Booleans and constraints that link them to some Booleans of the model.
// Creating Booleans related to integer variable is fine since we only deal
// with Boolean only symmetry here. It is why we disable this when we have
// linear relaxation as some of them create new constraints.
if (!parameters.optimize_with_core() && parameters.symmetry_level() > 1 &&
!parameters.enumerate_all_solutions() &&
parameters.linearization_level() == 0) {
LoadBooleanSymmetries(model_proto, model);
}
ExtractEncoding(model_proto, model);
PropagateEncodingFromEquivalenceRelations(model_proto, model);
// Check the model is still feasible before continuing.
if (sat_solver->ModelIsUnsat()) return unsat();
// Fully encode variables as needed by the search strategy.
AddFullEncodingFromSearchBranching(model_proto, model);
if (sat_solver->ModelIsUnsat()) return unsat();
// Reserve space for the precedence relations.
model->GetOrCreate<PrecedenceRelations>()->Resize(
model->GetOrCreate<IntegerTrail>()->NumIntegerVariables().value());
// Load the constraints.
int num_ignored_constraints = 0;
absl::flat_hash_set<ConstraintProto::ConstraintCase> unsupported_types;
for (const ConstraintProto& ct : model_proto.constraints()) {
if (mapping->ConstraintIsAlreadyLoaded(&ct)) {
++num_ignored_constraints;
continue;
}
if (!LoadConstraint(ct, model)) {
unsupported_types.insert(ct.constraint_case());
continue;
}
// We propagate after each new Boolean constraint but not the integer
// ones. So we call FinishPropagation() manually here.
//
// Note that we only do that in debug mode as this can be really slow on
// certain types of problems with millions of constraints.
if (DEBUG_MODE) {
if (sat_solver->FinishPropagation()) {
Trail* trail = model->GetOrCreate<Trail>();
const int old_num_fixed = trail->Index();
if (trail->Index() > old_num_fixed) {
VLOG(3) << "Constraint fixed " << trail->Index() - old_num_fixed
<< " Boolean variable(s): " << ProtobufDebugString(ct);
}
}
}
if (sat_solver->ModelIsUnsat()) {
VLOG(2) << "UNSAT during extraction (after adding '"