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  // Fast track for the most common case.
74  const Domain initial_rhs = ReadDomainFromProto(ct.linear());
75  if (free_vars.size() == 1) {
76  const int var = free_vars[0];
77  const Domain domain = initial_rhs.AdditionWith(Domain(-fixed_activity))
78  .InverseMultiplicationBy(free_coeffs[0])
79  .IntersectionWith((*domains)[var]);
80  const int64 value = prefer_lower_value[var] ? domain.Min() : domain.Max();
81  (*domains)[var] = Domain(value);
82  return;
83  }
84 
85  // The postsolve code is a bit involved if there is more than one free
86  // variable, we have to postsolve them one by one.
87  //
88  // Here we recompute the same domains as during the presolve. Everything is
89  // like if we where substiting the variable one by one:
90  // terms[i] + fixed_activity \in rhs_domains[i]
91  // In the reverse order.
92  std::vector<Domain> rhs_domains;
93  rhs_domains.push_back(initial_rhs);
94  for (int i = 0; i + 1 < free_vars.size(); ++i) {
95  // Note that these should be exactly the same computation as the one done
96  // during presolve and should be exact. However, we have some tests that do
97  // not comply, so we don't check exactness here. Also, as long as we don't
98  // get empty domain below, and the complexity of the domain do not explode
99  // here, we should be fine.
100  Domain term = (*domains)[free_vars[i]].MultiplicationBy(-free_coeffs[i]);
101  rhs_domains.push_back(term.AdditionWith(rhs_domains.back()));
102  }
103  for (int i = free_vars.size() - 1; i >= 0; --i) {
104  // Choose a value for free_vars[i] that fall into rhs_domains[i] -
105  // fixed_activity. This will crash if the intersection is empty, but it
106  // shouldn't be.
107  const int var = free_vars[i];
108  const int64 coeff = free_coeffs[i];
109  const Domain domain = rhs_domains[i]
110  .AdditionWith(Domain(-fixed_activity))
112  .IntersectionWith((*domains)[var]);
113 
114  // TODO(user): I am not 100% that the algo here might cover all the presolve
115  // case, so if this fail, it might indicate an issue here and not in the
116  // presolve/solver code.
117  CHECK(!domain.IsEmpty()) << ct.ShortDebugString();
118  const int64 value = prefer_lower_value[var] ? domain.Min() : domain.Max();
119  (*domains)[var] = Domain(value);
120 
121  fixed_activity += coeff * value;
122  }
123  DCHECK(initial_rhs.Contains(fixed_activity));
124 }
125 
126 // We assign any non fixed lhs variables to their minimum value. Then we assign
127 // the target to the max. This should always be feasible.
128 void PostsolveIntMax(const ConstraintProto& ct, std::vector<Domain>* domains) {
129  int64 m = kint64min;
130  for (const int ref : ct.int_max().vars()) {
131  const int var = PositiveRef(ref);
132  if (!(*domains)[var].IsFixed()) {
133  // Assign to minimum value.
134  const int64 value =
135  RefIsPositive(ref) ? (*domains)[var].Min() : (*domains)[var].Max();
136  (*domains)[var] = Domain(value);
137  }
138 
139  const int64 value = (*domains)[var].FixedValue();
140  m = std::max(m, RefIsPositive(ref) ? value : -value);
141  }
142  const int target_ref = ct.int_max().target();
143  const int target_var = PositiveRef(target_ref);
144  if (RefIsPositive(target_ref)) {
145  (*domains)[target_var] = (*domains)[target_var].IntersectionWith(Domain(m));
146  } else {
147  (*domains)[target_var] =
148  (*domains)[target_var].IntersectionWith(Domain(-m));
149  }
150  CHECK(!(*domains)[target_var].IsEmpty());
151 }
152 
153 // We only support 3 cases in the presolve currently.
154 void PostsolveElement(const ConstraintProto& ct, std::vector<Domain>* domains) {
155  const int index_ref = ct.element().index();
156  const int index_var = PositiveRef(index_ref);
157  const int target_ref = ct.element().target();
158  const int target_var = PositiveRef(target_ref);
159 
160  // Deal with non-fixed target and non-fixed index. This only happen if
161  // whatever the value of the index and selected variable, we can choose a
162  // valid target, so we just fix the index to its min value in this case.
163  if (!(*domains)[target_var].IsFixed() && !(*domains)[index_var].IsFixed()) {
164  const int64 index_value = (*domains)[index_var].Min();
165  (*domains)[index_var] = Domain(index_value);
166 
167  // If the selected variable is not fixed, we also need to fix it.
168  const int selected_ref = ct.element().vars(
169  RefIsPositive(index_ref) ? index_value : -index_value);
170  const int selected_var = PositiveRef(selected_ref);
171  if (!(*domains)[selected_var].IsFixed()) {
172  (*domains)[selected_var] = Domain((*domains)[selected_var].Min());
173  }
174  }
175 
176  // Deal with fixed index (and constant vars).
177  if ((*domains)[index_var].IsFixed()) {
178  const int64 index_value = (*domains)[index_var].FixedValue();
179  const int selected_ref = ct.element().vars(
180  RefIsPositive(index_ref) ? index_value : -index_value);
181  const int selected_var = PositiveRef(selected_ref);
182  const int64 selected_value = (*domains)[selected_var].FixedValue();
183  (*domains)[target_var] = (*domains)[target_var].IntersectionWith(
184  Domain(RefIsPositive(target_ref) == RefIsPositive(selected_ref)
185  ? selected_value
186  : -selected_value));
187  DCHECK(!(*domains)[target_var].IsEmpty());
188  return;
189  }
190 
191  // Deal with fixed target (and constant vars).
192  const int64 target_value = (*domains)[target_var].FixedValue();
193  int selected_index_value = -1;
194  for (int i = 0; i < ct.element().vars().size(); ++i) {
195  const int ref = ct.element().vars(i);
196  const int var = PositiveRef(ref);
197  const int64 value = (*domains)[var].FixedValue();
198  if (RefIsPositive(target_ref) == RefIsPositive(ref)) {
199  if (value == target_value) {
200  selected_index_value = i;
201  break;
202  }
203  } else {
204  if (value == -target_value) {
205  selected_index_value = i;
206  break;
207  }
208  }
209  }
210 
211  CHECK_NE(selected_index_value, -1);
212  (*domains)[index_var] = (*domains)[index_var].IntersectionWith(Domain(
213  RefIsPositive(index_var) ? selected_index_value : -selected_index_value));
214  DCHECK(!(*domains)[index_var].IsEmpty());
215 }
216 
217 void PostsolveResponse(const int64 num_variables_in_original_model,
218  const CpModelProto& mapping_proto,
219  const std::vector<int>& postsolve_mapping,
220  CpSolverResponse* response) {
221  // Map back the sufficient assumptions for infeasibility.
222  for (int& ref :
223  *(response->mutable_sufficient_assumptions_for_infeasibility())) {
224  ref = RefIsPositive(ref) ? postsolve_mapping[ref]
225  : NegatedRef(postsolve_mapping[PositiveRef(ref)]);
226  }
227 
228  // Abort if no solution or something is wrong.
229  if (response->status() != CpSolverStatus::FEASIBLE &&
230  response->status() != CpSolverStatus::OPTIMAL) {
231  return;
232  }
233  if (response->solution_size() != postsolve_mapping.size()) return;
234 
235  // Read the initial variable domains, either from the fixed solution of the
236  // presolved problems or from the mapping model.
237  std::vector<Domain> domains(mapping_proto.variables_size());
238  for (int i = 0; i < postsolve_mapping.size(); ++i) {
239  CHECK_LE(postsolve_mapping[i], domains.size());
240  domains[postsolve_mapping[i]] = Domain(response->solution(i));
241  }
242  for (int i = 0; i < domains.size(); ++i) {
243  if (domains[i].IsEmpty()) {
244  domains[i] = ReadDomainFromProto(mapping_proto.variables(i));
245  }
246  CHECK(!domains[i].IsEmpty());
247  }
248 
249  // Some free variable should be fixed towards their good objective direction.
250  //
251  // TODO(user): currently the objective is not part of the mapping_proto, so
252  // this shouldn't matter for our current presolve reduction.
253  CHECK(!mapping_proto.has_objective());
254  std::vector<bool> prefer_lower_value(domains.size(), true);
255  if (mapping_proto.has_objective()) {
256  const int size = mapping_proto.objective().vars().size();
257  for (int i = 0; i < size; ++i) {
258  int var = mapping_proto.objective().vars(i);
259  int64 coeff = mapping_proto.objective().coeffs(i);
260  if (!RefIsPositive(var)) {
261  var = PositiveRef(var);
262  coeff = -coeff;
263  }
264  prefer_lower_value[i] = (coeff >= 0);
265  }
266  }
267 
268  // Process the constraints in reverse order.
269  const int num_constraints = mapping_proto.constraints_size();
270  for (int i = num_constraints - 1; i >= 0; i--) {
271  const ConstraintProto& ct = mapping_proto.constraints(i);
272 
273  // We should only encounter assigned enforcement literal.
274  bool enforced = true;
275  for (const int ref : ct.enforcement_literal()) {
276  if (domains[PositiveRef(ref)].FixedValue() ==
277  (RefIsPositive(ref) ? 0 : 1)) {
278  enforced = false;
279  break;
280  }
281  }
282  if (!enforced) continue;
283 
284  switch (ct.constraint_case()) {
285  case ConstraintProto::kBoolOr:
286  PostsolveClause(ct, &domains);
287  break;
288  case ConstraintProto::kLinear:
289  PostsolveLinear(ct, prefer_lower_value, &domains);
290  break;
291  case ConstraintProto::kIntMax:
292  PostsolveIntMax(ct, &domains);
293  break;
294  case ConstraintProto::kElement:
295  PostsolveElement(ct, &domains);
296  break;
297  default:
298  // This should never happen as we control what kind of constraint we
299  // add to the mapping_proto;
300  LOG(FATAL) << "Unsupported constraint: " << ct.ShortDebugString();
301  }
302  }
303 
304  // Fill the response. Maybe fix some still unfixed variable.
305  response->mutable_solution()->Clear();
306  CHECK_LE(num_variables_in_original_model, domains.size());
307  for (int i = 0; i < num_variables_in_original_model; ++i) {
308  if (prefer_lower_value[i]) {
309  response->add_solution(domains[i].Min());
310  } else {
311  response->add_solution(domains[i].Max());
312  }
313  }
314 }
315 
316 } // namespace sat
317 } // 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...