OR-Tools  9.6
highs_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 #if defined(USE_HIGHS)
15 
16 #include <atomic>
17 #include <cstdint>
18 #include <optional>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "absl/base/attributes.h"
24 #include "absl/status/status.h"
25 #include "absl/status/statusor.h"
26 #include "absl/strings/str_cat.h"
27 #include "absl/types/optional.h"
28 #include "google/protobuf/text_format.h"
29 #include "ortools/base/logging.h"
31 #include "ortools/linear_solver/linear_solver.pb.h"
34 
35 namespace operations_research {
36 
37 class HighsInterface : public MPSolverInterface {
38  public:
39  explicit HighsInterface(MPSolver* const solver, bool solve_as_a_mip);
40  ~HighsInterface() override;
41 
42  // ----- Solve -----
43  MPSolver::ResultStatus Solve(const MPSolverParameters& param) override;
44  std::optional<MPSolutionResponse> DirectlySolveProto(
45  const MPModelRequest& request, std::atomic<bool>* interrupt) override;
46 
47  // ----- Model modifications and extraction -----
48  void Reset() override;
49  void SetOptimizationDirection(bool maximize) override;
50  void SetVariableBounds(int index, double lb, double ub) override;
51  void SetVariableInteger(int index, bool integer) override;
52  void SetConstraintBounds(int index, double lb, double ub) override;
53  void AddRowConstraint(MPConstraint* const ct) override;
54  void AddVariable(MPVariable* const var) override;
55  void SetCoefficient(MPConstraint* const constraint,
56  const MPVariable* const variable, double new_value,
57  double old_value) override;
58  void ClearConstraint(MPConstraint* const constraint) override;
59  void SetObjectiveCoefficient(const MPVariable* const variable,
60  double coefficient) override;
61  void SetObjectiveOffset(double value) override;
62  void ClearObjective() override;
63 
64  // ------ Query statistics on the solution and the solve ------
65  int64_t iterations() const override;
66  int64_t nodes() const override;
67  MPSolver::BasisStatus row_status(int constraint_index) const override;
68  MPSolver::BasisStatus column_status(int variable_index) const override;
69 
70  // ----- Misc -----
71  bool IsContinuous() const override;
72  bool IsLP() const override;
73  bool IsMIP() const override;
74 
75  std::string SolverVersion() const override;
76  void* underlying_solver() override;
77 
78  void ExtractNewVariables() override;
79  void ExtractNewConstraints() override;
80  void ExtractObjective() override;
81 
82  void SetParameters(const MPSolverParameters& param) override;
83  void SetRelativeMipGap(double value) override;
84  void SetPrimalTolerance(double value) override;
85  void SetDualTolerance(double value) override;
86  void SetPresolveMode(int value) override;
87  void SetScalingMode(int value) override;
88  void SetLpAlgorithm(int value) override;
89  bool SetSolverSpecificParametersAsString(
90  const std::string& parameters) override;
91  absl::Status SetNumThreads(int num_threads) override;
92 
93  private:
94  void NonIncrementalChange();
95 
96  const bool solve_as_a_mip_;
97 };
98 
99 HighsInterface::HighsInterface(MPSolver* const solver, bool solve_as_a_mip)
100  : MPSolverInterface(solver), solve_as_a_mip_(solve_as_a_mip) {}
101 
102 HighsInterface::~HighsInterface() {}
103 
104 MPSolver::ResultStatus HighsInterface::Solve(const MPSolverParameters& param) {
105  // Reset extraction as this interface is not incremental yet.
106  Reset();
107  ExtractModel();
108 
109  SetParameters(param);
110  if (quiet_) {
111  // parameters_.set_verbosity_level(0);
112  } else {
113  // parameters_.set_verbosity_level(3);
114  }
115 
116  solver_->SetSolverSpecificParametersAsString(
117  solver_->solver_specific_parameter_string_);
118 
119  // Time limit.
120  if (solver_->time_limit()) {
121  VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms.";
122  // parameters_.mutable_termination_criteria()->set_time_sec_limit(
123  // static_cast<double>(solver_->time_limit()) / 1000.0);
124  }
125 
126  // Mark variables and constraints as extracted.
127  for (int i = 0; i < solver_->variables_.size(); ++i) {
128  set_variable_as_extracted(i, true);
129  }
130  for (int i = 0; i < solver_->constraints_.size(); ++i) {
131  set_constraint_as_extracted(i, true);
132  }
133 
134  MPModelProto model_proto;
135  solver_->ExportModelToProto(&model_proto);
136  MPModelRequest request;
137  *request.mutable_model() = std::move(model_proto);
138  request.set_solver_type(solve_as_a_mip_
139  ? MPModelRequest::HIGHS_MIXED_INTEGER_PROGRAMMING
140  : MPModelRequest::HIGHS_LINEAR_PROGRAMMING);
141 
142  // Set parameters.
143  absl::StatusOr<MPSolutionResponse> response = HighsSolveProto(request);
144 
145  if (!response.ok()) {
146  LOG(ERROR) << "Unexpected error solving with Highs: " << response.status();
147  return MPSolver::ABNORMAL;
148  }
149 
150  // The solution must be marked as synchronized even when no solution exists.
151  sync_status_ = SOLUTION_SYNCHRONIZED;
152  result_status_ = static_cast<MPSolver::ResultStatus>(response->status());
153  LOG_IF(ERROR, DEBUG_MODE && !response->has_solver_specific_info())
154  << *response;
155  // if (!solve_log_.ParseFromString(response->solver_specific_info())) {
156  // LOG(DFATAL) << "Unable to parse Highs's SolveLog from
157  // solver_specific_info";
158  // }
159 
160  if (response->status() == MPSOLVER_FEASIBLE ||
161  response->status() == MPSOLVER_OPTIMAL) {
162  const absl::Status result = solver_->LoadSolutionFromProto(*response);
163  if (!result.ok()) {
164  LOG(ERROR) << "LoadSolutionFromProto failed: " << result;
165  }
166  }
167 
168  return result_status_;
169 }
170 
171 std::optional<MPSolutionResponse> HighsInterface::DirectlySolveProto(
172  const MPModelRequest& request, std::atomic<bool>* interrupt) {
173  if (interrupt) return std::nullopt;
174  absl::StatusOr<MPSolutionResponse> response = HighsSolveProto(request);
175 
176  if (!response.ok()) {
177  LOG(ERROR) << "Unexpected error solving with Highs: " << response.status();
178  MPSolutionResponse error_response;
179  error_response.set_status(MPSolverResponseStatus::MPSOLVER_ABNORMAL);
180  error_response.set_status_str(response.status().ToString());
181  return error_response;
182  }
183 
184  return *response;
185 }
186 
187 void HighsInterface::Reset() { ResetExtractionInformation(); }
188 
189 void HighsInterface::SetOptimizationDirection(bool maximize) {
190  NonIncrementalChange();
191 }
192 
193 void HighsInterface::SetVariableBounds(int index, double lb, double ub) {
194  NonIncrementalChange();
195 }
196 
197 void HighsInterface::SetVariableInteger(int index, bool integer) {
198  NonIncrementalChange();
199 }
200 
201 void HighsInterface::SetConstraintBounds(int index, double lb, double ub) {
202  NonIncrementalChange();
203 }
204 
205 void HighsInterface::AddRowConstraint(MPConstraint* const ct) {
206  NonIncrementalChange();
207 }
208 
209 void HighsInterface::AddVariable(MPVariable* const var) {
210  NonIncrementalChange();
211 }
212 
213 void HighsInterface::SetCoefficient(MPConstraint* const constraint,
214  const MPVariable* const variable,
215  double new_value, double old_value) {
216  NonIncrementalChange();
217 }
218 
219 void HighsInterface::ClearConstraint(MPConstraint* const constraint) {
220  NonIncrementalChange();
221 }
222 
223 void HighsInterface::SetObjectiveCoefficient(const MPVariable* const variable,
224  double coefficient) {
225  NonIncrementalChange();
226 }
227 
228 void HighsInterface::SetObjectiveOffset(double value) {
229  NonIncrementalChange();
230 }
231 
232 void HighsInterface::ClearObjective() { NonIncrementalChange(); }
233 
234 int64_t HighsInterface::iterations() const {
235  return 0; // FIXME.
236 }
237 
238 int64_t HighsInterface::nodes() const {
239  LOG(DFATAL) << "Number of nodes only available for discrete problems";
240  return MPSolverInterface::kUnknownNumberOfNodes;
241 }
242 
243 MPSolver::BasisStatus HighsInterface::row_status(int constraint_index) const {
244  // TODO(user): While basis status isn't well defined for PDLP, we could
245  // guess statuses that might be useful.
246  return MPSolver::BasisStatus::FREE;
247 }
248 
249 MPSolver::BasisStatus HighsInterface::column_status(int variable_index) const {
250  // TODO(user): While basis status isn't well defined for PDLP, we could
251  // guess statuses that might be useful.
252  return MPSolver::BasisStatus::FREE;
253 }
254 
255 bool HighsInterface::IsContinuous() const { return true; }
256 
257 bool HighsInterface::IsLP() const { return true; }
258 
259 bool HighsInterface::IsMIP() const { return solve_as_a_mip_; }
260 
261 std::string HighsInterface::SolverVersion() const { return "PDLP Solver"; }
262 
263 // TODO(user): Consider returning the SolveLog here, as it could be essential
264 // for interpreting the PDLP solution.
265 void* HighsInterface::underlying_solver() { return nullptr; }
266 
267 void HighsInterface::ExtractNewVariables() { NonIncrementalChange(); }
268 
269 void HighsInterface::ExtractNewConstraints() { NonIncrementalChange(); }
270 
271 void HighsInterface::ExtractObjective() { NonIncrementalChange(); }
272 
273 void HighsInterface::SetParameters(const MPSolverParameters& param) {
274  SetCommonParameters(param);
275 }
276 
277 absl::Status HighsInterface::SetNumThreads(int num_threads) {
278  if (num_threads < 1) {
279  return absl::InvalidArgumentError(
280  absl::StrCat("Invalid number of threads: ", num_threads));
281  }
282  // parameters_.set_num_threads(num_threads);
283  return absl::OkStatus();
284 }
285 
286 // These have no effect. Use SetSolverSpecificParametersAsString instead.
287 void HighsInterface::SetPrimalTolerance(double value) {}
288 void HighsInterface::SetDualTolerance(double value) {}
289 void HighsInterface::SetScalingMode(int value) {}
290 void HighsInterface::SetLpAlgorithm(int value) {}
291 void HighsInterface::SetRelativeMipGap(double value) {}
292 void HighsInterface::SetPresolveMode(int value) {}
293 
294 bool HighsInterface::SetSolverSpecificParametersAsString(
295  const std::string& parameters) {
296  // return ProtobufTextFormatMergeFromString(parameters, &parameters_);
297  return false;
298 }
299 
300 void HighsInterface::NonIncrementalChange() {
301  // The current implementation is not incremental.
302  sync_status_ = MUST_RELOAD;
303 }
304 
305 // Register PDLP in the global linear solver factory.
306 MPSolverInterface* BuildHighsInterface(bool mip, MPSolver* const solver) {
307  return new HighsInterface(solver, mip);
308 }
309 
310 } // namespace operations_research
311 #endif // #if defined(USE_HIGHS)
ResultStatus
The status of solving the problem.
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
SatParameters parameters
CpModelProto const * model_proto
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
const bool DEBUG_MODE
Definition: macros.h:24
absl::StatusOr< SolveResult > Solve(const Model &model, const SolverType solver_type, const SolveArguments &solve_args, const SolverInitArguments &init_args)
Collection of objects used to extend the Constraint Solver library.
absl::StatusOr< MPSolutionResponse > HighsSolveProto(MPModelRequest request)
int64_t coefficient
int nodes
#define VLOG(verboselevel)
Definition: vlog.h:39