Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cp_model.cc
Go to the documentation of this file.
1// Copyright 2010-2024 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 <cstdint>
17#include <initializer_list>
18#include <limits>
19#include <ostream>
20#include <string>
21#include <vector>
22
23#include "absl/container/flat_hash_map.h"
24#include "absl/log/check.h"
25#include "absl/strings/str_cat.h"
26#include "absl/strings/str_format.h"
27#include "absl/strings/string_view.h"
28#include "absl/types/span.h"
29#include "ortools/sat/cp_model.pb.h"
32
33namespace operations_research {
34namespace sat {
35
36BoolVar::BoolVar(int index, CpModelBuilder* builder)
37 : builder_(builder), index_(index) {}
38
39BoolVar BoolVar::WithName(absl::string_view name) {
40 DCHECK(builder_ != nullptr);
41 if (builder_ == nullptr) return *this;
42 builder_->MutableProto()
43 ->mutable_variables(PositiveRef(index_))
44 ->set_name(name);
45 return *this;
46}
47
48std::string BoolVar::Name() const {
49 if (builder_ == nullptr) return "null";
50 const std::string& name =
51 builder_->Proto().variables(PositiveRef(index_)).name();
52 if (RefIsPositive(index_)) {
53 return name;
54 } else {
55 return absl::StrCat("Not(", name, ")");
56 }
57}
58
59std::string BoolVar::DebugString() const {
60 if (builder_ == nullptr) return "null";
61 if (index_ < 0) {
62 return absl::StrFormat("Not(%s)", Not().DebugString());
63 } else {
64 std::string output;
65 const IntegerVariableProto& var_proto = builder_->Proto().variables(index_);
66 // Special case for constant variables without names.
67 if (var_proto.name().empty() && var_proto.domain_size() == 2 &&
68 var_proto.domain(0) == var_proto.domain(1)) {
69 output.append(var_proto.domain(0) == 0 ? "false" : "true");
70 } else {
71 if (var_proto.name().empty()) {
72 absl::StrAppendFormat(&output, "BoolVar%i(", index_);
73 } else {
74 absl::StrAppendFormat(&output, "%s(", var_proto.name());
75 }
76 if (var_proto.domain(0) == var_proto.domain(1)) {
77 output.append(var_proto.domain(0) == 0 ? "false)" : "true)");
78 } else {
79 absl::StrAppend(&output, var_proto.domain(0), ", ", var_proto.domain(1),
80 ")");
81 }
82 }
83 return output;
84 }
85}
86
87BoolVar Not(BoolVar x) { return x.Not(); }
88
89std::ostream& operator<<(std::ostream& os, const BoolVar& var) {
90 os << var.DebugString();
91 return os;
92}
93
94IntVar::IntVar(int index, CpModelBuilder* builder)
95 : builder_(builder), index_(index) {
96 DCHECK(RefIsPositive(index_));
97}
98
100 if (var.builder_ == nullptr) {
101 *this = IntVar();
102 return;
103 }
104 builder_ = var.builder_;
105 index_ = builder_->GetOrCreateIntegerIndex(var.index_);
106 DCHECK(RefIsPositive(index_));
107}
108
109BoolVar IntVar::ToBoolVar() const {
110 if (builder_ != nullptr) {
111 const IntegerVariableProto& proto = builder_->Proto().variables(index_);
112 DCHECK_EQ(2, proto.domain_size());
113 DCHECK_GE(proto.domain(0), 0);
114 DCHECK_LE(proto.domain(1), 1);
115 }
116 return BoolVar(index_, builder_);
117}
118
119IntVar IntVar::WithName(absl::string_view name) {
120 DCHECK(builder_ != nullptr);
121 if (builder_ == nullptr) return *this;
122 builder_->MutableProto()->mutable_variables(index_)->set_name(name);
123 return *this;
124}
125
126std::string IntVar::Name() const {
127 if (builder_ == nullptr) return "null";
128 return builder_->Proto().variables(index_).name();
129}
130
131::operations_research::Domain IntVar::Domain() const {
132 if (builder_ == nullptr) return Domain();
133 return ReadDomainFromProto(builder_->Proto().variables(index_));
134}
135
136std::string IntVar::DebugString() const {
137 if (builder_ == nullptr) return "null";
138 return VarDebugString(builder_->Proto(), index_);
139}
140
141// TODO(user): unfortunately, we need this indirection to get a DebugString()
142// in a const way from an index. Because building an IntVar is non-const.
143std::string VarDebugString(const CpModelProto& proto, int index) {
144 std::string output;
145
146 // Special case for constant variables without names.
147 const IntegerVariableProto& var_proto = proto.variables(index);
148 if (var_proto.name().empty() && var_proto.domain_size() == 2 &&
149 var_proto.domain(0) == var_proto.domain(1)) {
150 absl::StrAppend(&output, var_proto.domain(0));
151 } else {
152 if (var_proto.name().empty()) {
153 absl::StrAppend(&output, "V", index, "(");
154 } else {
155 absl::StrAppend(&output, var_proto.name(), "(");
156 }
157
158 // TODO(user): Use domain pretty print function.
159 if (var_proto.domain_size() == 2 &&
160 var_proto.domain(0) == var_proto.domain(1)) {
161 absl::StrAppend(&output, var_proto.domain(0), ")");
162 } else {
163 absl::StrAppend(&output, var_proto.domain(0), ", ", var_proto.domain(1),
164 ")");
165 }
166 }
167
168 return output;
169}
170
171std::ostream& operator<<(std::ostream& os, const IntVar& var) {
172 os << var.DebugString();
173 return os;
174}
175
177 DCHECK(var.builder_ != nullptr);
178 const int index = var.index_;
179 if (RefIsPositive(index)) {
180 variables_.push_back(index);
181 coefficients_.push_back(1);
182 } else {
183 // We add 1 - var instead.
184 variables_.push_back(PositiveRef(index));
185 coefficients_.push_back(-1);
186 constant_ += 1;
187 }
188}
189
191 DCHECK(var.builder_ != nullptr);
192 variables_.push_back(var.index_);
193 coefficients_.push_back(1);
194}
195
196LinearExpr::LinearExpr(int64_t constant) { constant_ = constant; }
197
198LinearExpr LinearExpr::FromProto(const LinearExpressionProto& expr_proto) {
199 LinearExpr result(expr_proto.offset());
200 for (int i = 0; i < expr_proto.vars_size(); ++i) {
201 result.variables_.push_back(expr_proto.vars(i));
202 result.coefficients_.push_back(expr_proto.coeffs(i));
203 }
204 return result;
205}
206
207LinearExpr LinearExpr::Sum(absl::Span<const IntVar> vars) {
208 LinearExpr result;
209 for (const IntVar& var : vars) {
210 result += var;
211 }
212 return result;
213}
214
215LinearExpr LinearExpr::Sum(absl::Span<const BoolVar> vars) {
216 LinearExpr result;
217 for (const BoolVar& var : vars) {
218 result += var;
219 }
220 return result;
221}
222
223LinearExpr LinearExpr::WeightedSum(absl::Span<const IntVar> vars,
224 absl::Span<const int64_t> coeffs) {
225 CHECK_EQ(vars.size(), coeffs.size());
226 LinearExpr result;
227 for (int i = 0; i < vars.size(); ++i) {
228 result += vars[i] * coeffs[i];
229 }
230 return result;
231}
232
233LinearExpr LinearExpr::WeightedSum(absl::Span<const BoolVar> vars,
234 absl::Span<const int64_t> coeffs) {
235 CHECK_EQ(vars.size(), coeffs.size());
236 LinearExpr result;
237 for (int i = 0; i < vars.size(); ++i) {
238 result += vars[i] * coeffs[i];
239 }
240 return result;
241}
242
243LinearExpr LinearExpr::Term(IntVar var, int64_t coefficient) {
244 LinearExpr result;
245 result += var * coefficient;
246 return result;
247}
248
249LinearExpr LinearExpr::Term(BoolVar var, int64_t coefficient) {
250 LinearExpr result;
251 result += var * coefficient;
252 return result;
253}
254
256 constant_ += other.constant_;
257 variables_.insert(variables_.end(), other.variables_.begin(),
258 other.variables_.end());
259 coefficients_.insert(coefficients_.end(), other.coefficients_.begin(),
260 other.coefficients_.end());
261 return *this;
262}
263
265 constant_ -= other.constant_;
266 variables_.insert(variables_.end(), other.variables_.begin(),
267 other.variables_.end());
268 for (const int64_t coeff : other.coefficients_) {
269 coefficients_.push_back(-coeff);
270 }
271 return *this;
272}
273
275 constant_ *= factor;
276 for (int64_t& coeff : coefficients_) coeff *= factor;
277 return *this;
278}
279
280std::string LinearExpr::DebugString(const CpModelProto* proto) const {
281 std::string result;
282 for (int i = 0; i < variables_.size(); ++i) {
283 const int64_t coeff = coefficients_[i];
284 const std::string var_string = proto == nullptr
285 ? absl::StrCat("V", variables_[i])
286 : VarDebugString(*proto, variables_[i]);
287 if (i == 0) {
288 if (coeff == 1) {
289 absl::StrAppend(&result, var_string);
290 } else if (coeff == -1) {
291 absl::StrAppend(&result, "-", var_string);
292 } else if (coeff != 0) {
293 absl::StrAppend(&result, coeff, " * ", var_string);
294 }
295 } else if (coeff == 1) {
296 absl::StrAppend(&result, " + ", var_string);
297 } else if (coeff > 0) {
298 absl::StrAppend(&result, " + ", coeff, " * ", var_string);
299 } else if (coeff == -1) {
300 absl::StrAppend(&result, " - ", var_string);
301 } else if (coeff < 0) {
302 absl::StrAppend(&result, " - ", -coeff, " * ", var_string);
303 }
304 }
305
306 if (constant_ != 0) {
307 if (variables_.empty()) {
308 return absl::StrCat(constant_);
309 } else if (constant_ > 0) {
310 absl::StrAppend(&result, " + ", constant_);
311 } else {
312 absl::StrAppend(&result, " - ", -constant_);
313 }
314 }
315 return result;
316}
317
318std::ostream& operator<<(std::ostream& os, const LinearExpr& e) {
319 os << e.DebugString();
320 return os;
321}
322
323DoubleLinearExpr::DoubleLinearExpr() = default;
324
325DoubleLinearExpr::DoubleLinearExpr(BoolVar var) { AddTerm(var, 1); }
326
327DoubleLinearExpr::DoubleLinearExpr(IntVar var) { AddTerm(var, 1); }
328
329DoubleLinearExpr::DoubleLinearExpr(double constant) { constant_ = constant; }
330
331DoubleLinearExpr DoubleLinearExpr::Sum(absl::Span<const IntVar> vars) {
332 DoubleLinearExpr result;
333 for (const IntVar& var : vars) {
334 result.AddTerm(var, 1.0);
335 }
336 return result;
337}
338
339DoubleLinearExpr DoubleLinearExpr::Sum(absl::Span<const BoolVar> vars) {
340 DoubleLinearExpr result;
341 for (const BoolVar& var : vars) {
342 result.AddTerm(var, 1.0);
343 }
344 return result;
345}
346
347DoubleLinearExpr DoubleLinearExpr::WeightedSum(
348 absl::Span<const IntVar> vars, absl::Span<const double> coeffs) {
349 CHECK_EQ(vars.size(), coeffs.size());
350 DoubleLinearExpr result;
351 for (int i = 0; i < vars.size(); ++i) {
352 result.AddTerm(vars[i], coeffs[i]);
353 }
354 return result;
355}
356
357DoubleLinearExpr DoubleLinearExpr::WeightedSum(
358 absl::Span<const BoolVar> vars, absl::Span<const double> coeffs) {
359 CHECK_EQ(vars.size(), coeffs.size());
360 DoubleLinearExpr result;
361 for (int i = 0; i < vars.size(); ++i) {
362 result.AddTerm(vars[i], coeffs[i]);
363 }
364 return result;
365}
366
367DoubleLinearExpr& DoubleLinearExpr::operator+=(double value) {
368 constant_ += value;
369 return *this;
370}
371
372DoubleLinearExpr& DoubleLinearExpr::operator+=(IntVar var) {
373 AddTerm(var, 1);
374 return *this;
375}
376
377DoubleLinearExpr& DoubleLinearExpr::operator+=(BoolVar var) {
378 AddTerm(var, 1);
379 return *this;
380}
381
382DoubleLinearExpr& DoubleLinearExpr::operator+=(const DoubleLinearExpr& expr) {
383 constant_ += expr.constant_;
384 variables_.insert(variables_.end(), expr.variables_.begin(),
385 expr.variables_.end());
386 coefficients_.insert(coefficients_.end(), expr.coefficients_.begin(),
387 expr.coefficients_.end());
388 return *this;
389}
390
391DoubleLinearExpr& DoubleLinearExpr::AddTerm(IntVar var, double coeff) {
392 variables_.push_back(var.index_);
393 coefficients_.push_back(coeff);
394 return *this;
395}
396
397DoubleLinearExpr& DoubleLinearExpr::AddTerm(BoolVar var, double coeff) {
398 const int index = var.index_;
399 if (RefIsPositive(index)) {
400 variables_.push_back(index);
401 coefficients_.push_back(coeff);
402 } else {
403 variables_.push_back(PositiveRef(index));
404 coefficients_.push_back(-coeff);
405 constant_ += coeff;
406 }
407 return *this;
408}
409
410DoubleLinearExpr& DoubleLinearExpr::AddExpression(const LinearExpr& expr,
411 double coeff) {
412 const std::vector<int>& indices = expr.variables();
413 const std::vector<int64_t> coefficients = expr.coefficients();
414 for (int i = 0; i < indices.size(); ++i) {
415 variables_.push_back(indices[i]);
416 coefficients_.push_back(1.0 * static_cast<double>(coefficients[i]) * coeff);
417 }
418
419 return *this;
420}
421
422DoubleLinearExpr& DoubleLinearExpr::operator-=(double value) {
423 constant_ -= value;
424 return *this;
425}
426
427DoubleLinearExpr& DoubleLinearExpr::operator-=(IntVar var) {
428 AddTerm(var, -1.0);
429 return *this;
430}
431
432DoubleLinearExpr& DoubleLinearExpr::operator-=(const DoubleLinearExpr& expr) {
433 constant_ -= expr.constant_;
434 variables_.insert(variables_.end(), expr.variables_.begin(),
435 expr.variables_.end());
436 for (const double coeff : expr.coefficients()) {
437 coefficients_.push_back(-coeff);
438 }
439 return *this;
440}
441
442DoubleLinearExpr& DoubleLinearExpr::operator*=(double coeff) {
443 constant_ *= coeff;
444 for (double& c : coefficients_) {
445 c *= coeff;
446 }
447 return *this;
448}
449
450std::string DoubleLinearExpr::DebugString(const CpModelProto* proto) const {
451 std::string result;
452 for (int i = 0; i < variables_.size(); ++i) {
453 const double coeff = coefficients_[i];
454 const std::string var_string = proto == nullptr
455 ? absl::StrCat("V", variables_[i])
456 : VarDebugString(*proto, variables_[i]);
457 if (i == 0) {
458 if (coeff == 1.0) {
459 absl::StrAppend(&result, var_string);
460 } else if (coeff == -1.0) {
461 absl::StrAppend(&result, "-", var_string);
462 } else if (coeff != 0.0) {
463 absl::StrAppend(&result, coeff, " * ", var_string);
464 }
465 } else if (coeff == 1.0) {
466 absl::StrAppend(&result, " + ", var_string);
467 } else if (coeff > 0.0) {
468 absl::StrAppend(&result, " + ", coeff, " * ", var_string);
469 } else if (coeff == -1.0) {
470 absl::StrAppend(&result, " - ", var_string);
471 } else if (coeff < 0.0) {
472 absl::StrAppend(&result, " - ", -coeff, " * ", var_string);
473 }
474 }
475
476 if (constant_ != 0.0) {
477 if (variables_.empty()) {
478 return absl::StrCat(constant_);
479 } else if (constant_ > 0.0) {
480 absl::StrAppend(&result, " + ", constant_);
481 } else {
482 absl::StrAppend(&result, " - ", -constant_);
483 }
484 }
485 return result;
486}
487
488std::ostream& operator<<(std::ostream& os, const DoubleLinearExpr& e) {
489 os << e.DebugString();
490 return os;
491}
492
493Constraint::Constraint(ConstraintProto* proto) : proto_(proto) {}
494
496 proto_->set_name(name);
497 return *this;
498}
499
500absl::string_view Constraint::Name() const { return proto_->name(); }
501
502Constraint Constraint::OnlyEnforceIf(absl::Span<const BoolVar> literals) {
503 for (const BoolVar& var : literals) {
504 proto_->add_enforcement_literal(var.index_);
505 }
506 return *this;
507}
508
510 proto_->add_enforcement_literal(literal.index_);
511 return *this;
512}
513
515 proto_->mutable_circuit()->add_tails(tail);
516 proto_->mutable_circuit()->add_heads(head);
517 proto_->mutable_circuit()->add_literals(literal.index_);
518}
519
521 proto_->mutable_routes()->add_tails(tail);
522 proto_->mutable_routes()->add_heads(head);
523 proto_->mutable_routes()->add_literals(literal.index_);
524}
525
526void TableConstraint::AddTuple(absl::Span<const int64_t> tuple) {
527 CHECK_EQ(tuple.size(), proto_->table().vars_size());
528 for (const int64_t t : tuple) {
529 proto_->mutable_table()->add_values(t);
530 }
531}
532
533ReservoirConstraint::ReservoirConstraint(ConstraintProto* proto,
534 CpModelBuilder* builder)
535 : Constraint(proto), builder_(builder) {}
536
537void ReservoirConstraint::AddEvent(LinearExpr time, int64_t level_change) {
538 *proto_->mutable_reservoir()->add_time_exprs() =
539 builder_->LinearExprToProto(time);
540 proto_->mutable_reservoir()->add_level_changes()->set_offset(level_change);
541 proto_->mutable_reservoir()->add_active_literals(
542 builder_->IndexFromConstant(1));
543}
544
546 int64_t level_change,
547 BoolVar is_active) {
548 *proto_->mutable_reservoir()->add_time_exprs() =
549 builder_->LinearExprToProto(time);
550 proto_->mutable_reservoir()->add_level_changes()->set_offset(level_change);
551 proto_->mutable_reservoir()->add_active_literals(is_active.index_);
552}
553
555 int64_t transition_label) {
556 proto_->mutable_automaton()->add_transition_tail(tail);
557 proto_->mutable_automaton()->add_transition_head(head);
558 proto_->mutable_automaton()->add_transition_label(transition_label);
559}
560
562 IntervalVar y_coordinate) {
563 proto_->mutable_no_overlap_2d()->add_x_intervals(x_coordinate.index_);
564 proto_->mutable_no_overlap_2d()->add_y_intervals(y_coordinate.index_);
565}
566
567CumulativeConstraint::CumulativeConstraint(ConstraintProto* proto,
568 CpModelBuilder* builder)
569 : Constraint(proto), builder_(builder) {}
570
572 proto_->mutable_cumulative()->add_intervals(interval.index_);
573 *proto_->mutable_cumulative()->add_demands() =
574 builder_->LinearExprToProto(demand);
575}
576
577IntervalVar::IntervalVar() : builder_(nullptr), index_() {}
578
580 : builder_(builder), index_(index) {}
581
583 DCHECK(builder_ != nullptr);
584 if (builder_ == nullptr) return *this;
585 builder_->MutableProto()->mutable_constraints(index_)->set_name(name);
586 return *this;
587}
588
590 DCHECK(builder_ != nullptr);
591 if (builder_ == nullptr) return LinearExpr();
593 builder_->Proto().constraints(index_).interval().start());
594}
595
597 DCHECK(builder_ != nullptr);
598 if (builder_ == nullptr) return LinearExpr();
600 builder_->Proto().constraints(index_).interval().size());
601}
602
604 DCHECK(builder_ != nullptr);
605 if (builder_ == nullptr) return LinearExpr();
607 builder_->Proto().constraints(index_).interval().end());
608}
609
611 DCHECK(builder_ != nullptr);
612 if (builder_ == nullptr) return BoolVar();
613 return BoolVar(builder_->Proto().constraints(index_).enforcement_literal(0),
614 builder_);
615}
616
617std::string IntervalVar::Name() const {
618 if (builder_ == nullptr) return "null";
619 return builder_->Proto().constraints(index_).name();
620}
621
622std::string IntervalVar::DebugString() const {
623 if (builder_ == nullptr) return "null";
624
625 CHECK_GE(index_, 0);
626 const CpModelProto& proto = builder_->Proto();
627 const ConstraintProto& ct_proto = proto.constraints(index_);
628 std::string output;
629 if (ct_proto.name().empty()) {
630 absl::StrAppend(&output, "IntervalVar", index_, "(");
631 } else {
632 absl::StrAppend(&output, ct_proto.name(), "(");
633 }
634 absl::StrAppend(&output, StartExpr().DebugString(&proto), ", ",
635 SizeExpr().DebugString(&proto), ", ",
636 EndExpr().DebugString(&proto), ", ",
638 return output;
639}
640
641std::ostream& operator<<(std::ostream& os, const IntervalVar& var) {
642 os << var.DebugString();
643 return os;
644}
645
646void CpModelBuilder::SetName(absl::string_view name) {
647 cp_model_.set_name(name);
648}
649
650int CpModelBuilder::IndexFromConstant(int64_t value) {
651 if (!constant_to_index_map_.contains(value)) {
652 const int index = cp_model_.variables_size();
653 IntegerVariableProto* const var_proto = cp_model_.add_variables();
654 var_proto->add_domain(value);
655 var_proto->add_domain(value);
656 constant_to_index_map_[value] = index;
657 }
658 return constant_to_index_map_[value];
659}
660
661int CpModelBuilder::GetOrCreateIntegerIndex(int index) {
662 if (index >= 0) {
663 return index;
664 }
665 if (!bool_to_integer_index_map_.contains(index)) {
666 const int var = PositiveRef(index);
667 const IntegerVariableProto& old_var = cp_model_.variables(var);
668 const int new_index = cp_model_.variables_size();
669 IntegerVariableProto* const new_var = cp_model_.add_variables();
670 new_var->add_domain(0);
671 new_var->add_domain(1);
672 if (!old_var.name().empty()) {
673 new_var->set_name(absl::StrCat("Not(", old_var.name(), ")"));
674 }
675 AddEquality(IntVar(new_index, this), BoolVar(index, this));
676 bool_to_integer_index_map_[index] = new_index;
677 return new_index;
678 }
679 return bool_to_integer_index_map_[index];
680}
681
683 const int index = cp_model_.variables_size();
684 IntegerVariableProto* const var_proto = cp_model_.add_variables();
685 for (const auto& interval : domain) {
686 var_proto->add_domain(interval.start);
687 var_proto->add_domain(interval.end);
688 }
689 return IntVar(index, this);
690}
691
693 const int index = cp_model_.variables_size();
694 IntegerVariableProto* const var_proto = cp_model_.add_variables();
695 var_proto->add_domain(0);
696 var_proto->add_domain(1);
697 return BoolVar(index, this);
698}
699
701 return IntVar(IndexFromConstant(value), this);
702}
703
705 return BoolVar(IndexFromConstant(1), this);
706}
707
709 return BoolVar(IndexFromConstant(0), this);
710}
711
717
722
724 const LinearExpr& size,
725 const LinearExpr& end,
726 BoolVar presence) {
727 const int index = cp_model_.constraints_size();
728 ConstraintProto* const ct = cp_model_.add_constraints();
729 ct->add_enforcement_literal(presence.index_);
730 IntervalConstraintProto* const interval = ct->mutable_interval();
731 *interval->mutable_start() = LinearExprToProto(start);
732 *interval->mutable_size() = LinearExprToProto(size);
733 *interval->mutable_end() = LinearExprToProto(end);
734 return IntervalVar(index, this);
735}
736
738 const LinearExpr& start, int64_t size, BoolVar presence) {
739 const int index = cp_model_.constraints_size();
740 ConstraintProto* const ct = cp_model_.add_constraints();
741 ct->add_enforcement_literal(presence.index_);
742 IntervalConstraintProto* const interval = ct->mutable_interval();
743 *interval->mutable_start() = LinearExprToProto(start);
744 interval->mutable_size()->set_offset(size);
745 *interval->mutable_end() = LinearExprToProto(start);
746 interval->mutable_end()->set_offset(interval->end().offset() + size);
747 return IntervalVar(index, this);
748}
749
751 FillDomainInProto(Domain(value), cp_model_.mutable_variables(var.index()));
752}
753
755 const int index = var.index();
756 if (RefIsPositive(index)) {
757 FillDomainInProto(Domain(value), cp_model_.mutable_variables(index));
758 } else {
760 cp_model_.mutable_variables(NegatedRef(index)));
761 }
762}
763
764Constraint CpModelBuilder::AddBoolOr(absl::Span<const BoolVar> literals) {
765 ConstraintProto* const proto = cp_model_.add_constraints();
766 for (const BoolVar& lit : literals) {
767 proto->mutable_bool_or()->add_literals(lit.index_);
768 }
769 return Constraint(proto);
770}
771
772Constraint CpModelBuilder::AddAtLeastOne(absl::Span<const BoolVar> literals) {
773 return AddBoolOr(literals);
774}
775
776Constraint CpModelBuilder::AddAtMostOne(absl::Span<const BoolVar> literals) {
777 ConstraintProto* const proto = cp_model_.add_constraints();
778 for (const BoolVar& lit : literals) {
779 proto->mutable_at_most_one()->add_literals(lit.index_);
780 }
781 return Constraint(proto);
782}
783
784Constraint CpModelBuilder::AddExactlyOne(absl::Span<const BoolVar> literals) {
785 ConstraintProto* const proto = cp_model_.add_constraints();
786 for (const BoolVar& lit : literals) {
787 proto->mutable_exactly_one()->add_literals(lit.index_);
788 }
789 return Constraint(proto);
790}
791
792Constraint CpModelBuilder::AddBoolAnd(absl::Span<const BoolVar> literals) {
793 ConstraintProto* const proto = cp_model_.add_constraints();
794 for (const BoolVar& lit : literals) {
795 proto->mutable_bool_and()->add_literals(lit.index_);
796 }
797 return Constraint(proto);
798}
799
800Constraint CpModelBuilder::AddBoolXor(absl::Span<const BoolVar> literals) {
801 ConstraintProto* const proto = cp_model_.add_constraints();
802 for (const BoolVar& lit : literals) {
803 proto->mutable_bool_xor()->add_literals(lit.index_);
804 }
805 return Constraint(proto);
806}
807
808void CpModelBuilder::FillLinearTerms(const LinearExpr& left,
809 const LinearExpr& right,
810 LinearConstraintProto* proto) {
811 for (const int x : left.variables()) {
812 proto->add_vars(x);
813 }
814 for (const int64_t coeff : left.coefficients()) {
815 proto->add_coeffs(coeff);
816 }
817 for (const int x : right.variables()) {
818 proto->add_vars(x);
819 }
820 for (const int64_t coeff : right.coefficients()) {
821 proto->add_coeffs(-coeff);
822 }
823}
824
826 const LinearExpr& right) {
827 ConstraintProto* const proto = cp_model_.add_constraints();
828 FillLinearTerms(left, right, proto->mutable_linear());
829 const int64_t rhs = right.constant() - left.constant();
830 proto->mutable_linear()->add_domain(rhs);
831 proto->mutable_linear()->add_domain(rhs);
832 return Constraint(proto);
833}
834
836 const LinearExpr& right) {
837 ConstraintProto* const proto = cp_model_.add_constraints();
838 FillLinearTerms(left, right, proto->mutable_linear());
839 const int64_t rhs = right.constant() - left.constant();
840 proto->mutable_linear()->add_domain(rhs);
841 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::max());
842 return Constraint(proto);
843}
844
846 const LinearExpr& right) {
847 ConstraintProto* const proto = cp_model_.add_constraints();
848 FillLinearTerms(left, right, proto->mutable_linear());
849 const int64_t rhs = right.constant() - left.constant();
850 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::min());
851 proto->mutable_linear()->add_domain(rhs);
852 return Constraint(proto);
853}
854
856 const LinearExpr& right) {
857 ConstraintProto* const proto = cp_model_.add_constraints();
858 FillLinearTerms(left, right, proto->mutable_linear());
859 const int64_t rhs = right.constant() - left.constant();
860 proto->mutable_linear()->add_domain(rhs + 1);
861 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::max());
862 return Constraint(proto);
863}
864
866 const LinearExpr& right) {
867 ConstraintProto* const proto = cp_model_.add_constraints();
868 FillLinearTerms(left, right, proto->mutable_linear());
869 const int64_t rhs = right.constant() - left.constant();
870 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::min());
871 proto->mutable_linear()->add_domain(rhs - 1);
872 return Constraint(proto);
873}
874
876 const Domain& domain) {
877 ConstraintProto* const proto = cp_model_.add_constraints();
878 for (const int x : expr.variables()) {
879 proto->mutable_linear()->add_vars(x);
880 }
881 for (const int64_t coeff : expr.coefficients()) {
882 proto->mutable_linear()->add_coeffs(coeff);
883 }
884 const int64_t cst = expr.constant();
885 for (const auto& i : domain) {
886 proto->mutable_linear()->add_domain(i.start - cst);
887 proto->mutable_linear()->add_domain(i.end - cst);
888 }
889 return Constraint(proto);
890}
891
893 const LinearExpr& right) {
894 ConstraintProto* const proto = cp_model_.add_constraints();
895 FillLinearTerms(left, right, proto->mutable_linear());
896 const int64_t rhs = right.constant() - left.constant();
897 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::min());
898 proto->mutable_linear()->add_domain(rhs - 1);
899 proto->mutable_linear()->add_domain(rhs + 1);
900 proto->mutable_linear()->add_domain(std::numeric_limits<int64_t>::max());
901 return Constraint(proto);
902}
903
904Constraint CpModelBuilder::AddAllDifferent(absl::Span<const IntVar> vars) {
905 ConstraintProto* const proto = cp_model_.add_constraints();
906 for (const IntVar& var : vars) {
907 auto* expr = proto->mutable_all_diff()->add_exprs();
908 expr->add_vars(var.index_);
909 expr->add_coeffs(1);
910 }
911 return Constraint(proto);
912}
913
914Constraint CpModelBuilder::AddAllDifferent(absl::Span<const LinearExpr> exprs) {
915 ConstraintProto* const proto = cp_model_.add_constraints();
916 for (const LinearExpr& expr : exprs) {
917 *proto->mutable_all_diff()->add_exprs() = LinearExprToProto(expr);
918 }
919 return Constraint(proto);
920}
921
923 std::initializer_list<LinearExpr> exprs) {
924 ConstraintProto* const proto = cp_model_.add_constraints();
925 for (const LinearExpr& expr : exprs) {
926 *proto->mutable_all_diff()->add_exprs() = LinearExprToProto(expr);
927 }
928 return Constraint(proto);
929}
930
932 IntVar index, absl::Span<const IntVar> variables, IntVar target) {
933 ConstraintProto* const proto = cp_model_.add_constraints();
934 proto->mutable_element()->set_index(index.index_);
935 proto->mutable_element()->set_target(target.index_);
936 for (const IntVar& var : variables) {
937 proto->mutable_element()->add_vars(var.index_);
938 }
939 return Constraint(proto);
940}
941
943 absl::Span<const int64_t> values,
944 IntVar target) {
945 ConstraintProto* const proto = cp_model_.add_constraints();
946 proto->mutable_element()->set_index(index.index_);
947 proto->mutable_element()->set_target(target.index_);
948 for (int64_t value : values) {
949 proto->mutable_element()->add_vars(IndexFromConstant(value));
950 }
951 return Constraint(proto);
952}
953
955 return CircuitConstraint(cp_model_.add_constraints());
956}
957
961
963 absl::Span<const IntVar> vars) {
964 ConstraintProto* const proto = cp_model_.add_constraints();
965 for (const IntVar& var : vars) {
966 proto->mutable_table()->add_vars(var.index_);
967 }
968 return TableConstraint(proto);
969}
970
972 absl::Span<const IntVar> vars) {
973 ConstraintProto* const proto = cp_model_.add_constraints();
974 for (const IntVar& var : vars) {
975 proto->mutable_table()->add_vars(var.index_);
976 }
977 proto->mutable_table()->set_negated(true);
978 return TableConstraint(proto);
979}
980
982 absl::Span<const IntVar> variables,
983 absl::Span<const IntVar> inverse_variables) {
984 ConstraintProto* const proto = cp_model_.add_constraints();
985 for (const IntVar& var : variables) {
986 proto->mutable_inverse()->add_f_direct(var.index_);
987 }
988 for (const IntVar& var : inverse_variables) {
989 proto->mutable_inverse()->add_f_inverse(var.index_);
990 }
991 return Constraint(proto);
992}
993
995 int64_t max_level) {
996 ConstraintProto* const proto = cp_model_.add_constraints();
997 proto->mutable_reservoir()->set_min_level(min_level);
998 proto->mutable_reservoir()->set_max_level(max_level);
999 return ReservoirConstraint(proto, this);
1000}
1001
1003 absl::Span<const IntVar> transition_variables, int starting_state,
1004 absl::Span<const int> final_states) {
1005 ConstraintProto* const proto = cp_model_.add_constraints();
1006 for (const IntVar& var : transition_variables) {
1007 proto->mutable_automaton()->add_vars(var.index_);
1008 }
1009 proto->mutable_automaton()->set_starting_state(starting_state);
1010 for (const int final_state : final_states) {
1011 proto->mutable_automaton()->add_final_states(final_state);
1012 }
1013 return AutomatonConstraint(proto);
1014}
1015
1016LinearExpressionProto CpModelBuilder::LinearExprToProto(const LinearExpr& expr,
1017 bool negate) {
1018 LinearExpressionProto expr_proto;
1019 for (const int var : expr.variables()) {
1020 expr_proto.add_vars(var);
1021 }
1022 const int64_t mult = negate ? -1 : 1;
1023 for (const int64_t coeff : expr.coefficients()) {
1024 expr_proto.add_coeffs(coeff * mult);
1025 }
1026 expr_proto.set_offset(expr.constant() * mult);
1027 return expr_proto;
1028}
1029
1031 absl::Span<const IntVar> vars) {
1032 ConstraintProto* ct = cp_model_.add_constraints();
1033 *ct->mutable_lin_max()->mutable_target() =
1034 LinearExprToProto(target, /*negate=*/true);
1035 for (const IntVar& var : vars) {
1036 *ct->mutable_lin_max()->add_exprs() =
1037 LinearExprToProto(var, /*negate=*/true);
1038 }
1039 return Constraint(ct);
1040}
1041
1043 absl::Span<const LinearExpr> exprs) {
1044 ConstraintProto* ct = cp_model_.add_constraints();
1045 *ct->mutable_lin_max()->mutable_target() =
1046 LinearExprToProto(target, /*negate=*/true);
1047 for (const LinearExpr& expr : exprs) {
1048 *ct->mutable_lin_max()->add_exprs() =
1049 LinearExprToProto(expr, /*negate=*/true);
1050 }
1051 return Constraint(ct);
1052}
1053
1055 const LinearExpr& target, std::initializer_list<LinearExpr> exprs) {
1056 ConstraintProto* ct = cp_model_.add_constraints();
1057 *ct->mutable_lin_max()->mutable_target() =
1058 LinearExprToProto(target, /*negate=*/true);
1059 for (const LinearExpr& expr : exprs) {
1060 *ct->mutable_lin_max()->add_exprs() =
1061 LinearExprToProto(expr, /*negate=*/true);
1062 }
1063 return Constraint(ct);
1064}
1065
1067 absl::Span<const IntVar> vars) {
1068 ConstraintProto* ct = cp_model_.add_constraints();
1069 *ct->mutable_lin_max()->mutable_target() = LinearExprToProto(target);
1070 for (const IntVar& var : vars) {
1071 *ct->mutable_lin_max()->add_exprs() = LinearExprToProto(var);
1072 }
1073 return Constraint(ct);
1074}
1075
1077 absl::Span<const LinearExpr> exprs) {
1078 ConstraintProto* ct = cp_model_.add_constraints();
1079 *ct->mutable_lin_max()->mutable_target() = LinearExprToProto(target);
1080 for (const LinearExpr& expr : exprs) {
1081 *ct->mutable_lin_max()->add_exprs() = LinearExprToProto(expr);
1082 }
1083 return Constraint(ct);
1084}
1085
1087 const LinearExpr& target, std::initializer_list<LinearExpr> exprs) {
1088 ConstraintProto* ct = cp_model_.add_constraints();
1089 *ct->mutable_lin_max()->mutable_target() = LinearExprToProto(target);
1090 for (const LinearExpr& expr : exprs) {
1091 *ct->mutable_lin_max()->add_exprs() = LinearExprToProto(expr);
1092 }
1093 return Constraint(ct);
1094}
1095
1097 const LinearExpr& numerator,
1098 const LinearExpr& denominator) {
1099 ConstraintProto* const proto = cp_model_.add_constraints();
1100 *proto->mutable_int_div()->mutable_target() = LinearExprToProto(target);
1101 *proto->mutable_int_div()->add_exprs() = LinearExprToProto(numerator);
1102 *proto->mutable_int_div()->add_exprs() = LinearExprToProto(denominator);
1103 return Constraint(proto);
1104}
1105
1107 const LinearExpr& expr) {
1108 ConstraintProto* const proto = cp_model_.add_constraints();
1109 *proto->mutable_lin_max()->mutable_target() = LinearExprToProto(target);
1110 *proto->mutable_lin_max()->add_exprs() = LinearExprToProto(expr);
1111 *proto->mutable_lin_max()->add_exprs() =
1112 LinearExprToProto(expr, /*negate=*/true);
1113 return Constraint(proto);
1114}
1115
1117 const LinearExpr& var,
1118 const LinearExpr& mod) {
1119 ConstraintProto* const proto = cp_model_.add_constraints();
1120 *proto->mutable_int_mod()->mutable_target() = LinearExprToProto(target);
1121 *proto->mutable_int_mod()->add_exprs() = LinearExprToProto(var);
1122 *proto->mutable_int_mod()->add_exprs() = LinearExprToProto(mod);
1123 return Constraint(proto);
1124}
1125
1127 const LinearExpr& target, absl::Span<const IntVar> vars) {
1128 ConstraintProto* const proto = cp_model_.add_constraints();
1129 *proto->mutable_int_prod()->mutable_target() = LinearExprToProto(target);
1130 for (const IntVar& var : vars) {
1131 *proto->mutable_int_prod()->add_exprs() = LinearExprToProto(var);
1132 }
1133 return Constraint(proto);
1134}
1135
1137 const LinearExpr& target, absl::Span<const LinearExpr> exprs) {
1138 ConstraintProto* const proto = cp_model_.add_constraints();
1139 *proto->mutable_int_prod()->mutable_target() = LinearExprToProto(target);
1140 for (const LinearExpr& expr : exprs) {
1141 *proto->mutable_int_prod()->add_exprs() = LinearExprToProto(expr);
1142 }
1143 return Constraint(proto);
1144}
1145
1147 const LinearExpr& target, std::initializer_list<LinearExpr> exprs) {
1148 ConstraintProto* const proto = cp_model_.add_constraints();
1149 *proto->mutable_int_prod()->mutable_target() = LinearExprToProto(target);
1150 for (const LinearExpr& expr : exprs) {
1151 *proto->mutable_int_prod()->add_exprs() = LinearExprToProto(expr);
1152 }
1153 return Constraint(proto);
1154}
1156 const LinearExpr& left,
1157 const LinearExpr& right) {
1158 ConstraintProto* const proto = cp_model_.add_constraints();
1159 *proto->mutable_int_prod()->mutable_target() = LinearExprToProto(target);
1160 *proto->mutable_int_prod()->add_exprs() = LinearExprToProto(left);
1161 *proto->mutable_int_prod()->add_exprs() = LinearExprToProto(right);
1162
1163 return Constraint(proto);
1164}
1165
1166Constraint CpModelBuilder::AddNoOverlap(absl::Span<const IntervalVar> vars) {
1167 ConstraintProto* const proto = cp_model_.add_constraints();
1168 for (const IntervalVar& var : vars) {
1169 proto->mutable_no_overlap()->add_intervals(var.index_);
1170 }
1171 return Constraint(proto);
1172}
1173
1175 return NoOverlap2DConstraint(cp_model_.add_constraints());
1176}
1177
1179 ConstraintProto* const proto = cp_model_.add_constraints();
1180 *proto->mutable_cumulative()->mutable_capacity() =
1181 LinearExprToProto(capacity);
1182 return CumulativeConstraint(proto, this);
1183}
1184
1187 for (const int x : expr.variables()) {
1188 cp_model_.mutable_objective()->add_vars(x);
1189 }
1190 for (const int64_t coeff : expr.coefficients()) {
1191 cp_model_.mutable_objective()->add_coeffs(coeff);
1192 }
1193 cp_model_.mutable_objective()->set_offset(expr.constant());
1194}
1195
1198 for (const int x : expr.variables()) {
1199 cp_model_.mutable_objective()->add_vars(x);
1200 }
1201 for (const int64_t coeff : expr.coefficients()) {
1202 cp_model_.mutable_objective()->add_coeffs(-coeff);
1203 }
1204 cp_model_.mutable_objective()->set_offset(-expr.constant());
1205 cp_model_.mutable_objective()->set_scaling_factor(-1.0);
1206}
1207
1210 for (int i = 0; i < expr.variables().size(); ++i) {
1211 cp_model_.mutable_floating_point_objective()->add_vars(expr.variables()[i]);
1212 cp_model_.mutable_floating_point_objective()->add_coeffs(
1213 expr.coefficients()[i]);
1214 }
1215 cp_model_.mutable_floating_point_objective()->set_offset(expr.constant());
1216 cp_model_.mutable_floating_point_objective()->set_maximize(false);
1217}
1218
1221 for (int i = 0; i < expr.variables().size(); ++i) {
1222 cp_model_.mutable_floating_point_objective()->add_vars(expr.variables()[i]);
1223 cp_model_.mutable_floating_point_objective()->add_coeffs(
1224 expr.coefficients()[i]);
1225 }
1226 cp_model_.mutable_floating_point_objective()->set_offset(expr.constant());
1227 cp_model_.mutable_floating_point_objective()->set_maximize(true);
1228}
1229
1231 cp_model_.clear_objective();
1232 cp_model_.clear_floating_point_objective();
1233}
1234
1236 return cp_model_.has_objective() || cp_model_.has_floating_point_objective();
1237}
1238
1240 absl::Span<const IntVar> variables,
1241 DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1242 DecisionStrategyProto::DomainReductionStrategy domain_strategy) {
1243 DecisionStrategyProto* const proto = cp_model_.add_search_strategy();
1244 for (const IntVar& var : variables) {
1245 LinearExpressionProto* expr = proto->add_exprs();
1246 if (var.index_ >= 0) {
1247 expr->add_vars(var.index_);
1248 expr->add_coeffs(1);
1249 } else {
1250 expr->add_vars(PositiveRef(var.index_));
1251 expr->add_coeffs(-1);
1252 expr->set_offset(1);
1253 }
1254 }
1255 proto->set_variable_selection_strategy(var_strategy);
1256 proto->set_domain_reduction_strategy(domain_strategy);
1257}
1258
1260 absl::Span<const BoolVar> variables,
1261 DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1262 DecisionStrategyProto::DomainReductionStrategy domain_strategy) {
1263 DecisionStrategyProto* const proto = cp_model_.add_search_strategy();
1264 for (const BoolVar& var : variables) {
1265 LinearExpressionProto* expr = proto->add_exprs();
1266 if (var.index_ >= 0) {
1267 expr->add_vars(var.index_);
1268 expr->add_coeffs(1);
1269 } else {
1270 expr->add_vars(PositiveRef(var.index_));
1271 expr->add_coeffs(-1);
1272 expr->set_offset(1);
1273 }
1274 }
1275 proto->set_variable_selection_strategy(var_strategy);
1276 proto->set_domain_reduction_strategy(domain_strategy);
1277}
1278
1280 absl::Span<const LinearExpr> expressions,
1281 DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1282 DecisionStrategyProto::DomainReductionStrategy domain_strategy) {
1283 DecisionStrategyProto* const proto = cp_model_.add_search_strategy();
1284 for (const LinearExpr& expr : expressions) {
1285 *proto->add_exprs() = LinearExprToProto(expr);
1286 }
1287 proto->set_variable_selection_strategy(var_strategy);
1288 proto->set_domain_reduction_strategy(domain_strategy);
1289}
1290
1292 std::initializer_list<LinearExpr> expressions,
1293 DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1294 DecisionStrategyProto::DomainReductionStrategy domain_strategy) {
1295 DecisionStrategyProto* const proto = cp_model_.add_search_strategy();
1296 for (const LinearExpr& expr : expressions) {
1297 *proto->add_exprs() = LinearExprToProto(expr);
1298 }
1299 proto->set_variable_selection_strategy(var_strategy);
1300 proto->set_domain_reduction_strategy(domain_strategy);
1301}
1302
1304 cp_model_.mutable_solution_hint()->add_vars(var.index_);
1305 cp_model_.mutable_solution_hint()->add_values(value);
1306}
1307
1309 if (var.index_ >= 0) {
1310 cp_model_.mutable_solution_hint()->add_vars(var.index_);
1311 cp_model_.mutable_solution_hint()->add_values(value);
1312 } else {
1313 cp_model_.mutable_solution_hint()->add_vars(PositiveRef(var.index_));
1314 cp_model_.mutable_solution_hint()->add_values(!value);
1315 }
1316}
1317
1319 cp_model_.mutable_solution_hint()->Clear();
1320}
1321
1323 cp_model_.mutable_assumptions()->Add(lit.index_);
1324}
1325
1326void CpModelBuilder::AddAssumptions(absl::Span<const BoolVar> literals) {
1327 for (const BoolVar& lit : literals) {
1328 cp_model_.mutable_assumptions()->Add(lit.index_);
1329 }
1330}
1331
1333 cp_model_.mutable_assumptions()->Clear();
1334}
1335
1337 CpModelBuilder clone;
1338 clone.ResetAndImport(cp_model_);
1339 return clone;
1340}
1341
1342void CpModelBuilder::ResetAndImport(const CpModelProto& model_proto) {
1343 cp_model_ = model_proto;
1344 // Rebuild constant to index map.
1345 constant_to_index_map_.clear();
1346 for (int i = 0; i < cp_model_.variables_size(); ++i) {
1347 const IntegerVariableProto& var = cp_model_.variables(i);
1348 if (var.domain_size() == 2 && var.domain(0) == var.domain(1)) {
1349 constant_to_index_map_[var.domain(0)] = i;
1350 }
1351 }
1352 // This one would be more complicated to rebuild. Let's just clear it.
1353 bool_to_integer_index_map_.clear();
1354}
1355
1357 CHECK_GE(index, 0);
1358 CHECK_LT(index, cp_model_.variables_size());
1359 const IntegerVariableProto& proto = cp_model_.variables(index);
1360 CHECK_EQ(2, proto.domain_size())
1361 << "CpModelBuilder::GetBoolVarFromProtoIndex: The domain of the variable "
1362 "is not Boolean";
1363 CHECK_GE(0, proto.domain(0))
1364 << "CpModelBuilder::GetBoolVarFromProtoIndex: The domain of the variable "
1365 "is not Boolean";
1366 CHECK_LE(1, proto.domain(1))
1367 << "CpModelBuilder::GetBoolVarFromProtoIndex: The domain of the variable "
1368 "is not Boolean";
1369 return BoolVar(index, this);
1370}
1371
1373 CHECK_GE(index, 0);
1374 CHECK_LT(index, cp_model_.variables_size());
1375 return IntVar(index, this);
1376}
1377
1379 CHECK_GE(index, 0);
1380 CHECK_LT(index, cp_model_.constraints_size());
1381 const ConstraintProto& ct = cp_model_.constraints(index);
1382 CHECK_EQ(ct.constraint_case(), ConstraintProto::kInterval)
1383 << "CpModelBuilder::GetIntervalVarFromProtoIndex: the referenced "
1384 "object is not an interval variable";
1385 return IntervalVar(index, this);
1386}
1387
1388bool CpModelBuilder::ExportToFile(absl::string_view filename) const {
1389 return WriteModelProtoToFile(cp_model_, filename);
1390}
1391
1392int64_t SolutionIntegerValue(const CpSolverResponse& r,
1393 const LinearExpr& expr) {
1394 int64_t result = expr.constant();
1395 const std::vector<int>& variables = expr.variables();
1396 const std::vector<int64_t>& coefficients = expr.coefficients();
1397 for (int i = 0; i < variables.size(); ++i) {
1398 result += r.solution(variables[i]) * coefficients[i];
1399 }
1400 return result;
1401}
1402
1403bool SolutionBooleanValue(const CpSolverResponse& r, BoolVar x) {
1404 const int ref = x.index_;
1405 if (RefIsPositive(ref)) {
1406 return r.solution(ref) == 1;
1407 } else {
1408 return r.solution(PositiveRef(ref)) == 0;
1409 }
1410}
1411
1412} // namespace sat
1413} // namespace operations_research
IntegerValue size
virtual std::string DebugString() const
IntVar(Solver *s)
-------— IntVar -------—
LinearExpr & operator+=(const LinearExpr &rhs)
LinearExpr & operator-=(const LinearExpr &rhs)
LinearExpr & operator*=(double rhs)
virtual std::string name() const
Object naming.
void AddTransition(int tail, int head, int64_t transition_label)
Adds a transitions to the automaton.
Definition cp_model.cc:554
BoolVar Not() const
Returns the logical negation of the current Boolean variable.
Definition cp_model.h:91
void AddArc(int tail, int head, BoolVar literal)
Definition cp_model.cc:514
Constraint WithName(absl::string_view name)
Sets the name of the constraint.
Definition cp_model.cc:495
Constraint OnlyEnforceIf(absl::Span< const BoolVar > literals)
Definition cp_model.cc:502
absl::string_view Name() const
Returns the name of the constraint (or the empty string if not set).
Definition cp_model.cc:500
Constraint AddVariableElement(IntVar index, absl::Span< const IntVar > variables, IntVar target)
Adds the element constraint: variables[index] == target.
Definition cp_model.cc:931
bool HasObjective() const
Checks whether the model contains an objective.
Definition cp_model.cc:1235
TableConstraint AddForbiddenAssignments(absl::Span< const IntVar > vars)
Definition cp_model.cc:971
BoolVar GetBoolVarFromProtoIndex(int index)
Returns the Boolean variable from its index in the proto.
Definition cp_model.cc:1356
IntVar NewIntVar(const Domain &domain)
Creates an integer variable with the given domain.
Definition cp_model.cc:682
Constraint AddInverseConstraint(absl::Span< const IntVar > variables, absl::Span< const IntVar > inverse_variables)
Definition cp_model.cc:981
void Minimize(const LinearExpr &expr)
Adds a linear minimization objective.
Definition cp_model.cc:1185
NoOverlap2DConstraint AddNoOverlap2D()
Definition cp_model.cc:1174
Constraint AddBoolXor(absl::Span< const BoolVar > literals)
Adds the constraint that an odd number of literals is true.
Definition cp_model.cc:800
IntervalVar NewIntervalVar(const LinearExpr &start, const LinearExpr &size, const LinearExpr &end)
Creates an interval variable from 3 affine expressions.
Definition cp_model.cc:712
IntVar GetIntVarFromProtoIndex(int index)
Returns the integer variable from its index in the proto.
Definition cp_model.cc:1372
Constraint AddMultiplicationEquality(const LinearExpr &target, absl::Span< const LinearExpr > exprs)
Adds target == prod(exprs).
Definition cp_model.cc:1136
CpModelBuilder Clone() const
Returns a cloned version of the current model.
Definition cp_model.cc:1336
Constraint AddBoolAnd(absl::Span< const BoolVar > literals)
Adds the constraint that all literals must be true.
Definition cp_model.cc:792
Constraint AddMaxEquality(const LinearExpr &target, absl::Span< const IntVar > vars)
Adds target == max(vars).
Definition cp_model.cc:1066
void Maximize(const LinearExpr &expr)
Adds a linear maximization objective.
Definition cp_model.cc:1196
void FixVariable(IntVar var, int64_t value)
Definition cp_model.cc:750
ReservoirConstraint AddReservoirConstraint(int64_t min_level, int64_t max_level)
Definition cp_model.cc:994
void AddDecisionStrategy(absl::Span< const IntVar > variables, DecisionStrategyProto::VariableSelectionStrategy var_strategy, DecisionStrategyProto::DomainReductionStrategy domain_strategy)
Adds a decision strategy on a list of integer variables.
Definition cp_model.cc:1239
Constraint AddLessOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left <= right.
Definition cp_model.cc:845
IntervalVar NewOptionalIntervalVar(const LinearExpr &start, const LinearExpr &size, const LinearExpr &end, BoolVar presence)
Definition cp_model.cc:723
void ClearAssumptions()
Remove all assumptions from the model.
Definition cp_model.cc:1332
Constraint AddLinearConstraint(const LinearExpr &expr, const Domain &domain)
Adds expr in domain.
Definition cp_model.cc:875
AutomatonConstraint AddAutomaton(absl::Span< const IntVar > transition_variables, int starting_state, absl::Span< const int > final_states)
Definition cp_model.cc:1002
void AddHint(IntVar var, int64_t value)
Adds hinting to a variable.
Definition cp_model.cc:1303
Constraint AddAllDifferent(absl::Span< const IntVar > vars)
This constraint forces all variables to have different values.
Definition cp_model.cc:904
IntervalVar GetIntervalVarFromProtoIndex(int index)
Returns the interval variable from its index in the proto.
Definition cp_model.cc:1378
Constraint AddExactlyOne(absl::Span< const BoolVar > literals)
Exactly one literal is true. Sum literals == 1.
Definition cp_model.cc:784
Constraint AddMinEquality(const LinearExpr &target, absl::Span< const IntVar > vars)
Adds target == min(vars).
Definition cp_model.cc:1030
void AddAssumption(BoolVar lit)
Adds a literal to the model as assumptions.
Definition cp_model.cc:1322
bool ExportToFile(absl::string_view filename) const
Export the model to file.
Definition cp_model.cc:1388
Constraint AddGreaterOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left >= right.
Definition cp_model.cc:835
Constraint AddLessThan(const LinearExpr &left, const LinearExpr &right)
Adds left < right.
Definition cp_model.cc:865
TableConstraint AddAllowedAssignments(absl::Span< const IntVar > vars)
Definition cp_model.cc:962
Constraint AddElement(IntVar index, absl::Span< const int64_t > values, IntVar target)
Adds the element constraint: values[index] == target.
Definition cp_model.cc:942
MultipleCircuitConstraint AddMultipleCircuitConstraint()
Definition cp_model.cc:958
Constraint AddNoOverlap(absl::Span< const IntervalVar > vars)
Definition cp_model.cc:1166
const CpModelProto & Proto() const
Definition cp_model.h:1112
BoolVar NewBoolVar()
Creates a Boolean variable.
Definition cp_model.cc:692
Constraint AddNotEqual(const LinearExpr &left, const LinearExpr &right)
Adds left != right.
Definition cp_model.cc:892
Constraint AddAtLeastOne(absl::Span< const BoolVar > literals)
Same as AddBoolOr(). Sum literals >= 1.
Definition cp_model.cc:772
void ClearObjective()
Removes the objective from the model.
Definition cp_model.cc:1230
Constraint AddAtMostOne(absl::Span< const BoolVar > literals)
At most one literal is true. Sum literals <= 1.
Definition cp_model.cc:776
void ClearHints()
Removes all hints.
Definition cp_model.cc:1318
void AddAssumptions(absl::Span< const BoolVar > literals)
Adds multiple literals to the model as assumptions.
Definition cp_model.cc:1326
Constraint AddGreaterThan(const LinearExpr &left, const LinearExpr &right)
Adds left > right.
Definition cp_model.cc:855
Constraint AddDivisionEquality(const LinearExpr &target, const LinearExpr &numerator, const LinearExpr &denominator)
Adds target = num / denom (integer division rounded towards 0).
Definition cp_model.cc:1096
Constraint AddEquality(const LinearExpr &left, const LinearExpr &right)
Adds left == right.
Definition cp_model.cc:825
void SetName(absl::string_view name)
Sets the name of the model.
Definition cp_model.cc:646
Constraint AddAbsEquality(const LinearExpr &target, const LinearExpr &expr)
Adds target == abs(expr).
Definition cp_model.cc:1106
Constraint AddBoolOr(absl::Span< const BoolVar > literals)
Adds the constraint that at least one of the literals must be true.
Definition cp_model.cc:764
IntervalVar NewFixedSizeIntervalVar(const LinearExpr &start, int64_t size)
Creates an interval variable with a fixed size.
Definition cp_model.cc:718
CumulativeConstraint AddCumulative(LinearExpr capacity)
Definition cp_model.cc:1178
Constraint AddModuloEquality(const LinearExpr &target, const LinearExpr &var, const LinearExpr &mod)
Adds target = var % mod.
Definition cp_model.cc:1116
IntervalVar NewOptionalFixedSizeIntervalVar(const LinearExpr &start, int64_t size, BoolVar presence)
Creates an optional interval variable with a fixed size.
Definition cp_model.cc:737
void AddDemand(IntervalVar interval, LinearExpr demand)
Adds a pair (interval, demand) to the constraint.
Definition cp_model.cc:571
const std::vector< double > & coefficients() const
Returns the vector of coefficients.
Definition cp_model.h:411
DoubleLinearExpr & AddTerm(IntVar var, double coeff)
Adds a term (var * coeff) to the linear expression.
Definition cp_model.cc:391
double constant() const
Returns the constant term.
Definition cp_model.h:417
const std::vector< int > & variables() const
Returns the vector of variable indices.
Definition cp_model.h:408
std::string DebugString(const CpModelProto *proto=nullptr) const
Debug string. See the documentation for LinearExpr::DebugString().
Definition cp_model.cc:450
std::string DebugString() const
Definition cp_model.cc:136
IntervalVar WithName(absl::string_view name)
Sets the name of the variable.
Definition cp_model.cc:582
std::string Name() const
Returns the name of the interval (or the empty string if not set).
Definition cp_model.cc:617
std::string DebugString() const
Returns a debug string.
Definition cp_model.cc:622
std::string DebugString(const CpModelProto *proto=nullptr) const
Definition cp_model.cc:280
int64_t constant() const
Returns the constant term.
Definition cp_model.h:303
static LinearExpr FromProto(const LinearExpressionProto &proto)
Constructs a linear expr from its proto representation.
Definition cp_model.cc:198
const std::vector< int > & variables() const
Returns the vector of variable indices.
Definition cp_model.h:294
const std::vector< int64_t > & coefficients() const
Returns the vector of coefficients.
Definition cp_model.h:297
void AddArc(int tail, int head, BoolVar literal)
Definition cp_model.cc:520
void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate)
Adds a rectangle (parallel to the axis) to the constraint.
Definition cp_model.cc:561
void AddOptionalEvent(LinearExpr time, int64_t level_change, BoolVar is_active)
Definition cp_model.cc:545
void AddEvent(LinearExpr time, int64_t level_change)
Definition cp_model.cc:537
void AddTuple(absl::Span< const int64_t > tuple)
Adds a tuple of possible values to the constraint.
Definition cp_model.cc:526
CpModelProto proto
The output proto.
const std::string name
A name for logging purposes.
const Constraint * ct
int64_t value
IntVar * var
absl::Span< const double > coefficients
int lit
int literal
int index
std::string VarDebugString(const CpModelProto &proto, int index)
Definition cp_model.cc:143
bool WriteModelProtoToFile(const M &proto, absl::string_view filename)
BoolVar Not(BoolVar x)
Definition cp_model.cc:87
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
Definition cp_model.cc:89
void FillDomainInProto(const Domain &domain, ProtoWithDomain *proto)
Serializes a Domain into the domain field of a proto.
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Reads a Domain from the domain field of a proto.
int64_t SolutionIntegerValue(const CpSolverResponse &r, const LinearExpr &expr)
Evaluates the value of an linear expression in a solver response.
Definition cp_model.cc:1392
int NegatedRef(int ref)
Small utility functions to deal with negative variable/literal references.
bool SolutionBooleanValue(const CpSolverResponse &r, BoolVar x)
Evaluates the value of a Boolean literal in a solver response.
Definition cp_model.cc:1403
In SWIG mode, we don't want anything besides these top-level includes.
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
const Variable x
Definition qp_tests.cc:127
int64_t demand
Definition resource.cc:126
int64_t time
Definition resource.cc:1708
IntervalVar * interval
Definition resource.cc:101
int64_t coefficient
int head
int tail
std::optional< int64_t > end
int64_t start
std::ostream & operator<<(std::ostream &out, const std::pair< First, Second > &p)
Definition stl_logging.h:99