OR-Tools  9.6
sat_interface.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 
14 #include <atomic>
15 #include <cstdint>
16 #include <optional>
17 #include <string>
18 #include <utility>
19 #include <vector>
20 
21 #include "absl/base/attributes.h"
22 #include "absl/status/status.h"
23 #include "absl/status/statusor.h"
25 #include "ortools/base/logging.h"
27 #include "ortools/linear_solver/linear_solver.pb.h"
30 #include "ortools/sat/cp_model.pb.h"
32 
33 namespace operations_research {
34 
36  public:
37  explicit SatInterface(MPSolver* const solver);
38  ~SatInterface() override;
39 
40  // ----- Solve -----
41  MPSolver::ResultStatus Solve(const MPSolverParameters& param) override;
42  std::optional<MPSolutionResponse> DirectlySolveProto(
43  const MPModelRequest& request, std::atomic<bool>* interrupt) override;
44  bool InterruptSolve() override;
45 
46  // ----- Model modifications and extraction -----
47  void Reset() override;
48  void SetOptimizationDirection(bool maximize) override;
49  void SetVariableBounds(int index, double lb, double ub) override;
50  void SetVariableInteger(int index, bool integer) override;
51  void SetConstraintBounds(int index, double lb, double ub) override;
52  void AddRowConstraint(MPConstraint* const ct) override;
53  void AddVariable(MPVariable* const var) override;
54  void SetCoefficient(MPConstraint* const constraint,
55  const MPVariable* const variable, double new_value,
56  double old_value) override;
57  void ClearConstraint(MPConstraint* const constraint) override;
58  void SetObjectiveCoefficient(const MPVariable* const variable,
59  double coefficient) override;
60  void SetObjectiveOffset(double value) override;
61  void ClearObjective() override;
62 
63  bool AddIndicatorConstraint(MPConstraint* const ct) override { return true; }
64 
65  // ------ Query statistics on the solution and the solve ------
66  int64_t iterations() const override;
67  int64_t nodes() const override;
68  MPSolver::BasisStatus row_status(int constraint_index) const override;
69  MPSolver::BasisStatus column_status(int variable_index) const override;
70 
71  // ----- Misc -----
72  bool IsContinuous() const override;
73  bool IsLP() const override;
74  bool IsMIP() const override;
75 
76  std::string SolverVersion() const override;
77  void* underlying_solver() override;
78 
79  void ExtractNewVariables() override;
80  void ExtractNewConstraints() override;
81  void ExtractObjective() override;
82 
83  void SetParameters(const MPSolverParameters& param) override;
84  void SetRelativeMipGap(double value) override;
85  void SetPrimalTolerance(double value) override;
86  void SetDualTolerance(double value) override;
87  void SetPresolveMode(int value) override;
88  void SetScalingMode(int value) override;
89  void SetLpAlgorithm(int value) override;
91  const std::string& parameters) override;
92  absl::Status SetNumThreads(int num_threads) override;
93 
94  private:
95  void NonIncrementalChange();
96 
97  std::atomic<bool> interrupt_solve_;
98  sat::SatParameters parameters_;
99  int num_threads_ = 0;
100 };
101 
103  : MPSolverInterface(solver), interrupt_solve_(false) {}
104 
106 
108  interrupt_solve_ = false;
109 
110  // Reset extraction as this interface is not incremental yet.
111  Reset();
112  ExtractModel();
113 
114  SetParameters(param);
116  solver_->solver_specific_parameter_string_);
117 
118  // Time limit.
119  if (solver_->time_limit()) {
120  VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms.";
121  parameters_.set_max_time_in_seconds(
122  static_cast<double>(solver_->time_limit()) / 1000.0);
123  }
124 
125  // Mark variables and constraints as extracted.
126  for (int i = 0; i < solver_->variables_.size(); ++i) {
127  set_variable_as_extracted(i, true);
128  }
129  for (int i = 0; i < solver_->constraints_.size(); ++i) {
131  }
132 
133  MPModelRequest request;
134  solver_->ExportModelToProto(request.mutable_model());
135  request.set_solver_specific_parameters(
136  EncodeSatParametersAsString(parameters_));
137  request.set_enable_internal_solver_output(!quiet_);
138  const absl::StatusOr<MPSolutionResponse> status_or =
139  SatSolveProto(std::move(request), &interrupt_solve_);
140 
141  if (!status_or.ok()) return MPSolver::ABNORMAL;
142  const MPSolutionResponse& response = status_or.value();
143 
144  // The solution must be marked as synchronized even when no solution exists.
146  result_status_ = static_cast<MPSolver::ResultStatus>(response.status());
147 
148  if (response.status() == MPSOLVER_FEASIBLE ||
149  response.status() == MPSOLVER_OPTIMAL) {
150  const absl::Status result = solver_->LoadSolutionFromProto(response);
151  if (!result.ok()) {
152  LOG(ERROR) << "LoadSolutionFromProto failed: " << result;
153  }
154  }
155 
156  return result_status_;
157 }
158 
159 std::optional<MPSolutionResponse> SatInterface::DirectlySolveProto(
160  const MPModelRequest& request, std::atomic<bool>* interrupt) {
161  absl::StatusOr<MPSolutionResponse> status_or =
162  SatSolveProto(request, interrupt);
163  if (status_or.ok()) return std::move(status_or).value();
164  if (request.enable_internal_solver_output()) {
165  LOG(INFO) << "Failed SAT solve: " << status_or.status();
166  }
167  MPSolutionResponse response;
168  // As of 2021-08, the sole non-OK status returned by SatSolveProto is an
169  // INVALID_ARGUMENT error caused by invalid solver parameters.
170  // TODO(user): Move that conversion to SatSolveProto, which should always
171  // return a MPSolutionResponse, even for errors.
172  response.set_status(absl::IsInvalidArgument(status_or.status())
173  ? MPSOLVER_MODEL_INVALID_SOLVER_PARAMETERS
174  : MPSOLVER_ABNORMAL);
175  response.set_status_str(status_or.status().ToString());
176  return response;
177 }
178 
180  interrupt_solve_ = true;
181  return true;
182 }
183 
185 
187  NonIncrementalChange();
188 }
189 
190 void SatInterface::SetVariableBounds(int index, double lb, double ub) {
191  NonIncrementalChange();
192 }
193 
194 void SatInterface::SetVariableInteger(int index, bool integer) {
195  NonIncrementalChange();
196 }
197 
198 void SatInterface::SetConstraintBounds(int index, double lb, double ub) {
199  NonIncrementalChange();
200 }
201 
203  NonIncrementalChange();
204 }
205 
207  NonIncrementalChange();
208 }
209 
211  const MPVariable* const variable,
212  double new_value, double old_value) {
213  NonIncrementalChange();
214 }
215 
217  NonIncrementalChange();
218 }
219 
221  double coefficient) {
222  NonIncrementalChange();
223 }
224 
225 void SatInterface::SetObjectiveOffset(double value) { NonIncrementalChange(); }
226 
227 void SatInterface::ClearObjective() { NonIncrementalChange(); }
228 
229 int64_t SatInterface::iterations() const {
230  return 0; // FIXME
231 }
232 
233 int64_t SatInterface::nodes() const { return 0; }
234 
235 MPSolver::BasisStatus SatInterface::row_status(int constraint_index) const {
236  return MPSolver::BasisStatus::FREE; // FIXME
237 }
238 
240  return MPSolver::BasisStatus::FREE; // FIXME
241 }
242 
243 bool SatInterface::IsContinuous() const { return false; }
244 bool SatInterface::IsLP() const { return false; }
245 bool SatInterface::IsMIP() const { return true; }
246 
247 std::string SatInterface::SolverVersion() const {
248  return sat::CpSatSolverVersion();
249 }
250 
251 void* SatInterface::underlying_solver() { return nullptr; }
252 
253 void SatInterface::ExtractNewVariables() { NonIncrementalChange(); }
254 
255 void SatInterface::ExtractNewConstraints() { NonIncrementalChange(); }
256 
257 void SatInterface::ExtractObjective() { NonIncrementalChange(); }
258 
260  parameters_.Clear();
261  parameters_.set_num_workers(num_threads_);
262  SetCommonParameters(param);
263 }
264 
265 absl::Status SatInterface::SetNumThreads(int num_threads) {
266  num_threads_ = num_threads;
267  return absl::OkStatus();
268 }
269 
270 // All these have no effect.
276 
277 // TODO(user): Implement me.
279 
281  const std::string& parameters) {
282  return ProtobufTextFormatMergeFromString(parameters, &parameters_);
283 }
284 
285 void SatInterface::NonIncrementalChange() {
286  // The current implementation is not incremental.
288 }
289 
290 // Register Sat in the global linear solver factory.
292  return new SatInterface(solver);
293 }
294 
295 } // namespace operations_research
The class for constraints of a Mathematical Programming (MP) model.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
ResultStatus
The status of solving the problem.
@ ABNORMAL
abnormal, i.e., error of some kind.
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=std::numeric_limits< double >::infinity())
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
void set_constraint_as_extracted(int ct_index, bool extracted)
void set_variable_as_extracted(int var_index, bool extracted)
void SetCommonParameters(const MPSolverParameters &param)
This class stores parameter settings for LP and MIP solvers.
The class for variables of a Mathematical Programming (MP) model.
void SetScalingMode(int value) override
void SetDualTolerance(double value) override
void AddRowConstraint(MPConstraint *const ct) override
void SetLpAlgorithm(int value) override
std::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request, std::atomic< bool > *interrupt) override
SatInterface(MPSolver *const solver)
bool IsContinuous() const override
MPSolver::ResultStatus Solve(const MPSolverParameters &param) override
void SetPrimalTolerance(double value) override
void ClearConstraint(MPConstraint *const constraint) override
bool SetSolverSpecificParametersAsString(const std::string &parameters) override
void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient) override
void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value) override
MPSolver::BasisStatus row_status(int constraint_index) const override
void SetObjectiveOffset(double value) override
void SetVariableInteger(int index, bool integer) override
void SetParameters(const MPSolverParameters &param) override
std::string SolverVersion() const override
void SetRelativeMipGap(double value) override
void SetConstraintBounds(int index, double lb, double ub) override
absl::Status SetNumThreads(int num_threads) override
void SetPresolveMode(int value) override
void SetVariableBounds(int index, double lb, double ub) override
void AddVariable(MPVariable *const var) override
int64_t nodes() const override
int64_t iterations() const override
bool AddIndicatorConstraint(MPConstraint *const ct) override
void SetOptimizationDirection(bool maximize) override
MPSolver::BasisStatus column_status(int variable_index) const override
SatParameters parameters
SharedResponseManager * response
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
A C++ wrapper that provides a simple and unified interface to several linear programming and mixed in...
int index
std::string CpSatSolverVersion()
Returns a string that describes the version of the solver.
Collection of objects used to extend the Constraint Solver library.
absl::StatusOr< MPSolutionResponse > SatSolveProto(MPModelRequest request, std::atomic< bool > *interrupt_solve, std::function< void(const std::string &)> logging_callback, std::function< void(const MPSolution &)> solution_callback)
std::string EncodeSatParametersAsString(const sat::SatParameters &parameters)
MPSolverInterface * BuildSatInterface(MPSolver *const solver)
bool ProtobufTextFormatMergeFromString(absl::string_view proto_text_string, ProtoType *proto)
int64_t coefficient
#define VLOG(verboselevel)
Definition: vlog.h:39