forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_checker.cc
1598 lines (1462 loc) · 61.1 KB
/
cp_model_checker.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/cp_model_checker.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "ortools/base/hash.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/port/proto_utils.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace sat {
namespace {
// =============================================================================
// CpModelProto validation.
// =============================================================================
// If the string returned by "statement" is not empty, returns it.
#define RETURN_IF_NOT_EMPTY(statement) \
do { \
const std::string error_message = statement; \
if (!error_message.empty()) return error_message; \
} while (false)
template <typename ProtoWithDomain>
bool DomainInProtoIsValid(const ProtoWithDomain& proto) {
if (proto.domain().size() % 2) return false;
std::vector<ClosedInterval> domain;
for (int i = 0; i < proto.domain_size(); i += 2) {
if (proto.domain(i) > proto.domain(i + 1)) return false;
domain.push_back({proto.domain(i), proto.domain(i + 1)});
}
return IntervalsAreSortedAndNonAdjacent(domain);
}
bool VariableReferenceIsValid(const CpModelProto& model, int reference) {
// We do it this way to avoid overflow if reference is kint64min for instance.
if (reference >= model.variables_size()) return false;
return reference >= -static_cast<int>(model.variables_size());
}
// Note(user): Historically we always accepted positive or negative variable
// reference everywhere, but now that we can always substitute affine relation,
// we starts to transition to positive reference only, which are clearer. Note
// that this doesn't concern literal reference though.
bool VariableIndexIsValid(const CpModelProto& model, int var) {
return var >= 0 && var < model.variables_size();
}
bool LiteralReferenceIsValid(const CpModelProto& model, int reference) {
if (!VariableReferenceIsValid(model, reference)) return false;
const auto& var_proto = model.variables(PositiveRef(reference));
const int64_t min_domain = var_proto.domain(0);
const int64_t max_domain = var_proto.domain(var_proto.domain_size() - 1);
return min_domain >= 0 && max_domain <= 1;
}
std::string ValidateIntegerVariable(const CpModelProto& model, int v) {
const IntegerVariableProto& proto = model.variables(v);
if (proto.domain_size() == 0) {
return absl::StrCat("var #", v,
" has no domain(): ", ProtobufShortDebugString(proto));
}
if (proto.domain_size() % 2 != 0) {
return absl::StrCat("var #", v, " has an odd domain() size: ",
ProtobufShortDebugString(proto));
}
if (!DomainInProtoIsValid(proto)) {
return absl::StrCat("var #", v, " has and invalid domain() format: ",
ProtobufShortDebugString(proto));
}
// Internally, we often take the negation of a domain, and we also want to
// have sentinel values greater than the min/max of a variable domain, so
// the domain must fall in [kint64min + 2, kint64max - 1].
const int64_t lb = proto.domain(0);
const int64_t ub = proto.domain(proto.domain_size() - 1);
if (lb < std::numeric_limits<int64_t>::min() + 2 ||
ub > std::numeric_limits<int64_t>::max() - 1) {
return absl::StrCat(
"var #", v, " domain do not fall in [kint64min + 2, kint64max - 1]. ",
ProtobufShortDebugString(proto));
}
// We do compute ub - lb in some place in the code and do not want to deal
// with overflow everywhere. This seems like a reasonable precondition anyway.
if (lb < 0 && lb + std::numeric_limits<int64_t>::max() < ub) {
return absl::StrCat(
"var #", v,
" has a domain that is too large, i.e. |UB - LB| overflow an int64_t: ",
ProtobufShortDebugString(proto));
}
return "";
}
std::string ValidateArgumentReferencesInConstraint(const CpModelProto& model,
int c) {
const ConstraintProto& ct = model.constraints(c);
IndexReferences references = GetReferencesUsedByConstraint(ct);
for (const int v : references.variables) {
if (!VariableReferenceIsValid(model, v)) {
return absl::StrCat("Out of bound integer variable ", v,
" in constraint #", c, " : ",
ProtobufShortDebugString(ct));
}
}
for (const int lit : ct.enforcement_literal()) {
if (!LiteralReferenceIsValid(model, lit)) {
return absl::StrCat("Invalid enforcement literal ", lit,
" in constraint #", c, " : ",
ProtobufShortDebugString(ct));
}
}
for (const int lit : references.literals) {
if (!LiteralReferenceIsValid(model, lit)) {
return absl::StrCat("Invalid literal ", lit, " in constraint #", c, " : ",
ProtobufShortDebugString(ct));
}
}
for (const int i : UsedIntervals(ct)) {
if (i < 0 || i >= model.constraints_size()) {
return absl::StrCat("Out of bound interval ", i, " in constraint #", c,
" : ", ProtobufShortDebugString(ct));
}
if (model.constraints(i).constraint_case() !=
ConstraintProto::ConstraintCase::kInterval) {
return absl::StrCat(
"Interval ", i,
" does not refer to an interval constraint. Problematic constraint #",
c, " : ", ProtobufShortDebugString(ct));
}
}
return "";
}
template <class LinearExpressionProto>
bool PossibleIntegerOverflow(const CpModelProto& model,
const LinearExpressionProto& proto,
int64_t offset = 0) {
if (offset == std::numeric_limits<int64_t>::min()) return true;
int64_t sum_min = -std::abs(offset);
int64_t sum_max = +std::abs(offset);
for (int i = 0; i < proto.vars_size(); ++i) {
const int ref = proto.vars(i);
const auto& var_proto = model.variables(PositiveRef(ref));
const int64_t min_domain = var_proto.domain(0);
const int64_t max_domain = var_proto.domain(var_proto.domain_size() - 1);
if (proto.coeffs(i) == std::numeric_limits<int64_t>::min()) return true;
const int64_t coeff =
RefIsPositive(ref) ? proto.coeffs(i) : -proto.coeffs(i);
const int64_t prod1 = CapProd(min_domain, coeff);
const int64_t prod2 = CapProd(max_domain, coeff);
// Note that we use min/max with zero to disallow "alternative" terms and
// be sure that we cannot have an overflow if we do the computation in a
// different order.
sum_min = CapAdd(sum_min, std::min(int64_t{0}, std::min(prod1, prod2)));
sum_max = CapAdd(sum_max, std::max(int64_t{0}, std::max(prod1, prod2)));
for (const int64_t v : {prod1, prod2, sum_min, sum_max}) {
if (v == std::numeric_limits<int64_t>::max() ||
v == std::numeric_limits<int64_t>::min())
return true;
}
}
// In addition to computing the min/max possible sum, we also often compare
// it with the constraint bounds, so we do not want max - min to overflow.
if (sum_min < 0 && sum_min + std::numeric_limits<int64_t>::max() < sum_max) {
return true;
}
return false;
}
int64_t MinOfRef(const CpModelProto& model, int ref) {
const IntegerVariableProto& var_proto = model.variables(PositiveRef(ref));
if (RefIsPositive(ref)) {
return var_proto.domain(0);
} else {
return -var_proto.domain(var_proto.domain_size() - 1);
}
}
int64_t MaxOfRef(const CpModelProto& model, int ref) {
const IntegerVariableProto& var_proto = model.variables(PositiveRef(ref));
if (RefIsPositive(ref)) {
return var_proto.domain(var_proto.domain_size() - 1);
} else {
return -var_proto.domain(0);
}
}
template <class LinearExpressionProto>
int64_t MinOfExpression(const CpModelProto& model,
const LinearExpressionProto& proto) {
int64_t sum_min = proto.offset();
for (int i = 0; i < proto.vars_size(); ++i) {
const int ref = proto.vars(i);
const int64_t coeff = proto.coeffs(i);
sum_min =
CapAdd(sum_min, coeff >= 0 ? CapProd(MinOfRef(model, ref), coeff)
: CapProd(MaxOfRef(model, ref), coeff));
}
return sum_min;
}
template <class LinearExpressionProto>
int64_t MaxOfExpression(const CpModelProto& model,
const LinearExpressionProto& proto) {
int64_t sum_max = proto.offset();
for (int i = 0; i < proto.vars_size(); ++i) {
const int ref = proto.vars(i);
const int64_t coeff = proto.coeffs(i);
sum_max =
CapAdd(sum_max, coeff >= 0 ? CapProd(MaxOfRef(model, ref), coeff)
: CapProd(MinOfRef(model, ref), coeff));
}
return sum_max;
}
int64_t IntervalSizeMin(const CpModelProto& model, int interval_index) {
DCHECK_EQ(ConstraintProto::ConstraintCase::kInterval,
model.constraints(interval_index).constraint_case());
const IntervalConstraintProto& proto =
model.constraints(interval_index).interval();
return MinOfExpression(model, proto.size());
}
int64_t IntervalSizeMax(const CpModelProto& model, int interval_index) {
DCHECK_EQ(ConstraintProto::ConstraintCase::kInterval,
model.constraints(interval_index).constraint_case());
const IntervalConstraintProto& proto =
model.constraints(interval_index).interval();
return MaxOfExpression(model, proto.size());
}
Domain DomainOfRef(const CpModelProto& model, int ref) {
const Domain domain = ReadDomainFromProto(model.variables(PositiveRef(ref)));
return RefIsPositive(ref) ? domain : domain.Negation();
}
std::string ValidateLinearExpression(const CpModelProto& model,
const LinearExpressionProto& expr) {
if (expr.coeffs_size() != expr.vars_size()) {
return absl::StrCat("coeffs_size() != vars_size() in linear expression: ",
ProtobufShortDebugString(expr));
}
if (PossibleIntegerOverflow(model, expr, expr.offset())) {
return absl::StrCat("Possible overflow in linear expression: ",
ProtobufShortDebugString(expr));
}
return "";
}
std::string ValidateAffineExpression(const CpModelProto& model,
const LinearExpressionProto& expr) {
if (expr.vars_size() > 1) {
return absl::StrCat("expression must be affine: ",
ProtobufShortDebugString(expr));
}
return ValidateLinearExpression(model, expr);
}
std::string ValidateLinearConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (!DomainInProtoIsValid(ct.linear())) {
return absl::StrCat("Invalid domain in constraint : ",
ProtobufShortDebugString(ct));
}
if (ct.linear().coeffs_size() != ct.linear().vars_size()) {
return absl::StrCat("coeffs_size() != vars_size() in constraint: ",
ProtobufShortDebugString(ct));
}
const LinearConstraintProto& arg = ct.linear();
if (PossibleIntegerOverflow(model, arg)) {
return "Possible integer overflow in constraint: " +
ProtobufDebugString(ct);
}
return "";
}
std::string ValidateIntModConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.int_mod().exprs().size() != 2) {
return absl::StrCat("An int_mod constraint should have exactly 2 terms: ",
ProtobufShortDebugString(ct));
}
if (!ct.int_mod().has_target()) {
return absl::StrCat("An int_mod constraint should have a target: ",
ProtobufShortDebugString(ct));
}
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_mod().exprs(0)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_mod().exprs(1)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_mod().target()));
const LinearExpressionProto mod_expr = ct.int_mod().exprs(1);
if (MinOfExpression(model, mod_expr) <= 0) {
return absl::StrCat(
"An int_mod must have a strictly positive modulo argument: ",
ProtobufShortDebugString(ct));
}
return "";
}
std::string ValidateIntProdConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.int_prod().exprs().size() != 2) {
return absl::StrCat("An int_prod constraint should have exactly 2 terms: ",
ProtobufShortDebugString(ct));
}
if (!ct.int_prod().has_target()) {
return absl::StrCat("An int_prod constraint should have a target: ",
ProtobufShortDebugString(ct));
}
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_prod().exprs(0)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_prod().exprs(1)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_prod().target()));
// Detect potential overflow if some of the variables span across 0.
const LinearExpressionProto& expr0 = ct.int_prod().exprs(0);
const LinearExpressionProto& expr1 = ct.int_prod().exprs(1);
const Domain product_domain =
Domain({MinOfExpression(model, expr0), MaxOfExpression(model, expr0)})
.ContinuousMultiplicationBy(Domain(
{MinOfExpression(model, expr1), MaxOfExpression(model, expr1)}));
if ((product_domain.Max() == std::numeric_limits<int64_t>::max() &&
product_domain.Min() < 0) ||
(product_domain.Min() == std::numeric_limits<int64_t>::min() &&
product_domain.Max() > 0)) {
return absl::StrCat("Potential integer overflow in constraint: ",
ProtobufShortDebugString(ct));
}
return "";
}
std::string ValidateIntDivConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.int_div().exprs().size() != 2) {
return absl::StrCat("An int_div constraint should have exactly 2 terms: ",
ProtobufShortDebugString(ct));
}
if (!ct.int_div().has_target()) {
return absl::StrCat("An int_div constraint should have a target: ",
ProtobufShortDebugString(ct));
}
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_div().exprs(0)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_div().exprs(1)));
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, ct.int_div().target()));
const LinearExpressionProto& divisor_proto = ct.int_div().exprs(1);
if (MinOfExpression(model, divisor_proto) <= 0 &&
MaxOfExpression(model, divisor_proto) >= 0) {
return absl::StrCat("The divisor cannot span across zero in constraint: ",
ProtobufShortDebugString(ct));
}
return "";
}
std::string ValidateTableConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
const TableConstraintProto& arg = ct.table();
if (arg.vars().empty()) return "";
if (arg.values().size() % arg.vars().size() != 0) {
return absl::StrCat(
"The flat encoding of a table constraint must be a multiple of the "
"number of variable: ",
ProtobufDebugString(ct));
}
return "";
}
std::string ValidateAutomatonConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
const int num_transistions = ct.automaton().transition_tail().size();
if (num_transistions != ct.automaton().transition_head().size() ||
num_transistions != ct.automaton().transition_label().size()) {
return absl::StrCat(
"The transitions repeated fields must have the same size: ",
ProtobufShortDebugString(ct));
}
absl::flat_hash_map<std::pair<int64_t, int64_t>, int64_t> tail_label_to_head;
for (int i = 0; i < num_transistions; ++i) {
const int64_t tail = ct.automaton().transition_tail(i);
const int64_t head = ct.automaton().transition_head(i);
const int64_t label = ct.automaton().transition_label(i);
const auto [it, inserted] =
tail_label_to_head.insert({{tail, label}, head});
if (!inserted) {
if (it->second == head) {
return absl::StrCat("automaton: duplicate transition ", tail, " --(",
label, ")--> ", head);
} else {
return absl::StrCat("automaton: incompatible transitions ", tail,
" --(", label, ")--> ", head, " and ", tail, " --(",
label, ")--> ", it->second);
}
}
}
return "";
}
template <typename GraphProto>
std::string ValidateGraphInput(bool is_route, const CpModelProto& model,
const GraphProto& graph) {
const int size = graph.tails().size();
if (graph.heads().size() != size || graph.literals().size() != size) {
return absl::StrCat("Wrong field sizes in graph: ",
ProtobufShortDebugString(graph));
}
// We currently disallow multiple self-loop on the same node.
absl::flat_hash_set<int> self_loops;
for (int i = 0; i < size; ++i) {
if (graph.heads(i) != graph.tails(i)) continue;
if (!self_loops.insert(graph.heads(i)).second) {
return absl::StrCat(
"Circuit/Route constraint contains multiple self-loop involving "
"node ",
graph.heads(i));
}
if (is_route && graph.tails(i) == 0) {
return absl::StrCat(
"A route constraint cannot have a self-loop on the depot (node 0)");
}
}
return "";
}
std::string ValidateRoutesConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
int max_node = 0;
absl::flat_hash_set<int> nodes;
for (const int node : ct.routes().tails()) {
if (node < 0) {
return "All node in a route constraint must be in [0, num_nodes)";
}
nodes.insert(node);
max_node = std::max(max_node, node);
}
for (const int node : ct.routes().heads()) {
if (node < 0) {
return "All node in a route constraint must be in [0, num_nodes)";
}
nodes.insert(node);
max_node = std::max(max_node, node);
}
if (!nodes.empty() && max_node != nodes.size() - 1) {
return absl::StrCat(
"All nodes in a route constraint must have incident arcs");
}
return ValidateGraphInput(/*is_route=*/true, model, ct.routes());
}
std::string ValidateDomainIsPositive(const CpModelProto& model, int ref,
const std::string& ref_name) {
if (ref < 0) {
const IntegerVariableProto& var_proto = model.variables(NegatedRef(ref));
if (var_proto.domain(var_proto.domain_size() - 1) > 0) {
return absl::StrCat("Negative value in ", ref_name,
" domain: negation of ",
ProtobufDebugString(var_proto));
}
} else {
const IntegerVariableProto& var_proto = model.variables(ref);
if (var_proto.domain(0) < 0) {
return absl::StrCat("Negative value in ", ref_name,
" domain: ", ProtobufDebugString(var_proto));
}
}
return "";
}
void AppendToOverflowValidator(const LinearExpressionProto& input,
LinearExpressionProto* output) {
output->mutable_vars()->Add(input.vars().begin(), input.vars().end());
output->mutable_coeffs()->Add(input.coeffs().begin(), input.coeffs().end());
// We add the absolute value to be sure that future computation will not
// overflow depending on the order they are performed in.
output->set_offset(
CapAdd(std::abs(output->offset()), std::abs(input.offset())));
}
std::string ValidateIntervalConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.enforcement_literal().size() > 1) {
return absl::StrCat(
"Interval with more than one enforcement literals are currently not "
"supported: ",
ProtobufShortDebugString(ct));
}
const IntervalConstraintProto& arg = ct.interval();
if (!arg.has_start()) {
return absl::StrCat("Interval must have a start expression: ",
ProtobufShortDebugString(ct));
}
if (!arg.has_size()) {
return absl::StrCat("Interval must have a size expression: ",
ProtobufShortDebugString(ct));
}
if (!arg.has_end()) {
return absl::StrCat("Interval must have a end expression: ",
ProtobufShortDebugString(ct));
}
LinearExpressionProto for_overflow_validation;
if (arg.start().vars_size() > 1) {
return "Interval with a start expression containing more than one "
"variable are currently not supported.";
}
RETURN_IF_NOT_EMPTY(ValidateLinearExpression(model, arg.start()));
AppendToOverflowValidator(arg.start(), &for_overflow_validation);
if (arg.size().vars_size() > 1) {
return "Interval with a size expression containing more than one "
"variable are currently not supported.";
}
RETURN_IF_NOT_EMPTY(ValidateLinearExpression(model, arg.size()));
if (ct.enforcement_literal().empty() &&
MinOfExpression(model, arg.size()) < 0) {
return absl::StrCat(
"The size of an performed interval must be >= 0 in constraint: ",
ProtobufDebugString(ct));
}
AppendToOverflowValidator(arg.size(), &for_overflow_validation);
if (arg.end().vars_size() > 1) {
return "Interval with a end expression containing more than one "
"variable are currently not supported.";
}
RETURN_IF_NOT_EMPTY(ValidateLinearExpression(model, arg.end()));
AppendToOverflowValidator(arg.end(), &for_overflow_validation);
if (PossibleIntegerOverflow(model, for_overflow_validation,
for_overflow_validation.offset())) {
return absl::StrCat("Possible overflow in interval: ",
ProtobufShortDebugString(ct.interval()));
}
return "";
}
std::string ValidateCumulativeConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.cumulative().intervals_size() != ct.cumulative().demands_size()) {
return absl::StrCat("intervals_size() != demands_size() in constraint: ",
ProtobufShortDebugString(ct));
}
RETURN_IF_NOT_EMPTY(
ValidateLinearExpression(model, ct.cumulative().capacity()));
for (const LinearExpressionProto& demand : ct.cumulative().demands()) {
RETURN_IF_NOT_EMPTY(ValidateLinearExpression(model, demand));
}
for (const LinearExpressionProto& demand_expr : ct.cumulative().demands()) {
if (MinOfExpression(model, demand_expr) < 0) {
return absl::StrCat(
"Demand ", demand_expr.DebugString(),
" must be positive in constraint: ", ProtobufDebugString(ct));
}
if (demand_expr.vars_size() > 1) {
return absl::StrCat("Demand ", demand_expr.DebugString(),
" must be affine or constant in constraint: ",
ProtobufDebugString(ct));
}
}
if (ct.cumulative().capacity().vars_size() > 1) {
return absl::StrCat(
"capacity ", ct.cumulative().capacity().DebugString(),
" must be affine or constant in constraint: ", ProtobufDebugString(ct));
}
int64_t sum_max_demands = 0;
for (const LinearExpressionProto& demand_expr : ct.cumulative().demands()) {
const int64_t demand_max = MaxOfExpression(model, demand_expr);
DCHECK_GE(demand_max, 0);
sum_max_demands = CapAdd(sum_max_demands, demand_max);
if (sum_max_demands == std::numeric_limits<int64_t>::max()) {
return "The sum of max demands do not fit on an int64_t in constraint: " +
ProtobufDebugString(ct);
}
}
return "";
}
std::string ValidateNoOverlap2DConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
const int size_x = ct.no_overlap_2d().x_intervals().size();
const int size_y = ct.no_overlap_2d().y_intervals().size();
if (size_x != size_y) {
return absl::StrCat("The two lists of intervals must have the same size: ",
ProtobufShortDebugString(ct));
}
// Checks if the sum of max areas of each rectangle can overflow.
int64_t sum_max_areas = 0;
for (int i = 0; i < ct.no_overlap_2d().x_intervals().size(); ++i) {
const int64_t max_size_x =
IntervalSizeMax(model, ct.no_overlap_2d().x_intervals(i));
const int64_t max_size_y =
IntervalSizeMax(model, ct.no_overlap_2d().y_intervals(i));
sum_max_areas = CapAdd(sum_max_areas, CapProd(max_size_x, max_size_y));
if (sum_max_areas == std::numeric_limits<int64_t>::max()) {
return "Integer overflow when summing all areas in "
"constraint: " +
ProtobufDebugString(ct);
}
}
return "";
}
std::string ValidateReservoirConstraint(const CpModelProto& model,
const ConstraintProto& ct) {
if (ct.enforcement_literal_size() > 0) {
return "Reservoir does not support enforcement literals.";
}
if (ct.reservoir().time_exprs().size() !=
ct.reservoir().level_changes().size()) {
return absl::StrCat(
"time_exprs and level_changes fields must be of the same size: ",
ProtobufShortDebugString(ct));
}
for (const LinearExpressionProto& expr : ct.reservoir().time_exprs()) {
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, expr));
}
if (ct.reservoir().min_level() > 0) {
return absl::StrCat(
"The min level of a reservoir must be <= 0. Please use fixed events to "
"setup initial state: ",
ProtobufShortDebugString(ct));
}
if (ct.reservoir().max_level() < 0) {
return absl::StrCat(
"The max level of a reservoir must be >= 0. Please use fixed events to "
"setup initial state: ",
ProtobufShortDebugString(ct));
}
int64_t sum_abs = 0;
for (const int64_t demand : ct.reservoir().level_changes()) {
// We test for min int64_t before the abs().
if (demand == std::numeric_limits<int64_t>::min()) {
return "Possible integer overflow in constraint: " +
ProtobufDebugString(ct);
}
sum_abs = CapAdd(sum_abs, std::abs(demand));
if (sum_abs == std::numeric_limits<int64_t>::max()) {
return "Possible integer overflow in constraint: " +
ProtobufDebugString(ct);
}
}
if (ct.reservoir().active_literals_size() > 0 &&
ct.reservoir().active_literals_size() !=
ct.reservoir().time_exprs_size()) {
return "Wrong array length of active_literals variables";
}
if (ct.reservoir().level_changes_size() > 0 &&
ct.reservoir().level_changes_size() != ct.reservoir().time_exprs_size()) {
return "Wrong array length of level_changes variables";
}
return "";
}
std::string ValidateObjective(const CpModelProto& model,
const CpObjectiveProto& obj) {
if (!DomainInProtoIsValid(obj)) {
return absl::StrCat("The objective has and invalid domain() format: ",
ProtobufShortDebugString(obj));
}
if (obj.vars().size() != obj.coeffs().size()) {
return absl::StrCat("vars and coeffs size do not match in objective: ",
ProtobufShortDebugString(obj));
}
for (const int v : obj.vars()) {
if (!VariableReferenceIsValid(model, v)) {
return absl::StrCat("Out of bound integer variable ", v,
" in objective: ", ProtobufShortDebugString(obj));
}
}
if (PossibleIntegerOverflow(model, obj)) {
return "Possible integer overflow in objective: " +
ProtobufDebugString(obj);
}
return "";
}
std::string ValidateFloatingPointObjective(const CpModelProto& model,
const FloatObjectiveProto& obj) {
if (obj.vars().size() != obj.coeffs().size()) {
return absl::StrCat("vars and coeffs size do not match in objective: ",
ProtobufShortDebugString(obj));
}
for (const int v : obj.vars()) {
if (!VariableIndexIsValid(model, v)) {
return absl::StrCat("Out of bound integer variable ", v,
" in objective: ", ProtobufShortDebugString(obj));
}
}
for (const double coef : obj.coeffs()) {
if (!std::isfinite(coef)) {
return absl::StrCat("Coefficients must be finites in objective: ",
ProtobufShortDebugString(obj));
}
}
if (!std::isfinite(obj.offset())) {
return absl::StrCat("Offset must be finite in objective: ",
ProtobufShortDebugString(obj));
}
return "";
}
std::string ValidateSearchStrategies(const CpModelProto& model) {
for (const DecisionStrategyProto& strategy : model.search_strategy()) {
const int vss = strategy.variable_selection_strategy();
if (vss != DecisionStrategyProto::CHOOSE_FIRST &&
vss != DecisionStrategyProto::CHOOSE_LOWEST_MIN &&
vss != DecisionStrategyProto::CHOOSE_HIGHEST_MAX &&
vss != DecisionStrategyProto::CHOOSE_MIN_DOMAIN_SIZE &&
vss != DecisionStrategyProto::CHOOSE_MAX_DOMAIN_SIZE) {
return absl::StrCat(
"Unknown or unsupported variable_selection_strategy: ", vss);
}
const int drs = strategy.domain_reduction_strategy();
if (drs != DecisionStrategyProto::SELECT_MIN_VALUE &&
drs != DecisionStrategyProto::SELECT_MAX_VALUE &&
drs != DecisionStrategyProto::SELECT_LOWER_HALF &&
drs != DecisionStrategyProto::SELECT_UPPER_HALF &&
drs != DecisionStrategyProto::SELECT_MEDIAN_VALUE) {
return absl::StrCat("Unknown or unsupported domain_reduction_strategy: ",
drs);
}
for (const int ref : strategy.variables()) {
if (!VariableReferenceIsValid(model, ref)) {
return absl::StrCat("Invalid variable reference in strategy: ",
ProtobufShortDebugString(strategy));
}
if (drs == DecisionStrategyProto::SELECT_MEDIAN_VALUE &&
ReadDomainFromProto(model.variables(PositiveRef(ref))).Size() >
100000) {
return absl::StrCat("Variable #", PositiveRef(ref),
" has a domain too large to be used in a"
" SELECT_MEDIAN_VALUE value selection strategy");
}
}
int previous_index = -1;
for (const auto& transformation : strategy.transformations()) {
if (transformation.positive_coeff() <= 0) {
return absl::StrCat("Affine transformation coeff should be positive: ",
ProtobufShortDebugString(transformation));
}
if (transformation.index() <= previous_index ||
transformation.index() >= strategy.variables_size()) {
return absl::StrCat(
"Invalid indices (must be sorted and valid) in transformation: ",
ProtobufShortDebugString(transformation));
}
previous_index = transformation.index();
}
}
return "";
}
std::string ValidateSolutionHint(const CpModelProto& model) {
if (!model.has_solution_hint()) return "";
const auto& hint = model.solution_hint();
if (hint.vars().size() != hint.values().size()) {
return "Invalid solution hint: vars and values do not have the same size.";
}
for (const int ref : hint.vars()) {
if (!VariableReferenceIsValid(model, ref)) {
return absl::StrCat("Invalid variable reference in solution hint: ", ref);
}
}
// Reject hints with duplicate variables as this is likely a user error.
absl::flat_hash_set<int> indices;
for (const int var : hint.vars()) {
const auto insert = indices.insert(PositiveRef(var));
if (!insert.second) {
return absl::StrCat(
"The solution hint contains duplicate variables like the variable "
"with index #",
PositiveRef(var));
}
}
// Reject hints equals to INT_MIN or INT_MAX.
for (const int64_t value : hint.values()) {
if (value == std::numeric_limits<int64_t>::min() ||
value == std::numeric_limits<int64_t>::max()) {
return "The solution hint cannot contains the INT_MIN or INT_MAX values.";
}
}
return "";
}
} // namespace
std::string ValidateCpModel(const CpModelProto& model) {
for (int v = 0; v < model.variables_size(); ++v) {
RETURN_IF_NOT_EMPTY(ValidateIntegerVariable(model, v));
}
// Checks all variable references, and validate intervals before scanning the
// rest of the constraints.
for (int c = 0; c < model.constraints_size(); ++c) {
RETURN_IF_NOT_EMPTY(ValidateArgumentReferencesInConstraint(model, c));
const ConstraintProto& ct = model.constraints(c);
if (ct.constraint_case() == ConstraintProto::kInterval) {
RETURN_IF_NOT_EMPTY(ValidateIntervalConstraint(model, ct));
}
}
for (int c = 0; c < model.constraints_size(); ++c) {
// By default, a constraint does not support enforcement literals except if
// explicitly stated by setting this to true below.
bool support_enforcement = false;
// Other non-generic validations.
// TODO(user): validate all constraints.
const ConstraintProto& ct = model.constraints(c);
const ConstraintProto::ConstraintCase type = ct.constraint_case();
switch (type) {
case ConstraintProto::ConstraintCase::kBoolOr:
support_enforcement = true;
break;
case ConstraintProto::ConstraintCase::kBoolAnd:
support_enforcement = true;
break;
case ConstraintProto::ConstraintCase::kLinear:
support_enforcement = true;
RETURN_IF_NOT_EMPTY(ValidateLinearConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kLinMax: {
RETURN_IF_NOT_EMPTY(
ValidateLinearExpression(model, ct.lin_max().target()));
for (const LinearExpressionProto& expr : ct.lin_max().exprs()) {
RETURN_IF_NOT_EMPTY(ValidateLinearExpression(model, expr));
}
break;
}
case ConstraintProto::ConstraintCase::kIntProd:
RETURN_IF_NOT_EMPTY(ValidateIntProdConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kIntDiv:
RETURN_IF_NOT_EMPTY(ValidateIntDivConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kIntMod:
RETURN_IF_NOT_EMPTY(ValidateIntModConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kInverse:
if (ct.inverse().f_direct().size() != ct.inverse().f_inverse().size()) {
return absl::StrCat("Non-matching fields size in inverse: ",
ProtobufShortDebugString(ct));
}
break;
case ConstraintProto::ConstraintCase::kAllDiff:
for (const LinearExpressionProto& expr : ct.all_diff().exprs()) {
RETURN_IF_NOT_EMPTY(ValidateAffineExpression(model, expr));
}
break;
case ConstraintProto::ConstraintCase::kTable:
RETURN_IF_NOT_EMPTY(ValidateTableConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kAutomaton:
RETURN_IF_NOT_EMPTY(ValidateAutomatonConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kCircuit:
RETURN_IF_NOT_EMPTY(
ValidateGraphInput(/*is_route=*/false, model, ct.circuit()));
break;
case ConstraintProto::ConstraintCase::kRoutes:
RETURN_IF_NOT_EMPTY(ValidateRoutesConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kInterval:
support_enforcement = true;
break;
case ConstraintProto::ConstraintCase::kCumulative:
RETURN_IF_NOT_EMPTY(ValidateCumulativeConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kNoOverlap2D:
RETURN_IF_NOT_EMPTY(ValidateNoOverlap2DConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kReservoir:
RETURN_IF_NOT_EMPTY(ValidateReservoirConstraint(model, ct));
break;
case ConstraintProto::ConstraintCase::kDummyConstraint:
return "The dummy constraint should never appear in a model.";
default:
break;
}
// Because some client set fixed enforcement literal which are supported
// in the presolve for all constraints, we just check that there is no
// non-fixed enforcement.
if (!support_enforcement && !ct.enforcement_literal().empty()) {
for (const int ref : ct.enforcement_literal()) {
const int var = PositiveRef(ref);
const Domain domain = ReadDomainFromProto(model.variables(var));
if (domain.Size() != 1) {
return absl::StrCat(
"Enforcement literal not supported in constraint: ",
ProtobufShortDebugString(ct));
}
}
}
}
if (model.has_objective() && model.has_floating_point_objective()) {
return "A model cannot have both an objective and a floating point "
"objective.";
}
if (model.has_objective()) {
RETURN_IF_NOT_EMPTY(ValidateObjective(model, model.objective()));
}
if (model.has_floating_point_objective()) {
RETURN_IF_NOT_EMPTY(ValidateFloatingPointObjective(
model, model.floating_point_objective()));
}
RETURN_IF_NOT_EMPTY(ValidateSearchStrategies(model));
RETURN_IF_NOT_EMPTY(ValidateSolutionHint(model));
for (const int ref : model.assumptions()) {
if (!LiteralReferenceIsValid(model, ref)) {
return absl::StrCat("Invalid literal reference ", ref,
" in the 'assumptions' field.");
}
}
return "";
}
#undef RETURN_IF_NOT_EMPTY
// =============================================================================
// Solution Feasibility.
// =============================================================================
namespace {
class ConstraintChecker {
public:
explicit ConstraintChecker(const std::vector<int64_t>& variable_values)
: variable_values_(variable_values) {}
bool LiteralIsTrue(int l) const {
if (l >= 0) return variable_values_[l] != 0;
return variable_values_[-l - 1] == 0;
}
bool LiteralIsFalse(int l) const { return !LiteralIsTrue(l); }
int64_t Value(int var) const {
if (var >= 0) return variable_values_[var];
return -variable_values_[-var - 1];
}
bool ConstraintIsEnforced(const ConstraintProto& ct) {
for (const int lit : ct.enforcement_literal()) {
if (LiteralIsFalse(lit)) return false;
}
return true;
}
bool BoolOrConstraintIsFeasible(const ConstraintProto& ct) {
for (const int lit : ct.bool_or().literals()) {
if (LiteralIsTrue(lit)) return true;