OR-Tools  9.6
qap_reader.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 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 <limits>
17 #include <string>
18 #include <vector>
19 
20 #include "absl/log/check.h"
21 #include "absl/strings/numbers.h"
22 #include "absl/strings/str_split.h"
24 
25 namespace operations_research {
26 
27 // TODO(user): Unit test cases when the function dies, or return
28 // (and test) a status instead.
29 QapProblem ReadQapProblemOrDie(const std::string& filepath) {
30  QapProblem qap_problem;
31 
32  int n = 0;
33  int k = 0;
34  for (const std::string& line :
36  const std::vector<std::string> tokens =
37  absl::StrSplit(line, ' ', absl::SkipEmpty());
38  if (tokens.empty()) continue;
39  if (k == 0) {
40  CHECK_GE(tokens.size(), 1);
41  CHECK_LE(tokens.size(), 2);
42  CHECK(absl::SimpleAtoi(tokens[0], &n));
43  qap_problem.weights.resize(n);
44  qap_problem.distances.resize(n);
45  for (int j = 0; j < n; ++j) {
46  qap_problem.weights[j].assign(n, std::numeric_limits<int64_t>::max());
47  qap_problem.distances[j].assign(n, std::numeric_limits<int64_t>::max());
48  }
49  if (tokens.size() == 2) {
50  CHECK(absl::SimpleAtoi(tokens[1], &qap_problem.best_known_solution));
51  }
52  ++k;
53  } else if (k <= n * n) {
54  for (const std::string& token : tokens) {
55  const int i = (k - 1) / n;
56  const int j = (k - 1) % n;
57  int64_t v = 0.0;
58  CHECK(absl::SimpleAtoi(token, &v)) << "'" << token << "'";
59  qap_problem.weights[i][j] = v;
60  ++k;
61  }
62  } else if (k <= 2 * n * n) {
63  for (const std::string& token : tokens) {
64  const int i = (k - n * n - 1) / n;
65  const int j = (k - n * n - 1) % n;
66  int64_t v = 0.0;
67  CHECK(absl::SimpleAtoi(token, &v));
68  qap_problem.distances[i][j] = v;
69  ++k;
70  }
71  } else {
72  CHECK(false) << "File contains more than 1 + 2 * N^2 entries.";
73  }
74  }
75  return qap_problem;
76 }
77 
78 } // namespace operations_research
int64_t max
Definition: alldiff_cst.cc:140
Collection of objects used to extend the Constraint Solver library.
QapProblem ReadQapProblemOrDie(const std::string &filepath)
Definition: qap_reader.cc:29
int line
Definition: parse_proto.cc:31
std::vector< std::vector< int64_t > > weights
Definition: qap_reader.h:32
std::vector< std::vector< int64_t > > distances
Definition: qap_reader.h:35