OR-Tools  9.6
math_opt/constraints/sos/util.h
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 
14 #ifndef OR_TOOLS_MATH_OPT_CONSTRAINTS_SOS_UTIL_H_
15 #define OR_TOOLS_MATH_OPT_CONSTRAINTS_SOS_UTIL_H_
16 
17 #include <sstream>
18 #include <string>
19 #include <vector>
20 
21 #include "absl/strings/str_join.h"
22 #include "absl/strings/string_view.h"
25 
27 
28 // This method can only be called with a parameter of either `Sos1Constraint`
29 // or `Sos2Constraint`.
30 //
31 // Tested in sos1_constraint_test and sos2_constraint_test, as the ToString()
32 // member functions are thin wrappers around this function.
33 template <typename SosConstraint>
34 std::string SosConstraintToString(SosConstraint constraint,
35  absl::string_view sos_type_name);
36 
38 // Inline function implementations
40 
41 template <typename SosConstraint>
42 std::string SosConstraintToString(const SosConstraint constraint,
43  const absl::string_view sos_type_name) {
44  std::stringstream ostr;
45  const int64_t num_expressions = constraint.num_expressions();
46  std::vector<LinearExpression> expressions;
47  expressions.reserve(num_expressions);
48  for (int i = 0; i < num_expressions; ++i) {
49  expressions.push_back(constraint.Expression(i));
50  }
51  ostr << "{" << absl::StrJoin(expressions, ", ", absl::StreamFormatter())
52  << "} is " << sos_type_name;
53  if (constraint.has_weights()) {
54  std::vector<std::string> weights(num_expressions);
55  for (int i = 0; i < num_expressions; ++i) {
56  weights[i] = RoundTripDoubleFormat::ToString(constraint.weight(i));
57  }
58  ostr << " with weights {" << absl::StrJoin(weights, ", ") << "}";
59  }
60  return ostr.str();
61 }
62 
63 } // namespace operations_research::math_opt::internal
64 
65 #endif // OR_TOOLS_MATH_OPT_CONSTRAINTS_SOS_UTIL_H_
static std::string ToString(double value)
std::string SosConstraintToString(SosConstraint constraint, absl::string_view sos_type_name)