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