OR-Tools  9.6
sat/lp_utils.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 // Utility functions to interact with an lp solver from the SAT context.
15 
16 #ifndef OR_TOOLS_SAT_LP_UTILS_H_
17 #define OR_TOOLS_SAT_LP_UTILS_H_
18 
19 #include <stdint.h>
20 
21 #include <utility>
22 #include <vector>
23 
24 #include "ortools/linear_solver/linear_solver.pb.h"
26 #include "ortools/sat/boolean_problem.pb.h"
27 #include "ortools/sat/cp_model.pb.h"
28 #include "ortools/sat/sat_parameters.pb.h"
29 #include "ortools/sat/sat_solver.h"
30 #include "ortools/util/logging.h"
31 
32 namespace operations_research {
33 namespace sat {
34 
35 // Returns the smallest factor f such that f * abs(x) is integer modulo the
36 // given tolerance relative to f (we use f * tolerance). It is only looking
37 // for f smaller than the given limit. Returns zero if no such factor exist
38 // below the limit.
39 //
40 // The complexity is a lot less than O(limit), but it is possible that we might
41 // miss the smallest such factor if the tolerance used is too low. This is
42 // because we only rely on the best rational approximations of x with increasing
43 // denominator.
44 int64_t FindRationalFactor(double x, int64_t limit = 1e4,
45  double tolerance = 1e-6);
46 
47 // Given a linear expression Sum_i c_i * X_i with each X_i in [lb_i, ub_i],
48 // this returns a scaling factor f such that
49 // 1/ the rounded expression cannot overflow given the domains of the X_i:
50 // Sum |std::round(f * c_i) * X_i| <= max_absolute_activity
51 // 2/ the error is bounded:
52 // | Sum_i (std::round(f * c_i) - f * c_i) |
53 // < f * wanted_absolute_activity_precision
54 //
55 // This also fills the exact errors made by using the returned scaling factor.
56 // The heuristics try to minimize the magnitude of the scaled expression while
57 // satisfying the requested precision.
58 //
59 // Returns 0.0 if no scaling factor can be found under the condition 1/. Note
60 // that we try really hard to satisfy 2/ but we still return our best shot even
61 // when 2/ is not satisfied. One can check this by comparing the returned
62 // scaled_sum_error / f with wanted_absolute_activity_precision.
63 //
64 // TODO(user): unit test this and move to fp_utils.
65 // TODO(user): Ideally the lower/upper should be int64_t so that we can have
66 // an exact definition for the max_absolute_activity allowed.
68  const std::vector<double>& coefficients,
69  const std::vector<double>& lower_bounds,
70  const std::vector<double>& upper_bounds, int64_t max_absolute_activity,
71  double wanted_absolute_activity_precision, double* relative_coeff_error,
72  double* scaled_sum_error);
73 
74 // Multiplies all continuous variable by the given scaling parameters and change
75 // the rest of the model accordingly. The returned vector contains the scaling
76 // of each variable (will always be 1.0 for integers) and can be used to recover
77 // a solution of the unscaled problem from one of the new scaled problems by
78 // dividing the variable values.
79 //
80 // We usually scale a continuous variable by scaling, but if its domain is going
81 // to have larger values than max_bound, then we scale to have the max domain
82 // magnitude equal to max_bound.
83 //
84 // Note that it is recommended to call DetectImpliedIntegers() before this
85 // function so that we do not scale variables that do not need to be scaled.
86 //
87 // TODO(user): Also scale the solution hint if any.
88 std::vector<double> ScaleContinuousVariables(double scaling, double max_bound,
89  MPModelProto* mp_model);
90 
91 // This simple step helps and should be done first. Returns false if the model
92 // is trivially infeasible because of crossing bounds.
93 bool MakeBoundsOfIntegerVariablesInteger(const SatParameters& params,
94  MPModelProto* mp_model,
95  SolverLogger* logger);
96 
97 // Performs some extra tests on the given MPModelProto and returns false if one
98 // is not satisfied. These are needed before trying to convert it to the native
99 // CP-SAT format.
100 bool MPModelProtoValidationBeforeConversion(const SatParameters& params,
101  const MPModelProto& mp_model,
102  SolverLogger* logger);
103 
104 // To satisfy our scaling requirements, any terms that is almost zero can just
105 // be set to zero. We need to do that before operations like
106 // DetectImpliedIntegers(), becauses really low coefficients can cause issues
107 // and might lead to less detection.
108 void RemoveNearZeroTerms(const SatParameters& params, MPModelProto* mp_model,
109  SolverLogger* logger);
110 
111 // This will mark implied integer as such. Note that it can also discover
112 // variable of the form coeff * Integer + offset, and will change the model
113 // so that these are marked as integer. It is why we return both a scaling and
114 // an offset to transform the solution back to its original domain.
115 //
116 // TODO(user): Actually implement the offset part. This currently only happens
117 // on the 3 neos-46470* miplib problems where we have a non-integer rhs.
118 std::vector<double> DetectImpliedIntegers(MPModelProto* mp_model,
119  SolverLogger* logger);
120 
121 // Converts a MIP problem to a CpModel. Returns false if the coefficients
122 // couldn't be converted to integers with a good enough precision.
123 //
124 // There is a bunch of caveats and you can find more details on the
125 // SatParameters proto documentation for the mip_* parameters.
126 bool ConvertMPModelProtoToCpModelProto(const SatParameters& params,
127  const MPModelProto& mp_model,
128  CpModelProto* cp_model,
129  SolverLogger* logger);
130 
131 // Converts a CP-SAT model to a MPModelProto one.
132 // This only works for pure linear model (otherwise it returns false). This is
133 // mainly useful for debugging or using CP-SAT presolve and then trying other
134 // MIP solvers.
135 //
136 // TODO(user): This first version do not even handle basic Boolean constraint.
137 // Support more constraints as needed.
138 bool ConvertCpModelProtoToMPModelProto(const CpModelProto& input,
139  MPModelProto* output);
140 
141 // Scales a double objective to its integer version and fills it in the proto.
142 // The variable listed in the objective must be already defined in the cp_model
143 // proto as this uses the variables bounds to compute a proper scaling.
144 //
145 // This uses params.mip_wanted_tolerance() and
146 // params.mip_max_activity_exponent() to compute the scaling. Note however that
147 // if the wanted tolerance is not satisfied this still scale with best effort.
148 // You can see in the log the tolerance guaranteed by this automatic scaling.
149 //
150 // This will almost always returns true except for really bad cases like having
151 // infinity in the objective.
152 bool ScaleAndSetObjective(const SatParameters& params,
153  const std::vector<std::pair<int, double>>& objective,
154  double objective_offset, bool maximize,
155  CpModelProto* cp_model, SolverLogger* logger);
156 
157 // Given a CpModelProto with a floating point objective, and its scaled integer
158 // version with a known lower bound, this uses the variable bounds to derive a
159 // correct lower bound on the original objective.
160 //
161 // Note that the integer version can be way different, but then the bound is
162 // likely to be bad. For now, we solve this with a simple LP with one
163 // constraint.
164 //
165 // TODO(user): Code a custom algo with more precision guarantee?
167  const CpModelProto& model_proto_with_floating_point_objective,
168  const CpObjectiveProto& integer_objective,
169  const int64_t inner_integer_objective_lower_bound);
170 
171 // Converts an integer program with only binary variables to a Boolean
172 // optimization problem. Returns false if the problem didn't contains only
173 // binary integer variable, or if the coefficients couldn't be converted to
174 // integer with a good enough precision.
175 bool ConvertBinaryMPModelProtoToBooleanProblem(const MPModelProto& mp_model,
176  LinearBooleanProblem* problem);
177 
178 // Converts a Boolean optimization problem to its lp formulation.
179 void ConvertBooleanProblemToLinearProgram(const LinearBooleanProblem& problem,
180  glop::LinearProgram* lp);
181 
182 } // namespace sat
183 } // namespace operations_research
184 
185 #endif // OR_TOOLS_SAT_LP_UTILS_H_
absl::Span< const double > coefficients
bool ConvertCpModelProtoToMPModelProto(const CpModelProto &input, MPModelProto *output)
void ConvertBooleanProblemToLinearProgram(const LinearBooleanProblem &problem, glop::LinearProgram *lp)
bool ConvertBinaryMPModelProtoToBooleanProblem(const MPModelProto &mp_model, LinearBooleanProblem *problem)
void RemoveNearZeroTerms(const SatParameters &params, MPModelProto *mp_model, SolverLogger *logger)
bool ConvertMPModelProtoToCpModelProto(const SatParameters &params, const MPModelProto &mp_model, CpModelProto *cp_model, SolverLogger *logger)
bool MPModelProtoValidationBeforeConversion(const SatParameters &params, const MPModelProto &mp_model, SolverLogger *logger)
bool ScaleAndSetObjective(const SatParameters &params, const std::vector< std::pair< int, double >> &objective, double objective_offset, bool maximize, CpModelProto *cp_model, SolverLogger *logger)
int64_t FindRationalFactor(double x, int64_t limit, double tolerance)
bool MakeBoundsOfIntegerVariablesInteger(const SatParameters &params, MPModelProto *mp_model, SolverLogger *logger)
double ComputeTrueObjectiveLowerBound(const CpModelProto &model_proto_with_floating_point_objective, const CpObjectiveProto &integer_objective, const int64_t inner_integer_objective_lower_bound)
std::vector< double > ScaleContinuousVariables(double scaling, double max_bound, MPModelProto *mp_model)
double FindBestScalingAndComputeErrors(const std::vector< double > &coefficients, const std::vector< double > &lower_bounds, const std::vector< double > &upper_bounds, int64_t max_absolute_activity, double wanted_absolute_activity_precision, double *relative_coeff_error, double *scaled_sum_error)
std::vector< double > DetectImpliedIntegers(MPModelProto *mp_model, SolverLogger *logger)
Collection of objects used to extend the Constraint Solver library.
static int input(yyscan_t yyscanner)
std::vector< double > lower_bounds
std::vector< double > upper_bounds