OR-Tools  8.2
cp_model_postsolve.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
15 
17 
18 namespace operations_research {
19 namespace sat {
20 
21 // This postsolve is "special". If the clause is not satisfied, we fix the
22 // first literal in the clause to true (even if it was fixed to false). This
23 // allows to handle more complex presolve operations used by the SAT presolver.
24 //
25 // Also, any "free" Boolean should be fixed to some value for the subsequent
26 // postsolve steps.
27 void PostsolveClause(const ConstraintProto& ct, std::vector<Domain>* domains) {
28  const int size = ct.bool_or().literals_size();
29  CHECK_NE(size, 0);
30  bool satisfied = false;
31  for (int i = 0; i < size; ++i) {
32  const int ref = ct.bool_or().literals(i);
33  const int var = PositiveRef(ref);
34  if ((*domains)[var].IsFixed()) {
35  if ((*domains)[var].FixedValue() == (RefIsPositive(ref) ? 1 : 0)) {
36  satisfied = true;
37  }
38  } else {
39  // We still need to assign free variable. Any value should work.
40  (*domains)[PositiveRef(ref)] = Domain(0);
41  }
42  }
43  if (satisfied) return;
44 
45  // Change the value of the first variable (which was chosen at presolve).
46  const int first_ref = ct.bool_or().literals(0);
47  (*domains)[PositiveRef(first_ref)] = Domain(RefIsPositive(first_ref) ? 1 : 0);
48 }
49 
50 // Here we simply assign all non-fixed variable to a feasible value. Which
51 // should always exists by construction.
52 void PostsolveLinear(const ConstraintProto& ct,
53  const std::vector<bool>& prefer_lower_value,
54  std::vector<Domain>* domains) {
55  int64 fixed_activity = 0;
56  const int size = ct.linear().vars().size();
57  std::vector<int> free_vars;
58  std::vector<int64> free_coeffs;
59  for (int i = 0; i < size; ++i) {
60  const int var = ct.linear().vars(i);
61  const int64 coeff = ct.linear().coeffs(i);
62  CHECK_LT(var, domains->size());
63  if (coeff == 0) continue;
64  if ((*domains)[var].IsFixed()) {
65  fixed_activity += (*domains)[var].FixedValue() * coeff;
66  } else {
67  free_vars.push_back(var);
68  free_coeffs.push_back(coeff);
69  }
70  }
71  if (free_vars.empty()) return;
72 
73  Domain rhs =
74  ReadDomainFromProto(ct.linear()).AdditionWith(Domain(-fixed_activity));
75 
76  // Fast track for the most common case.
77  if (free_vars.size() == 1) {
78  const int var = free_vars[0];
79  const Domain domain = rhs.InverseMultiplicationBy(free_coeffs[0])
80  .IntersectionWith((*domains)[var]);
81  const int64 value = prefer_lower_value[var] ? domain.Min() : domain.Max();
82  (*domains)[var] = Domain(value);
83  return;
84  }
85 
86  // The postsolve code is a bit involved if there is more than one free
87  // variable, we have to postsolve them one by one.
88  //
89  // Note that if there are some not free variable that are not assigned, the
90  // presolve should have made it sure that whatever the value of those
91  // variables the first variable can always be assigned to satisfy the
92  // constraint. In that case, the MultiplicationBy() below might be inexact,
93  // but that should be okay.
94  std::vector<Domain> to_add;
95  to_add.push_back(Domain(0));
96  for (int i = 0; i + 1 < free_vars.size(); ++i) {
97  Domain term = (*domains)[free_vars[i]].MultiplicationBy(-free_coeffs[i]);
98  to_add.push_back(term.AdditionWith(to_add.back()));
99  }
100  for (int i = free_vars.size() - 1; i >= 0; --i) {
101  // Choose a value for free_vars[i] that fall into rhs + to_add[i].
102  // This will crash if the intersection is empty, but it shouldn't be.
103  const int var = free_vars[i];
104  const int64 coeff = free_coeffs[i];
105  const Domain domain = rhs.AdditionWith(to_add[i])
107  .IntersectionWith((*domains)[var]);
108 
109  // TODO(user): I am not 100% that the algo here might cover all the presolve
110  // case, so if this fail, it might indicate an issue here and not in the
111  // presolve/solver code.
112  CHECK(!domain.IsEmpty()) << ct.ShortDebugString();
113  const int64 value = prefer_lower_value[var] ? domain.Min() : domain.Max();
114  (*domains)[var] = Domain(value);
115  rhs = rhs.AdditionWith(Domain(-coeff * value));
116 
117  // Only needed in debug.
118  fixed_activity += coeff * value;
119  }
120  DCHECK(ReadDomainFromProto(ct.linear()).Contains(fixed_activity));
121 }
122 
123 // We assign any non fixed lhs variables to their minimum value. Then we assign
124 // the target to the max. This should always be feasible.
125 void PostsolveIntMax(const ConstraintProto& ct, std::vector<Domain>* domains) {
126  int64 m = kint64min;
127  for (const int ref : ct.int_max().vars()) {
128  const int var = PositiveRef(ref);
129  if (!(*domains)[var].IsFixed()) {
130  // Assign to minimum value.
131  const int64 value =
132  RefIsPositive(ref) ? (*domains)[var].Min() : (*domains)[var].Max();
133  (*domains)[var] = Domain(value);
134  }
135 
136  const int64 value = (*domains)[var].FixedValue();
137  m = std::max(m, RefIsPositive(ref) ? value : -value);
138  }
139  const int target_ref = ct.int_max().target();
140  const int target_var = PositiveRef(target_ref);
141  if (RefIsPositive(target_ref)) {
142  (*domains)[target_var] = (*domains)[target_var].IntersectionWith(Domain(m));
143  } else {
144  (*domains)[target_var] =
145  (*domains)[target_var].IntersectionWith(Domain(-m));
146  }
147  CHECK(!(*domains)[target_var].IsEmpty());
148 }
149 
150 // We only support 3 cases in the presolve currently.
151 void PostsolveElement(const ConstraintProto& ct, std::vector<Domain>* domains) {
152  const int index_ref = ct.element().index();
153  const int index_var = PositiveRef(index_ref);
154  const int target_ref = ct.element().target();
155  const int target_var = PositiveRef(target_ref);
156 
157  // Deal with non-fixed target and non-fixed index. This only happen if
158  // whatever the value of the index and selected variable, we can choose a
159  // valid target, so we just fix the index to its min value in this case.
160  if (!(*domains)[target_var].IsFixed() && !(*domains)[index_var].IsFixed()) {
161  const int64 index_value = (*domains)[index_var].Min();
162  (*domains)[index_var] = Domain(index_value);
163 
164  // If the selected variable is not fixed, we also need to fix it.
165  const int selected_ref = ct.element().vars(
166  RefIsPositive(index_ref) ? index_value : -index_value);
167  const int selected_var = PositiveRef(selected_ref);
168  if (!(*domains)[selected_var].IsFixed()) {
169  (*domains)[selected_var] = Domain((*domains)[selected_var].Min());
170  }
171  }
172 
173  // Deal with fixed index (and constant vars).
174  if ((*domains)[index_var].IsFixed()) {
175  const int64 index_value = (*domains)[index_var].FixedValue();
176  const int selected_ref = ct.element().vars(
177  RefIsPositive(index_ref) ? index_value : -index_value);
178  const int selected_var = PositiveRef(selected_ref);
179  const int64 selected_value = (*domains)[selected_var].FixedValue();
180  (*domains)[target_var] = (*domains)[target_var].IntersectionWith(
181  Domain(RefIsPositive(target_ref) == RefIsPositive(selected_ref)
182  ? selected_value
183  : -selected_value));
184  DCHECK(!(*domains)[target_var].IsEmpty());
185  return;
186  }
187 
188  // Deal with fixed target (and constant vars).
189  const int64 target_value = (*domains)[target_var].FixedValue();
190  int selected_index_value = -1;
191  for (int i = 0; i < ct.element().vars().size(); ++i) {
192  const int ref = ct.element().vars(i);
193  const int var = PositiveRef(ref);
194  const int64 value = (*domains)[var].FixedValue();
195  if (RefIsPositive(target_ref) == RefIsPositive(ref)) {
196  if (value == target_value) {
197  selected_index_value = i;
198  break;
199  }
200  } else {
201  if (value == -target_value) {
202  selected_index_value = i;
203  break;
204  }
205  }
206  }
207 
208  CHECK_NE(selected_index_value, -1);
209  (*domains)[index_var] = (*domains)[index_var].IntersectionWith(Domain(
210  RefIsPositive(index_var) ? selected_index_value : -selected_index_value));
211  DCHECK(!(*domains)[index_var].IsEmpty());
212 }
213 
214 void PostsolveResponse(const int64 num_variables_in_original_model,
215  const CpModelProto& mapping_proto,
216  const std::vector<int>& postsolve_mapping,
217  CpSolverResponse* response) {
218  // Map back the sufficient assumptions for infeasibility.
219  for (int& ref :
220  *(response->mutable_sufficient_assumptions_for_infeasibility())) {
221  ref = RefIsPositive(ref) ? postsolve_mapping[ref]
222  : NegatedRef(postsolve_mapping[PositiveRef(ref)]);
223  }
224 
225  // Abort if no solution or something is wrong.
226  if (response->status() != CpSolverStatus::FEASIBLE &&
227  response->status() != CpSolverStatus::OPTIMAL) {
228  return;
229  }
230  if (response->solution_size() != postsolve_mapping.size()) return;
231 
232  // Read the initial variable domains, either from the fixed solution of the
233  // presolved problems or from the mapping model.
234  std::vector<Domain> domains(mapping_proto.variables_size());
235  for (int i = 0; i < postsolve_mapping.size(); ++i) {
236  CHECK_LE(postsolve_mapping[i], domains.size());
237  domains[postsolve_mapping[i]] = Domain(response->solution(i));
238  }
239  for (int i = 0; i < domains.size(); ++i) {
240  if (domains[i].IsEmpty()) {
241  domains[i] = ReadDomainFromProto(mapping_proto.variables(i));
242  }
243  CHECK(!domains[i].IsEmpty());
244  }
245 
246  // Some free variable should be fixed towards their good objective direction.
247  //
248  // TODO(user): currently the objective is not part of the mapping_proto, so
249  // this shouldn't matter for our current presolve reduction.
250  CHECK(!mapping_proto.has_objective());
251  std::vector<bool> prefer_lower_value(domains.size(), true);
252  if (mapping_proto.has_objective()) {
253  const int size = mapping_proto.objective().vars().size();
254  for (int i = 0; i < size; ++i) {
255  int var = mapping_proto.objective().vars(i);
256  int64 coeff = mapping_proto.objective().coeffs(i);
257  if (!RefIsPositive(var)) {
258  var = PositiveRef(var);
259  coeff = -coeff;
260  }
261  prefer_lower_value[i] = (coeff >= 0);
262  }
263  }
264 
265  // Process the constraints in reverse order.
266  const int num_constraints = mapping_proto.constraints_size();
267  for (int i = num_constraints - 1; i >= 0; i--) {
268  const ConstraintProto& ct = mapping_proto.constraints(i);
269 
270  // We should only encounter assigned enforcement literal.
271  bool enforced = true;
272  for (const int ref : ct.enforcement_literal()) {
273  if (domains[PositiveRef(ref)].FixedValue() ==
274  (RefIsPositive(ref) ? 0 : 1)) {
275  enforced = false;
276  break;
277  }
278  }
279  if (!enforced) continue;
280 
281  switch (ct.constraint_case()) {
282  case ConstraintProto::kBoolOr:
283  PostsolveClause(ct, &domains);
284  break;
285  case ConstraintProto::kLinear:
286  PostsolveLinear(ct, prefer_lower_value, &domains);
287  break;
288  case ConstraintProto::kIntMax:
289  PostsolveIntMax(ct, &domains);
290  break;
291  case ConstraintProto::kElement:
292  PostsolveElement(ct, &domains);
293  break;
294  default:
295  // This should never happen as we control what kind of constraint we
296  // add to the mapping_proto;
297  LOG(FATAL) << "Unsupported constraint: " << ct.ShortDebugString();
298  }
299  }
300 
301  // Fill the response. Maybe fix some still unfixed variable.
302  response->mutable_solution()->Clear();
303  CHECK_LE(num_variables_in_original_model, domains.size());
304  for (int i = 0; i < num_variables_in_original_model; ++i) {
305  if (prefer_lower_value[i]) {
306  response->add_solution(domains[i].Min());
307  } else {
308  response->add_solution(domains[i].Max());
309  }
310  }
311 }
312 
313 } // namespace sat
314 } // namespace operations_research
int64 max
Definition: alldiff_cst.cc:139
#define CHECK(condition)
Definition: base/logging.h:495
#define CHECK_LT(val1, val2)
Definition: base/logging.h:700
#define CHECK_NE(val1, val2)
Definition: base/logging.h:698
#define LOG(severity)
Definition: base/logging.h:420
#define DCHECK(condition)
Definition: base/logging.h:884
#define CHECK_LE(val1, val2)
Definition: base/logging.h:699
We call domain any subset of Int64 = [kint64min, kint64max].
Domain MultiplicationBy(int64 coeff, bool *exact=nullptr) const
Returns {x ∈ Int64, ∃ e ∈ D, x = e * coeff}.
Domain InverseMultiplicationBy(const int64 coeff) const
Returns {x ∈ Int64, ∃ e ∈ D, x * coeff = e}.
Domain AdditionWith(const Domain &domain) const
Returns {x ∈ Int64, ∃ a ∈ D, ∃ b ∈ domain, x = a + b}.
int64 Min() const
Returns the min value of the domain.
int64 Max() const
Returns the max value of the domain.
Domain IntersectionWith(const Domain &domain) const
Returns the intersection of D and domain.
bool IsEmpty() const
Returns true if this is the empty set.
bool Contains(int64 value) const
Returns true iff value is in Domain.
SharedResponseManager * response
const Constraint * ct
int64 value
IntVar * var
Definition: expr_array.cc:1858
int64_t int64
static const int64 kint64min
const int FATAL
Definition: log_severity.h:32
void PostsolveElement(const ConstraintProto &ct, std::vector< Domain > *domains)
bool RefIsPositive(int ref)
void PostsolveIntMax(const ConstraintProto &ct, std::vector< Domain > *domains)
void PostsolveResponse(const int64 num_variables_in_original_model, const CpModelProto &mapping_proto, const std::vector< int > &postsolve_mapping, CpSolverResponse *response)
void PostsolveLinear(const ConstraintProto &ct, const std::vector< bool > &prefer_lower_value, std::vector< Domain > *domains)
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
void PostsolveClause(const ConstraintProto &ct, std::vector< Domain > *domains)
std::function< bool(const Model &)> IsFixed(IntegerVariable v)
Definition: integer.h:1479
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...