14 #ifndef OR_TOOLS_SAT_OPB_READER_H_
15 #define OR_TOOLS_SAT_OPB_READER_H_
23 #include "absl/strings/numbers.h"
24 #include "absl/strings/str_split.h"
27 #include "ortools/sat/boolean_problem.pb.h"
41 bool Load(
const std::string& filename, LinearBooleanProblem* problem) {
43 problem->set_name(ExtractProblemName(filename));
49 ProcessNewLine(problem,
line);
52 LOG(FATAL) <<
"File '" << filename <<
"' is empty or can't be read.";
54 problem->set_num_variables(num_variables_);
61 static std::string ExtractProblemName(
const std::string& filename) {
62 const int found = filename.find_last_of(
'/');
63 const std::string problem_name =
64 found != std::string::npos ? filename.substr(found + 1) : filename;
68 void ProcessNewLine(LinearBooleanProblem* problem,
const std::string&
line) {
69 const std::vector<std::string> words =
70 absl::StrSplit(
line, absl::ByAnyChar(
" ;"), absl::SkipEmpty());
71 if (words.empty() || words[0].empty() || words[0][0] ==
'*') {
75 if (words[0] ==
"min:") {
76 LinearObjective* objective = problem->mutable_objective();
77 for (
int i = 1; i < words.size(); ++i) {
78 const std::string& word = words[i];
79 if (word.empty() || word[0] ==
';')
continue;
82 CHECK(absl::SimpleAtoi(word.substr(1), &
literal));
84 objective->add_literals(
literal);
87 CHECK(absl::SimpleAtoi(word, &
value));
88 objective->add_coefficients(
value);
91 if (objective->literals_size() != objective->coefficients_size()) {
92 LOG(INFO) <<
"words.size() = " << words.size();
93 LOG(FATAL) <<
"Failed to parse objective:\n " <<
line;
97 LinearBooleanConstraint* constraint = problem->add_constraints();
98 for (
int i = 0; i < words.size(); ++i) {
99 const std::string& word = words[i];
100 CHECK(!word.empty());
102 CHECK_LT(i + 1, words.size());
104 CHECK(absl::SimpleAtoi(words[i + 1], &
value));
105 constraint->set_lower_bound(
value);
107 }
else if (word ==
"=") {
108 CHECK_LT(i + 1, words.size());
110 CHECK(absl::SimpleAtoi(words[i + 1], &
value));
111 constraint->set_upper_bound(
value);
112 constraint->set_lower_bound(
value);
115 if (word[0] ==
'x') {
117 CHECK(absl::SimpleAtoi(word.substr(1), &
literal));
119 constraint->add_literals(
literal);
122 CHECK(absl::SimpleAtoi(words[i], &
value));
123 constraint->add_coefficients(
value);
127 if (constraint->literals_size() != constraint->coefficients_size()) {
128 LOG(FATAL) <<
"Failed to parse constraint:\n " <<
line;
bool Load(const std::string &filename, LinearBooleanProblem *problem)
Collection of objects used to extend the Constraint Solver library.