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