OR-Tools  8.1
cp_model_checker.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 
16 #include <algorithm>
17 #include <memory>
18 #include <utility>
19 
20 #include "absl/container/flat_hash_map.h"
21 #include "absl/container/flat_hash_set.h"
22 #include "absl/strings/str_cat.h"
23 #include "ortools/base/hash.h"
24 #include "ortools/base/logging.h"
25 #include "ortools/base/map_util.h"
31 
32 namespace operations_research {
33 namespace sat {
34 namespace {
35 
36 // =============================================================================
37 // CpModelProto validation.
38 // =============================================================================
39 
40 // If the string returned by "statement" is not empty, returns it.
41 #define RETURN_IF_NOT_EMPTY(statement) \
42  do { \
43  const std::string error_message = statement; \
44  if (!error_message.empty()) return error_message; \
45  } while (false)
46 
47 template <typename ProtoWithDomain>
48 bool DomainInProtoIsValid(const ProtoWithDomain& proto) {
49  if (proto.domain().size() % 2) return false;
50  std::vector<ClosedInterval> domain;
51  for (int i = 0; i < proto.domain_size(); i += 2) {
52  if (proto.domain(i) > proto.domain(i + 1)) return false;
53  domain.push_back({proto.domain(i), proto.domain(i + 1)});
54  }
55  return IntervalsAreSortedAndNonAdjacent(domain);
56 }
57 
58 bool VariableReferenceIsValid(const CpModelProto& model, int reference) {
59  // We do it this way to avoid overflow if reference is kint64min for instance.
60  if (reference >= model.variables_size()) return false;
61  return reference >= -static_cast<int>(model.variables_size());
62 }
63 
64 bool LiteralReferenceIsValid(const CpModelProto& model, int reference) {
65  if (!VariableReferenceIsValid(model, reference)) return false;
66  const auto& var_proto = model.variables(PositiveRef(reference));
67  const int64 min_domain = var_proto.domain(0);
68  const int64 max_domain = var_proto.domain(var_proto.domain_size() - 1);
69  return min_domain >= 0 && max_domain <= 1;
70 }
71 
72 std::string ValidateIntegerVariable(const CpModelProto& model, int v) {
73  const IntegerVariableProto& proto = model.variables(v);
74  if (proto.domain_size() == 0) {
75  return absl::StrCat("var #", v,
76  " has no domain(): ", ProtobufShortDebugString(proto));
77  }
78  if (proto.domain_size() % 2 != 0) {
79  return absl::StrCat("var #", v, " has an odd domain() size: ",
81  }
82  if (!DomainInProtoIsValid(proto)) {
83  return absl::StrCat("var #", v, " has and invalid domain() format: ",
85  }
86 
87  // Internally, we often take the negation of a domain, and we also want to
88  // have sentinel values greater than the min/max of a variable domain, so
89  // the domain must fall in [kint64min + 2, kint64max - 1].
90  const int64 lb = proto.domain(0);
91  const int64 ub = proto.domain(proto.domain_size() - 1);
92  if (lb < kint64min + 2 || ub > kint64max - 1) {
93  return absl::StrCat(
94  "var #", v, " domain do not fall in [kint64min + 2, kint64max - 1]. ",
96  }
97 
98  // We do compute ub - lb in some place in the code and do not want to deal
99  // with overflow everywhere. This seems like a reasonable precondition anyway.
100  if (lb < 0 && lb + kint64max < ub) {
101  return absl::StrCat(
102  "var #", v,
103  " has a domain that is too large, i.e. |UB - LB| overflow an int64: ",
105  }
106 
107  return "";
108 }
109 
110 std::string ValidateArgumentReferencesInConstraint(const CpModelProto& model,
111  int c) {
112  const ConstraintProto& ct = model.constraints(c);
113  IndexReferences references = GetReferencesUsedByConstraint(ct);
114  for (const int v : references.variables) {
115  if (!VariableReferenceIsValid(model, v)) {
116  return absl::StrCat("Out of bound integer variable ", v,
117  " in constraint #", c, " : ",
119  }
120  }
121  for (const int lit : ct.enforcement_literal()) {
122  if (!LiteralReferenceIsValid(model, lit)) {
123  return absl::StrCat("Invalid enforcement literal ", lit,
124  " in constraint #", c, " : ",
126  }
127  }
128  for (const int lit : references.literals) {
129  if (!LiteralReferenceIsValid(model, lit)) {
130  return absl::StrCat("Invalid literal ", lit, " in constraint #", c, " : ",
132  }
133  }
134  for (const int i : UsedIntervals(ct)) {
135  if (i < 0 || i >= model.constraints_size()) {
136  return absl::StrCat("Out of bound interval ", i, " in constraint #", c,
137  " : ", ProtobufShortDebugString(ct));
138  }
139  if (model.constraints(i).constraint_case() !=
140  ConstraintProto::ConstraintCase::kInterval) {
141  return absl::StrCat(
142  "Interval ", i,
143  " does not refer to an interval constraint. Problematic constraint #",
144  c, " : ", ProtobufShortDebugString(ct));
145  }
146  }
147  return "";
148 }
149 
150 template <class LinearExpressionProto>
151 bool PossibleIntegerOverflow(const CpModelProto& model,
152  const LinearExpressionProto& proto) {
153  int64 sum_min = 0;
154  int64 sum_max = 0;
155  for (int i = 0; i < proto.vars_size(); ++i) {
156  const int ref = proto.vars(i);
157  const auto& var_proto = model.variables(PositiveRef(ref));
158  const int64 min_domain = var_proto.domain(0);
159  const int64 max_domain = var_proto.domain(var_proto.domain_size() - 1);
160  const int64 coeff = RefIsPositive(ref) ? proto.coeffs(i) : -proto.coeffs(i);
161  const int64 prod1 = CapProd(min_domain, coeff);
162  const int64 prod2 = CapProd(max_domain, coeff);
163 
164  // Note that we use min/max with zero to disallow "alternative" terms and
165  // be sure that we cannot have an overflow if we do the computation in a
166  // different order.
167  sum_min = CapAdd(sum_min, std::min(int64{0}, std::min(prod1, prod2)));
168  sum_max = CapAdd(sum_max, std::max(int64{0}, std::max(prod1, prod2)));
169  for (const int64 v : {prod1, prod2, sum_min, sum_max}) {
170  if (v == kint64max || v == kint64min) return true;
171  }
172  }
173 
174  // In addition to computing the min/max possible sum, we also often compare
175  // it with the constraint bounds, so we do not want max - min to overflow.
176  if (sum_min < 0 && sum_min + kint64max < sum_max) {
177  return true;
178  }
179  return false;
180 }
181 
182 std::string ValidateIntervalConstraint(const CpModelProto& model,
183  const ConstraintProto& ct) {
184  const IntervalConstraintProto& arg = ct.interval();
185  if (arg.size() < 0) {
186  const IntegerVariableProto& size_var_proto =
187  model.variables(NegatedRef(arg.size()));
188  if (size_var_proto.domain(size_var_proto.domain_size() - 1) > 0) {
189  return absl::StrCat(
190  "Negative value in interval size domain: ", ProtobufDebugString(ct),
191  "negation of size var: ", ProtobufDebugString(size_var_proto));
192  }
193  } else {
194  const IntegerVariableProto& size_var_proto = model.variables(arg.size());
195  if (size_var_proto.domain(0) < 0) {
196  return absl::StrCat(
197  "Negative value in interval size domain: ", ProtobufDebugString(ct),
198  "size var: ", ProtobufDebugString(size_var_proto));
199  }
200  }
201  return "";
202 }
203 
204 std::string ValidateLinearConstraint(const CpModelProto& model,
205  const ConstraintProto& ct) {
206  const LinearConstraintProto& arg = ct.linear();
207  if (PossibleIntegerOverflow(model, arg)) {
208  return "Possible integer overflow in constraint: " +
210  }
211  return "";
212 }
213 
214 std::string ValidateLinearExpression(const CpModelProto& model,
215  const LinearExpressionProto& expr) {
216  if (expr.coeffs_size() != expr.vars_size()) {
217  return absl::StrCat("coeffs_size() != vars_size() in linear expression: ",
219  }
220  if (PossibleIntegerOverflow(model, expr)) {
221  return absl::StrCat("Possible overflow in linear expression: ",
223  }
224  return "";
225 }
226 
227 std::string ValidateCircuitConstraint(const CpModelProto& model,
228  const ConstraintProto& ct) {
229  const int size = ct.circuit().tails().size();
230  if (ct.circuit().heads().size() != size ||
231  ct.circuit().literals().size() != size) {
232  return absl::StrCat("Wrong field sizes in circuit: ",
234  }
235  return "";
236 }
237 
238 std::string ValidateRoutesConstraint(const CpModelProto& model,
239  const ConstraintProto& ct) {
240  const int size = ct.routes().tails().size();
241  if (ct.routes().heads().size() != size ||
242  ct.routes().literals().size() != size) {
243  return absl::StrCat("Wrong field sizes in routes: ",
245  }
246  return "";
247 }
248 
249 std::string ValidateReservoirConstraint(const CpModelProto& model,
250  const ConstraintProto& ct) {
251  if (ct.enforcement_literal_size() > 0) {
252  return "Reservoir does not support enforcement literals.";
253  }
254  if (ct.reservoir().times().size() != ct.reservoir().demands().size()) {
255  return absl::StrCat("Times and demands fields must be of the same size: ",
257  }
258  for (const int t : ct.reservoir().times()) {
259  const IntegerVariableProto& time = model.variables(t);
260  for (const int64 bound : time.domain()) {
261  if (bound < 0) {
262  return absl::StrCat("Time variables must be >= 0 in constraint ",
264  }
265  }
266  }
267  int64 sum_abs = 0;
268  for (const int64 demand : ct.reservoir().demands()) {
269  sum_abs = CapAdd(sum_abs, std::abs(demand));
270  if (sum_abs == kint64max) {
271  return "Possible integer overflow in constraint: " +
273  }
274  }
275  if (ct.reservoir().actives_size() > 0 &&
276  ct.reservoir().actives_size() != ct.reservoir().times_size()) {
277  return "Wrong array length of actives variables";
278  }
279  if (ct.reservoir().demands_size() > 0 &&
280  ct.reservoir().demands_size() != ct.reservoir().times_size()) {
281  return "Wrong array length of demands variables";
282  }
283  return "";
284 }
285 
286 std::string ValidateCircuitCoveringConstraint(const ConstraintProto& ct) {
287  const int num_nodes = ct.circuit_covering().nexts_size();
288  for (const int d : ct.circuit_covering().distinguished_nodes()) {
289  if (d < 0 || d >= num_nodes) {
290  return absl::StrCat("Distinguished node ", d, " not in [0, ", num_nodes,
291  ").");
292  }
293  }
294 
295  return "";
296 }
297 
298 std::string ValidateIntModConstraint(const CpModelProto& model,
299  const ConstraintProto& ct) {
300  if (ct.int_mod().vars().size() != 2) {
301  return absl::StrCat("An int_mod constraint should have exactly 2 terms: ",
303  }
304  const IntegerVariableProto& mod_proto = model.variables(ct.int_mod().vars(1));
305  if (mod_proto.domain(0) <= 0) {
306  return absl::StrCat(
307  "An int_mod must have a strictly positive modulo argument: ",
309  }
310  return "";
311 }
312 
313 std::string ValidateObjective(const CpModelProto& model,
314  const CpObjectiveProto& obj) {
315  if (!DomainInProtoIsValid(obj)) {
316  return absl::StrCat("The objective has and invalid domain() format: ",
318  }
319  if (obj.vars().size() != obj.coeffs().size()) {
320  return absl::StrCat("vars and coeffs size do not match in objective: ",
322  }
323  for (const int v : obj.vars()) {
324  if (!VariableReferenceIsValid(model, v)) {
325  return absl::StrCat("Out of bound integer variable ", v,
326  " in objective: ", ProtobufShortDebugString(obj));
327  }
328  }
329  if (PossibleIntegerOverflow(model, obj)) {
330  return "Possible integer overflow in objective: " +
331  ProtobufDebugString(obj);
332  }
333  return "";
334 }
335 
336 std::string ValidateSearchStrategies(const CpModelProto& model) {
337  for (const DecisionStrategyProto& strategy : model.search_strategy()) {
338  for (const int ref : strategy.variables()) {
339  if (!VariableReferenceIsValid(model, ref)) {
340  return absl::StrCat("Invalid variable reference in strategy: ",
341  ProtobufShortDebugString(strategy));
342  }
343  }
344  for (const auto& transformation : strategy.transformations()) {
345  if (transformation.positive_coeff() <= 0) {
346  return absl::StrCat("Affine transformation coeff should be positive: ",
347  ProtobufShortDebugString(transformation));
348  }
349  if (!VariableReferenceIsValid(model, transformation.var())) {
350  return absl::StrCat(
351  "Invalid variable reference in affine transformation: ",
352  ProtobufShortDebugString(transformation));
353  }
354  }
355  }
356  return "";
357 }
358 
359 std::string ValidateSolutionHint(const CpModelProto& model) {
360  if (!model.has_solution_hint()) return "";
361  const auto& hint = model.solution_hint();
362  if (hint.vars().size() != hint.values().size()) {
363  return "Invalid solution hint: vars and values do not have the same size.";
364  }
365  for (const int ref : hint.vars()) {
366  if (!VariableReferenceIsValid(model, ref)) {
367  return absl::StrCat("Invalid variable reference in solution hint: ", ref);
368  }
369  }
370  return "";
371 }
372 
373 } // namespace
374 
375 std::string ValidateCpModel(const CpModelProto& model) {
376  for (int v = 0; v < model.variables_size(); ++v) {
377  RETURN_IF_NOT_EMPTY(ValidateIntegerVariable(model, v));
378  }
379  for (int c = 0; c < model.constraints_size(); ++c) {
380  RETURN_IF_NOT_EMPTY(ValidateArgumentReferencesInConstraint(model, c));
381 
382  // By default, a constraint does not support enforcement literals except if
383  // explicitly stated by setting this to true below.
384  bool support_enforcement = false;
385 
386  // Other non-generic validations.
387  // TODO(user): validate all constraints.
388  const ConstraintProto& ct = model.constraints(c);
389  const ConstraintProto::ConstraintCase type = ct.constraint_case();
390  switch (type) {
391  case ConstraintProto::ConstraintCase::kIntDiv:
392  if (ct.int_div().vars().size() != 2) {
393  return absl::StrCat(
394  "An int_div constraint should have exactly 2 terms: ",
396  }
397  break;
398  case ConstraintProto::ConstraintCase::kIntMod:
399  RETURN_IF_NOT_EMPTY(ValidateIntModConstraint(model, ct));
400  break;
401  case ConstraintProto::ConstraintCase::kBoolOr:
402  support_enforcement = true;
403  break;
404  case ConstraintProto::ConstraintCase::kBoolAnd:
405  support_enforcement = true;
406  break;
407  case ConstraintProto::ConstraintCase::kLinear:
408  support_enforcement = true;
409  if (!DomainInProtoIsValid(ct.linear())) {
410  return absl::StrCat("Invalid domain in constraint #", c, " : ",
412  }
413  if (ct.linear().coeffs_size() != ct.linear().vars_size()) {
414  return absl::StrCat("coeffs_size() != vars_size() in constraint #", c,
415  " : ", ProtobufShortDebugString(ct));
416  }
417  RETURN_IF_NOT_EMPTY(ValidateLinearConstraint(model, ct));
418  break;
419  case ConstraintProto::ConstraintCase::kLinMax: {
420  const std::string target_error =
421  ValidateLinearExpression(model, ct.lin_min().target());
422  if (!target_error.empty()) return target_error;
423  for (int i = 0; i < ct.lin_max().exprs_size(); ++i) {
424  const std::string expr_error =
425  ValidateLinearExpression(model, ct.lin_max().exprs(i));
426  if (!expr_error.empty()) return expr_error;
427  }
428  break;
429  }
430  case ConstraintProto::ConstraintCase::kLinMin: {
431  const std::string target_error =
432  ValidateLinearExpression(model, ct.lin_min().target());
433  if (!target_error.empty()) return target_error;
434  for (int i = 0; i < ct.lin_min().exprs_size(); ++i) {
435  const std::string expr_error =
436  ValidateLinearExpression(model, ct.lin_min().exprs(i));
437  if (!expr_error.empty()) return expr_error;
438  }
439  break;
440  }
441 
442  case ConstraintProto::ConstraintCase::kInterval:
443  support_enforcement = true;
444  RETURN_IF_NOT_EMPTY(ValidateIntervalConstraint(model, ct));
445  break;
446  case ConstraintProto::ConstraintCase::kCumulative:
447  if (ct.cumulative().intervals_size() !=
448  ct.cumulative().demands_size()) {
449  return absl::StrCat(
450  "intervals_size() != demands_size() in constraint #", c, " : ",
452  }
453  break;
454  case ConstraintProto::ConstraintCase::kInverse:
455  if (ct.inverse().f_direct().size() != ct.inverse().f_inverse().size()) {
456  return absl::StrCat("Non-matching fields size in inverse: ",
458  }
459  break;
460  case ConstraintProto::ConstraintCase::kCircuit:
461  RETURN_IF_NOT_EMPTY(ValidateCircuitConstraint(model, ct));
462  break;
463  case ConstraintProto::ConstraintCase::kRoutes:
464  RETURN_IF_NOT_EMPTY(ValidateRoutesConstraint(model, ct));
465  break;
466  case ConstraintProto::ConstraintCase::kReservoir:
467  RETURN_IF_NOT_EMPTY(ValidateReservoirConstraint(model, ct));
468  break;
469  case ConstraintProto::ConstraintCase::kCircuitCovering:
470  RETURN_IF_NOT_EMPTY(ValidateCircuitCoveringConstraint(ct));
471  break;
472  default:
473  break;
474  }
475 
476  // Because some client set fixed enforcement literal which are supported
477  // in the presolve for all constraints, we just check that there is no
478  // non-fixed enforcement.
479  if (!support_enforcement && !ct.enforcement_literal().empty()) {
480  for (const int ref : ct.enforcement_literal()) {
481  const int var = PositiveRef(ref);
482  const Domain domain = ReadDomainFromProto(model.variables(var));
483  if (domain.Size() != 1) {
484  return absl::StrCat(
485  "Enforcement literal not supported in constraint: ",
487  }
488  }
489  }
490  }
491  if (model.has_objective()) {
492  RETURN_IF_NOT_EMPTY(ValidateObjective(model, model.objective()));
493  }
494  RETURN_IF_NOT_EMPTY(ValidateSearchStrategies(model));
495  RETURN_IF_NOT_EMPTY(ValidateSolutionHint(model));
496  for (const int ref : model.assumptions()) {
497  if (!LiteralReferenceIsValid(model, ref)) {
498  return absl::StrCat("Invalid literal reference ", ref,
499  " in the 'assumptions' field.");
500  }
501  }
502  return "";
503 }
504 
505 #undef RETURN_IF_NOT_EMPTY
506 
507 // =============================================================================
508 // Solution Feasibility.
509 // =============================================================================
510 
511 namespace {
512 
513 class ConstraintChecker {
514  public:
515  explicit ConstraintChecker(const std::vector<int64>& variable_values)
516  : variable_values_(variable_values) {}
517 
518  bool LiteralIsTrue(int l) const {
519  if (l >= 0) return variable_values_[l] != 0;
520  return variable_values_[-l - 1] == 0;
521  }
522 
523  bool LiteralIsFalse(int l) const { return !LiteralIsTrue(l); }
524 
525  int64 Value(int var) const {
526  if (var >= 0) return variable_values_[var];
527  return -variable_values_[-var - 1];
528  }
529 
530  bool ConstraintIsEnforced(const ConstraintProto& ct) {
531  for (const int lit : ct.enforcement_literal()) {
532  if (LiteralIsFalse(lit)) return false;
533  }
534  return true;
535  }
536 
537  bool BoolOrConstraintIsFeasible(const ConstraintProto& ct) {
538  for (const int lit : ct.bool_or().literals()) {
539  if (LiteralIsTrue(lit)) return true;
540  }
541  return false;
542  }
543 
544  bool BoolAndConstraintIsFeasible(const ConstraintProto& ct) {
545  for (const int lit : ct.bool_and().literals()) {
546  if (LiteralIsFalse(lit)) return false;
547  }
548  return true;
549  }
550 
551  bool AtMostOneConstraintIsFeasible(const ConstraintProto& ct) {
552  int num_true_literals = 0;
553  for (const int lit : ct.at_most_one().literals()) {
554  if (LiteralIsTrue(lit)) ++num_true_literals;
555  }
556  return num_true_literals <= 1;
557  }
558 
559  bool BoolXorConstraintIsFeasible(const ConstraintProto& ct) {
560  int sum = 0;
561  for (const int lit : ct.bool_xor().literals()) {
562  sum ^= LiteralIsTrue(lit) ? 1 : 0;
563  }
564  return sum == 1;
565  }
566 
567  bool LinearConstraintIsFeasible(const ConstraintProto& ct) {
568  int64 sum = 0;
569  const int num_variables = ct.linear().coeffs_size();
570  for (int i = 0; i < num_variables; ++i) {
571  sum += Value(ct.linear().vars(i)) * ct.linear().coeffs(i);
572  }
573  return DomainInProtoContains(ct.linear(), sum);
574  }
575 
576  bool IntMaxConstraintIsFeasible(const ConstraintProto& ct) {
577  const int64 max = Value(ct.int_max().target());
578  int64 actual_max = kint64min;
579  for (int i = 0; i < ct.int_max().vars_size(); ++i) {
580  actual_max = std::max(actual_max, Value(ct.int_max().vars(i)));
581  }
582  return max == actual_max;
583  }
584 
585  int64 LinearExpressionValue(const LinearExpressionProto& expr) {
586  int64 sum = expr.offset();
587  const int num_variables = expr.vars_size();
588  for (int i = 0; i < num_variables; ++i) {
589  sum += Value(expr.vars(i)) * expr.coeffs(i);
590  }
591  return sum;
592  }
593 
594  bool LinMaxConstraintIsFeasible(const ConstraintProto& ct) {
595  const int64 max = LinearExpressionValue(ct.lin_max().target());
596  int64 actual_max = kint64min;
597  for (int i = 0; i < ct.lin_max().exprs_size(); ++i) {
598  const int64 expr_value = LinearExpressionValue(ct.lin_max().exprs(i));
599  actual_max = std::max(actual_max, expr_value);
600  }
601  return max == actual_max;
602  }
603 
604  bool IntProdConstraintIsFeasible(const ConstraintProto& ct) {
605  const int64 prod = Value(ct.int_prod().target());
606  int64 actual_prod = 1;
607  for (int i = 0; i < ct.int_prod().vars_size(); ++i) {
608  actual_prod *= Value(ct.int_prod().vars(i));
609  }
610  return prod == actual_prod;
611  }
612 
613  bool IntDivConstraintIsFeasible(const ConstraintProto& ct) {
614  return Value(ct.int_div().target()) ==
615  Value(ct.int_div().vars(0)) / Value(ct.int_div().vars(1));
616  }
617 
618  bool IntModConstraintIsFeasible(const ConstraintProto& ct) {
619  return Value(ct.int_mod().target()) ==
620  Value(ct.int_mod().vars(0)) % Value(ct.int_mod().vars(1));
621  }
622 
623  bool IntMinConstraintIsFeasible(const ConstraintProto& ct) {
624  const int64 min = Value(ct.int_min().target());
625  int64 actual_min = kint64max;
626  for (int i = 0; i < ct.int_min().vars_size(); ++i) {
627  actual_min = std::min(actual_min, Value(ct.int_min().vars(i)));
628  }
629  return min == actual_min;
630  }
631 
632  bool LinMinConstraintIsFeasible(const ConstraintProto& ct) {
633  const int64 min = LinearExpressionValue(ct.lin_min().target());
634  int64 actual_min = kint64max;
635  for (int i = 0; i < ct.lin_min().exprs_size(); ++i) {
636  const int64 expr_value = LinearExpressionValue(ct.lin_min().exprs(i));
637  actual_min = std::min(actual_min, expr_value);
638  }
639  return min == actual_min;
640  }
641 
642  bool AllDiffConstraintIsFeasible(const ConstraintProto& ct) {
643  absl::flat_hash_set<int64> values;
644  for (const int v : ct.all_diff().vars()) {
645  if (gtl::ContainsKey(values, Value(v))) return false;
646  values.insert(Value(v));
647  }
648  return true;
649  }
650 
651  bool IntervalConstraintIsFeasible(const ConstraintProto& ct) {
652  const int64 size = Value(ct.interval().size());
653  if (size < 0) return false;
654  return Value(ct.interval().start()) + size == Value(ct.interval().end());
655  }
656 
657  bool NoOverlapConstraintIsFeasible(const CpModelProto& model,
658  const ConstraintProto& ct) {
659  std::vector<std::pair<int64, int64>> start_durations_pairs;
660  for (const int i : ct.no_overlap().intervals()) {
661  const ConstraintProto& interval_constraint = model.constraints(i);
662  if (ConstraintIsEnforced(interval_constraint)) {
663  const IntervalConstraintProto& interval =
664  interval_constraint.interval();
665  start_durations_pairs.push_back(
666  {Value(interval.start()), Value(interval.size())});
667  }
668  }
669  std::sort(start_durations_pairs.begin(), start_durations_pairs.end());
670  int64 previous_end = kint64min;
671  for (const auto pair : start_durations_pairs) {
672  if (pair.first < previous_end) return false;
673  previous_end = pair.first + pair.second;
674  }
675  return true;
676  }
677 
678  bool IntervalsAreDisjoint(const IntervalConstraintProto& interval1,
679  const IntervalConstraintProto& interval2) {
680  return Value(interval1.end()) <= Value(interval2.start()) ||
681  Value(interval2.end()) <= Value(interval1.start());
682  }
683 
684  bool IntervalIsEmpty(const IntervalConstraintProto& interval) {
685  return Value(interval.start()) == Value(interval.end());
686  }
687 
688  bool NoOverlap2DConstraintIsFeasible(const CpModelProto& model,
689  const ConstraintProto& ct) {
690  const auto& arg = ct.no_overlap_2d();
691  // Those intervals from arg.x_intervals and arg.y_intervals where both
692  // the x and y intervals are enforced.
693  std::vector<std::pair<const IntervalConstraintProto* const,
694  const IntervalConstraintProto* const>>
695  enforced_intervals_xy;
696  {
697  const int num_intervals = arg.x_intervals_size();
698  CHECK_EQ(arg.y_intervals_size(), num_intervals);
699  for (int i = 0; i < num_intervals; ++i) {
700  const ConstraintProto& x = model.constraints(arg.x_intervals(i));
701  const ConstraintProto& y = model.constraints(arg.y_intervals(i));
702  if (ConstraintIsEnforced(x) && ConstraintIsEnforced(y) &&
703  (!arg.boxes_with_null_area_can_overlap() ||
704  (!IntervalIsEmpty(x.interval()) &&
705  !IntervalIsEmpty(y.interval())))) {
706  enforced_intervals_xy.push_back({&x.interval(), &y.interval()});
707  }
708  }
709  }
710  const int num_enforced_intervals = enforced_intervals_xy.size();
711  for (int i = 0; i < num_enforced_intervals; ++i) {
712  for (int j = i + 1; j < num_enforced_intervals; ++j) {
713  const auto& xi = *enforced_intervals_xy[i].first;
714  const auto& yi = *enforced_intervals_xy[i].second;
715  const auto& xj = *enforced_intervals_xy[j].first;
716  const auto& yj = *enforced_intervals_xy[j].second;
717  if (!IntervalsAreDisjoint(xi, xj) && !IntervalsAreDisjoint(yi, yj) &&
718  !IntervalIsEmpty(xi) && !IntervalIsEmpty(xj) &&
719  !IntervalIsEmpty(yi) && !IntervalIsEmpty(yj)) {
720  VLOG(1) << "Interval " << i << "(x=[" << Value(xi.start()) << ", "
721  << Value(xi.end()) << "], y=[" << Value(yi.start()) << ", "
722  << Value(yi.end()) << "]) and " << j << "("
723  << "(x=[" << Value(xj.start()) << ", " << Value(xj.end())
724  << "], y=[" << Value(yj.start()) << ", " << Value(yj.end())
725  << "]) are not disjoint.";
726  return false;
727  }
728  }
729  }
730  return true;
731  }
732 
733  bool CumulativeConstraintIsFeasible(const CpModelProto& model,
734  const ConstraintProto& ct) {
735  // TODO(user,user): Improve complexity for large durations.
736  const int64 capacity = Value(ct.cumulative().capacity());
737  const int num_intervals = ct.cumulative().intervals_size();
738  absl::flat_hash_map<int64, int64> usage;
739  for (int i = 0; i < num_intervals; ++i) {
740  const ConstraintProto& interval_constraint =
741  model.constraints(ct.cumulative().intervals(i));
742  if (ConstraintIsEnforced(interval_constraint)) {
743  const IntervalConstraintProto& interval =
744  interval_constraint.interval();
745  const int64 start = Value(interval.start());
746  const int64 duration = Value(interval.size());
747  const int64 demand = Value(ct.cumulative().demands(i));
748  for (int64 t = start; t < start + duration; ++t) {
749  usage[t] += demand;
750  if (usage[t] > capacity) return false;
751  }
752  }
753  }
754  return true;
755  }
756 
757  bool ElementConstraintIsFeasible(const ConstraintProto& ct) {
758  const int index = Value(ct.element().index());
759  return Value(ct.element().vars(index)) == Value(ct.element().target());
760  }
761 
762  bool TableConstraintIsFeasible(const ConstraintProto& ct) {
763  const int size = ct.table().vars_size();
764  if (size == 0) return true;
765  for (int row_start = 0; row_start < ct.table().values_size();
766  row_start += size) {
767  int i = 0;
768  while (Value(ct.table().vars(i)) == ct.table().values(row_start + i)) {
769  ++i;
770  if (i == size) return !ct.table().negated();
771  }
772  }
773  return ct.table().negated();
774  }
775 
776  bool AutomatonConstraintIsFeasible(const ConstraintProto& ct) {
777  // Build the transition table {tail, label} -> head.
778  absl::flat_hash_map<std::pair<int64, int64>, int64> transition_map;
779  const int num_transitions = ct.automaton().transition_tail().size();
780  for (int i = 0; i < num_transitions; ++i) {
781  transition_map[{ct.automaton().transition_tail(i),
782  ct.automaton().transition_label(i)}] =
783  ct.automaton().transition_head(i);
784  }
785 
786  // Walk the automaton.
787  int64 current_state = ct.automaton().starting_state();
788  const int num_steps = ct.automaton().vars_size();
789  for (int i = 0; i < num_steps; ++i) {
790  const std::pair<int64, int64> key = {current_state,
791  Value(ct.automaton().vars(i))};
792  if (!gtl::ContainsKey(transition_map, key)) {
793  return false;
794  }
795  current_state = transition_map[key];
796  }
797 
798  // Check we are now in a final state.
799  for (const int64 final : ct.automaton().final_states()) {
800  if (current_state == final) return true;
801  }
802  return false;
803  }
804 
805  bool CircuitConstraintIsFeasible(const ConstraintProto& ct) {
806  // Compute the set of relevant nodes for the constraint and set the next of
807  // each of them. This also detects duplicate nexts.
808  const int num_arcs = ct.circuit().tails_size();
809  absl::flat_hash_set<int> nodes;
810  absl::flat_hash_map<int, int> nexts;
811  for (int i = 0; i < num_arcs; ++i) {
812  const int tail = ct.circuit().tails(i);
813  const int head = ct.circuit().heads(i);
814  nodes.insert(tail);
815  nodes.insert(head);
816  if (LiteralIsFalse(ct.circuit().literals(i))) continue;
817  if (nexts.contains(tail)) return false; // Duplicate.
818  nexts[tail] = head;
819  }
820 
821  // All node must have a next.
822  int in_cycle;
823  int cycle_size = 0;
824  for (const int node : nodes) {
825  if (!nexts.contains(node)) return false; // No next.
826  if (nexts[node] == node) continue; // skip self-loop.
827  in_cycle = node;
828  ++cycle_size;
829  }
830  if (cycle_size == 0) return true;
831 
832  // Check that we have only one cycle. visited is used to not loop forever if
833  // we have a "rho" shape instead of a cycle.
834  absl::flat_hash_set<int> visited;
835  int current = in_cycle;
836  int num_visited = 0;
837  while (!visited.contains(current)) {
838  ++num_visited;
839  visited.insert(current);
840  current = nexts[current];
841  }
842  if (current != in_cycle) return false; // Rho shape.
843  return num_visited == cycle_size; // Another cycle somewhere if false.
844  }
845 
846  bool RoutesConstraintIsFeasible(const ConstraintProto& ct) {
847  const int num_arcs = ct.routes().tails_size();
848  int num_used_arcs = 0;
849  int num_self_arcs = 0;
850  int num_nodes = 0;
851  std::vector<int> tail_to_head;
852  std::vector<int> depot_nexts;
853  for (int i = 0; i < num_arcs; ++i) {
854  const int tail = ct.routes().tails(i);
855  const int head = ct.routes().heads(i);
856  num_nodes = std::max(num_nodes, 1 + tail);
857  num_nodes = std::max(num_nodes, 1 + head);
858  tail_to_head.resize(num_nodes, -1);
859  if (LiteralIsTrue(ct.routes().literals(i))) {
860  if (tail == head) {
861  if (tail == 0) return false;
862  ++num_self_arcs;
863  continue;
864  }
865  ++num_used_arcs;
866  if (tail == 0) {
867  depot_nexts.push_back(head);
868  } else {
869  if (tail_to_head[tail] != -1) return false;
870  tail_to_head[tail] = head;
871  }
872  }
873  }
874 
875  // An empty constraint with no node to visit should be feasible.
876  if (num_nodes == 0) return true;
877 
878  // Make sure each routes from the depot go back to it, and count such arcs.
879  int count = 0;
880  for (int start : depot_nexts) {
881  ++count;
882  while (start != 0) {
883  if (tail_to_head[start] == -1) return false;
884  start = tail_to_head[start];
885  ++count;
886  }
887  }
888 
889  if (count != num_used_arcs) {
890  VLOG(1) << "count: " << count << " != num_used_arcs:" << num_used_arcs;
891  return false;
892  }
893 
894  // Each routes cover as many node as there is arcs, but this way we count
895  // multiple times the depot. So the number of nodes covered are:
896  // count - depot_nexts.size() + 1.
897  // And this number + the self arcs should be num_nodes.
898  if (count - depot_nexts.size() + 1 + num_self_arcs != num_nodes) {
899  VLOG(1) << "Not all nodes are covered!";
900  return false;
901  }
902 
903  return true;
904  }
905 
906  bool CircuitCoveringConstraintIsFeasible(const ConstraintProto& ct) {
907  const int num_nodes = ct.circuit_covering().nexts_size();
908  std::vector<bool> distinguished(num_nodes, false);
909  std::vector<bool> visited(num_nodes, false);
910  for (const int node : ct.circuit_covering().distinguished_nodes()) {
911  distinguished[node] = true;
912  }
913 
914  // By design, every node has exactly one neighbour.
915  // Check that distinguished nodes do not share a circuit,
916  // mark nodes visited during the process.
917  std::vector<int> next(num_nodes, -1);
918  for (const int d : ct.circuit_covering().distinguished_nodes()) {
919  visited[d] = true;
920  for (int node = Value(ct.circuit_covering().nexts(d)); node != d;
921  node = Value(ct.circuit_covering().nexts(node))) {
922  if (distinguished[node]) return false;
923  CHECK(!visited[node]);
924  visited[node] = true;
925  }
926  }
927 
928  // Check that nodes that were not visited are all loops.
929  for (int node = 0; node < num_nodes; node++) {
930  if (!visited[node] && Value(ct.circuit_covering().nexts(node)) != node) {
931  return false;
932  }
933  }
934  return true;
935  }
936 
937  bool InverseConstraintIsFeasible(const ConstraintProto& ct) {
938  const int num_variables = ct.inverse().f_direct_size();
939  if (num_variables != ct.inverse().f_inverse_size()) return false;
940  // Check that f_inverse(f_direct(i)) == i; this is sufficient.
941  for (int i = 0; i < num_variables; i++) {
942  const int fi = Value(ct.inverse().f_direct(i));
943  if (fi < 0 || num_variables <= fi) return false;
944  if (i != Value(ct.inverse().f_inverse(fi))) return false;
945  }
946  return true;
947  }
948 
949  bool ReservoirConstraintIsFeasible(const ConstraintProto& ct) {
950  const int num_variables = ct.reservoir().times_size();
951  const int64 min_level = ct.reservoir().min_level();
952  const int64 max_level = ct.reservoir().max_level();
953  std::map<int64, int64> deltas;
954  deltas[0] = 0;
955  const bool has_active_variables = ct.reservoir().actives_size() > 0;
956  for (int i = 0; i < num_variables; i++) {
957  const int64 time = Value(ct.reservoir().times(i));
958  if (time < 0) {
959  VLOG(1) << "reservoir times(" << i << ") is negative.";
960  return false;
961  }
962  if (!has_active_variables || Value(ct.reservoir().actives(i)) == 1) {
963  deltas[time] += ct.reservoir().demands(i);
964  }
965  }
966  int64 current_level = 0;
967  for (const auto& delta : deltas) {
968  current_level += delta.second;
969  if (current_level < min_level || current_level > max_level) {
970  VLOG(1) << "Reservoir level " << current_level
971  << " is out of bounds at time" << delta.first;
972  return false;
973  }
974  }
975  return true;
976  }
977 
978  private:
979  std::vector<int64> variable_values_;
980 };
981 
982 } // namespace
983 
984 bool SolutionIsFeasible(const CpModelProto& model,
985  const std::vector<int64>& variable_values,
986  const CpModelProto* mapping_proto,
987  const std::vector<int>* postsolve_mapping) {
988  if (variable_values.size() != model.variables_size()) {
989  VLOG(1) << "Wrong number of variables in the solution vector";
990  return false;
991  }
992 
993  // Check that all values fall in the variable domains.
994  for (int i = 0; i < model.variables_size(); ++i) {
995  if (!DomainInProtoContains(model.variables(i), variable_values[i])) {
996  VLOG(1) << "Variable #" << i << " has value " << variable_values[i]
997  << " which do not fall in its domain: "
998  << ProtobufShortDebugString(model.variables(i));
999  return false;
1000  }
1001  }
1002 
1003  CHECK_EQ(variable_values.size(), model.variables_size());
1004  ConstraintChecker checker(variable_values);
1005 
1006  for (int c = 0; c < model.constraints_size(); ++c) {
1007  const ConstraintProto& ct = model.constraints(c);
1008 
1009  if (!checker.ConstraintIsEnforced(ct)) continue;
1010 
1011  bool is_feasible = true;
1012  const ConstraintProto::ConstraintCase type = ct.constraint_case();
1013  switch (type) {
1014  case ConstraintProto::ConstraintCase::kBoolOr:
1015  is_feasible = checker.BoolOrConstraintIsFeasible(ct);
1016  break;
1017  case ConstraintProto::ConstraintCase::kBoolAnd:
1018  is_feasible = checker.BoolAndConstraintIsFeasible(ct);
1019  break;
1020  case ConstraintProto::ConstraintCase::kAtMostOne:
1021  is_feasible = checker.AtMostOneConstraintIsFeasible(ct);
1022  break;
1023  case ConstraintProto::ConstraintCase::kBoolXor:
1024  is_feasible = checker.BoolXorConstraintIsFeasible(ct);
1025  break;
1026  case ConstraintProto::ConstraintCase::kLinear:
1027  is_feasible = checker.LinearConstraintIsFeasible(ct);
1028  break;
1029  case ConstraintProto::ConstraintCase::kIntProd:
1030  is_feasible = checker.IntProdConstraintIsFeasible(ct);
1031  break;
1032  case ConstraintProto::ConstraintCase::kIntDiv:
1033  is_feasible = checker.IntDivConstraintIsFeasible(ct);
1034  break;
1035  case ConstraintProto::ConstraintCase::kIntMod:
1036  is_feasible = checker.IntModConstraintIsFeasible(ct);
1037  break;
1038  case ConstraintProto::ConstraintCase::kIntMin:
1039  is_feasible = checker.IntMinConstraintIsFeasible(ct);
1040  break;
1041  case ConstraintProto::ConstraintCase::kLinMin:
1042  is_feasible = checker.LinMinConstraintIsFeasible(ct);
1043  break;
1044  case ConstraintProto::ConstraintCase::kIntMax:
1045  is_feasible = checker.IntMaxConstraintIsFeasible(ct);
1046  break;
1047  case ConstraintProto::ConstraintCase::kLinMax:
1048  is_feasible = checker.LinMaxConstraintIsFeasible(ct);
1049  break;
1050  case ConstraintProto::ConstraintCase::kAllDiff:
1051  is_feasible = checker.AllDiffConstraintIsFeasible(ct);
1052  break;
1053  case ConstraintProto::ConstraintCase::kInterval:
1054  is_feasible = checker.IntervalConstraintIsFeasible(ct);
1055  break;
1056  case ConstraintProto::ConstraintCase::kNoOverlap:
1057  is_feasible = checker.NoOverlapConstraintIsFeasible(model, ct);
1058  break;
1059  case ConstraintProto::ConstraintCase::kNoOverlap2D:
1060  is_feasible = checker.NoOverlap2DConstraintIsFeasible(model, ct);
1061  break;
1062  case ConstraintProto::ConstraintCase::kCumulative:
1063  is_feasible = checker.CumulativeConstraintIsFeasible(model, ct);
1064  break;
1065  case ConstraintProto::ConstraintCase::kElement:
1066  is_feasible = checker.ElementConstraintIsFeasible(ct);
1067  break;
1068  case ConstraintProto::ConstraintCase::kTable:
1069  is_feasible = checker.TableConstraintIsFeasible(ct);
1070  break;
1071  case ConstraintProto::ConstraintCase::kAutomaton:
1072  is_feasible = checker.AutomatonConstraintIsFeasible(ct);
1073  break;
1074  case ConstraintProto::ConstraintCase::kCircuit:
1075  is_feasible = checker.CircuitConstraintIsFeasible(ct);
1076  break;
1077  case ConstraintProto::ConstraintCase::kRoutes:
1078  is_feasible = checker.RoutesConstraintIsFeasible(ct);
1079  break;
1080  case ConstraintProto::ConstraintCase::kCircuitCovering:
1081  is_feasible = checker.CircuitCoveringConstraintIsFeasible(ct);
1082  break;
1083  case ConstraintProto::ConstraintCase::kInverse:
1084  is_feasible = checker.InverseConstraintIsFeasible(ct);
1085  break;
1086  case ConstraintProto::ConstraintCase::kReservoir:
1087  is_feasible = checker.ReservoirConstraintIsFeasible(ct);
1088  break;
1089  case ConstraintProto::ConstraintCase::CONSTRAINT_NOT_SET:
1090  // Empty constraint is always feasible.
1091  break;
1092  default:
1093  LOG(FATAL) << "Unuspported constraint: " << ConstraintCaseName(type);
1094  }
1095  if (!is_feasible) {
1096  VLOG(1) << "Failing constraint #" << c << " : "
1097  << ProtobufShortDebugString(model.constraints(c));
1098  if (mapping_proto != nullptr && postsolve_mapping != nullptr) {
1099  std::vector<bool> fixed(mapping_proto->variables().size(), false);
1100  for (const int var : *postsolve_mapping) fixed[var] = true;
1101  for (const int var : UsedVariables(model.constraints(c))) {
1102  VLOG(1) << "var: " << var << " value: " << variable_values[var]
1103  << " was_fixed: " << fixed[var] << " initial_domain: "
1104  << ReadDomainFromProto(model.variables(var))
1105  << " postsolved_domain: "
1106  << ReadDomainFromProto(mapping_proto->variables(var));
1107  }
1108  }
1109 
1110  return false;
1111  }
1112  }
1113  return true;
1114 }
1115 
1116 } // namespace sat
1117 } // namespace operations_research
var
IntVar * var
Definition: expr_array.cc:1858
tail
int64 tail
Definition: routing_flow.cc:127
min
int64 min
Definition: alldiff_cst.cc:138
map_util.h
VLOG
#define VLOG(verboselevel)
Definition: base/logging.h:978
cp_model.pb.h
max
int64 max
Definition: alldiff_cst.cc:139
bound
int64 bound
Definition: routing_search.cc:969
LOG
#define LOG(severity)
Definition: base/logging.h:420
operations_research::CapProd
int64 CapProd(int64 x, int64 y)
Definition: saturated_arithmetic.h:231
FATAL
const int FATAL
Definition: log_severity.h:32
proto_utils.h
operations_research::sat::UsedVariables
std::vector< int > UsedVariables(const ConstraintProto &ct)
Definition: cp_model_utils.cc:441
logging.h
saturated_arithmetic.h
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
operations_research::sat::GetReferencesUsedByConstraint
IndexReferences GetReferencesUsedByConstraint(const ConstraintProto &ct)
Definition: cp_model_utils.cc:46
kint64min
static const int64 kint64min
Definition: integral_types.h:60
operations_research::Domain
We call domain any subset of Int64 = [kint64min, kint64max].
Definition: sorted_interval_list.h:81
int64
int64_t int64
Definition: integral_types.h:34
operations_research::sat::SolutionIsFeasible
bool SolutionIsFeasible(const CpModelProto &model, const std::vector< int64 > &variable_values, const CpModelProto *mapping_proto, const std::vector< int > *postsolve_mapping)
Definition: cp_model_checker.cc:984
index
int index
Definition: pack.cc:508
operations_research::sat::UsedIntervals
std::vector< int > UsedIntervals(const ConstraintProto &ct)
Definition: cp_model_utils.cc:456
operations_research::ProtobufDebugString
std::string ProtobufDebugString(const P &message)
Definition: port/proto_utils.h:53
demand
int64 demand
Definition: resource.cc:123
operations_research::sat::PositiveRef
int PositiveRef(int ref)
Definition: cp_model_utils.h:33
operations_research::CapAdd
int64 CapAdd(int64 x, int64 y)
Definition: saturated_arithmetic.h:124
CHECK_EQ
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:697
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::sat::Value
std::function< int64(const Model &)> Value(IntegerVariable v)
Definition: integer.h:1414
operations_research::sat::DomainInProtoContains
bool DomainInProtoContains(const ProtoWithDomain &proto, int64 value)
Definition: cp_model_utils.h:82
operations_research::sat::NegatedRef
int NegatedRef(int ref)
Definition: cp_model_utils.h:32
sorted_interval_list.h
operations_research::IntervalsAreSortedAndNonAdjacent
bool IntervalsAreSortedAndNonAdjacent(absl::Span< const ClosedInterval > intervals)
Returns true iff we have:
Definition: sorted_interval_list.cc:37
model
GRBmodel * model
Definition: gurobi_interface.cc:269
operations_research::Domain::Size
int64 Size() const
Returns the number of elements in the domain.
Definition: sorted_interval_list.cc:194
operations_research::sat::RefIsPositive
bool RefIsPositive(int ref)
Definition: cp_model_utils.h:34
RETURN_IF_NOT_EMPTY
#define RETURN_IF_NOT_EMPTY(statement)
Definition: cp_model_checker.cc:41
operations_research::ProtobufShortDebugString
std::string ProtobufShortDebugString(const P &message)
Definition: port/proto_utils.h:58
hash.h
delta
int64 delta
Definition: resource.cc:1684
operations_research::sat::ConstraintCaseName
std::string ConstraintCaseName(ConstraintProto::ConstraintCase constraint_case)
Definition: cp_model_utils.cc:383
capacity
int64 capacity
Definition: routing_flow.cc:129
interval
IntervalVar * interval
Definition: resource.cc:98
next
Block * next
Definition: constraint_solver.cc:674
proto
CpModelProto proto
Definition: cp_model_fz_solver.cc:106
cp_model_checker.h
head
int64 head
Definition: routing_flow.cc:128
operations_research::sat::ReadDomainFromProto
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Definition: cp_model_utils.h:102
operations_research::sat::ValidateCpModel
std::string ValidateCpModel(const CpModelProto &model)
Definition: cp_model_checker.cc:375
CHECK
#define CHECK(condition)
Definition: base/logging.h:495
kint64max
static const int64 kint64max
Definition: integral_types.h:62
cp_model_utils.h
time
int64 time
Definition: resource.cc:1683
gtl::ContainsKey
bool ContainsKey(const Collection &collection, const Key &key)
Definition: map_util.h:170