Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
highs_interface.cc
Go to the documentation of this file.
1// Copyright 2010-2025 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 <string>
19#include <utility>
20#include <vector>
21
22#include "absl/base/attributes.h"
23#include "absl/log/check.h"
24#include "absl/status/status.h"
25#include "absl/status/statusor.h"
26#include "absl/strings/str_cat.h"
29#include "ortools/linear_solver/linear_solver.pb.h"
33
34namespace operations_research {
35
37 public:
38 explicit HighsInterface(MPSolver* solver, bool solve_as_a_mip);
39 ~HighsInterface() override;
40
41 // ----- Solve -----
42 MPSolver::ResultStatus Solve(const MPSolverParameters& param) override;
43
44 // ----- Directly solve proto is supported without interrupt ---
45 bool SupportsDirectlySolveProto(std::atomic<bool>* interrupt) const override {
46 return interrupt == nullptr;
47 }
49 std::atomic<bool>* interrupt) override {
50 DCHECK_EQ(interrupt, nullptr);
51 const bool log_error = request->enable_internal_solver_output();
53 log_error, HighsSolveProto(std::move(request)));
54 }
55
56 // ----- Model modifications and extraction -----
57 void Reset() override;
58 void SetOptimizationDirection(bool maximize) override;
59 void SetVariableBounds(int index, double lb, double ub) override;
60 void SetVariableInteger(int index, bool integer) override;
61 void SetConstraintBounds(int index, double lb, double ub) override;
62 void AddRowConstraint(MPConstraint* ct) override;
63 void AddVariable(MPVariable* var) override;
64 void SetCoefficient(MPConstraint* constraint, const MPVariable* variable,
65 double new_value, double old_value) override;
66 void ClearConstraint(MPConstraint* constraint) override;
67 void SetObjectiveCoefficient(const MPVariable* variable,
68 double coefficient) override;
69 void SetObjectiveOffset(double value) override;
70 void ClearObjective() override;
71
72 // ------ Query statistics on the solution and the solve ------
73 int64_t iterations() const override;
74 int64_t nodes() const override;
75 MPSolver::BasisStatus row_status(int constraint_index) const override;
76 MPSolver::BasisStatus column_status(int variable_index) const override;
77
78 // ----- Misc -----
79 bool IsContinuous() const override;
80 bool IsLP() const override;
81 bool IsMIP() const override;
82
83 std::string SolverVersion() const override;
84 void* underlying_solver() override;
85
86 void ExtractNewVariables() override;
87 void ExtractNewConstraints() override;
88 void ExtractObjective() override;
89
90 void SetParameters(const MPSolverParameters& param) override;
91 void SetRelativeMipGap(double value) override;
92 void SetPrimalTolerance(double value) override;
93 void SetDualTolerance(double value) override;
94 void SetPresolveMode(int value) override;
95 void SetScalingMode(int value) override;
96 void SetLpAlgorithm(int value) override;
98 const std::string& parameters) override;
99 absl::Status SetNumThreads(int num_threads) override;
100
101 private:
102 void NonIncrementalChange();
103
104 const bool solve_as_a_mip_;
105};
106
107HighsInterface::HighsInterface(MPSolver* const solver, bool solve_as_a_mip)
108 : MPSolverInterface(solver), solve_as_a_mip_(solve_as_a_mip) {}
109
111
113 // Reset extraction as this interface is not incremental yet.
114 Reset();
115 ExtractModel();
116
117 SetParameters(param);
118 if (quiet_) {
119 // parameters_.set_verbosity_level(0);
120 } else {
121 // parameters_.set_verbosity_level(3);
122 }
123
124 solver_->SetSolverSpecificParametersAsString(
125 solver_->solver_specific_parameter_string_);
126
127 // Time limit.
128 if (solver_->time_limit()) {
129 VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms.";
130 // parameters_.mutable_termination_criteria()->set_time_sec_limit(
131 // static_cast<double>(solver_->time_limit()) / 1000.0);
132 }
133
134 // Mark variables and constraints as extracted.
135 for (int i = 0; i < solver_->variables_.size(); ++i) {
137 }
138 for (int i = 0; i < solver_->constraints_.size(); ++i) {
140 }
141
142 MPModelProto model_proto;
143 solver_->ExportModelToProto(&model_proto);
144 MPModelRequest request;
145 *request.mutable_model() = std::move(model_proto);
146 request.set_solver_type(solve_as_a_mip_
147 ? MPModelRequest::HIGHS_MIXED_INTEGER_PROGRAMMING
148 : MPModelRequest::HIGHS_LINEAR_PROGRAMMING);
149
150 // Set parameters.
151 absl::StatusOr<MPSolutionResponse> response =
152 HighsSolveProto(std::move(request));
153
154 if (!response.ok()) {
155 LOG(ERROR) << "Unexpected error solving with Highs: " << response.status();
156 return MPSolver::ABNORMAL;
157 }
158
159 // The solution must be marked as synchronized even when no solution exists.
161 result_status_ = static_cast<MPSolver::ResultStatus>(response->status());
162
163 if (response->status() == MPSOLVER_FEASIBLE ||
164 response->status() == MPSOLVER_OPTIMAL) {
165 const absl::Status result = solver_->LoadSolutionFromProto(*response);
166 if (!result.ok()) {
167 LOG(ERROR) << "LoadSolutionFromProto failed: " << result;
168 }
169 }
170
171 return result_status_;
172}
173
175
177 NonIncrementalChange();
178}
179
180void HighsInterface::SetVariableBounds(int index, double lb, double ub) {
181 NonIncrementalChange();
182}
183
184void HighsInterface::SetVariableInteger(int index, bool integer) {
185 NonIncrementalChange();
186}
187
188void HighsInterface::SetConstraintBounds(int index, double lb, double ub) {
189 NonIncrementalChange();
190}
191
193 NonIncrementalChange();
194}
195
197 NonIncrementalChange();
198}
199
201 const MPVariable* const variable,
202 double new_value, double old_value) {
203 NonIncrementalChange();
204}
205
207 NonIncrementalChange();
208}
209
211 double coefficient) {
212 NonIncrementalChange();
213}
214
216 NonIncrementalChange();
217}
218
219void HighsInterface::ClearObjective() { NonIncrementalChange(); }
220
222 return 0; // FIXME.
223}
224
225int64_t HighsInterface::nodes() const {
226 LOG(DFATAL) << "Number of nodes only available for discrete problems";
228}
229
231 // TODO(user): While basis status isn't well defined for PDLP, we could
232 // guess statuses that might be useful.
234}
235
237 // TODO(user): While basis status isn't well defined for PDLP, we could
238 // guess statuses that might be useful.
240}
241
242bool HighsInterface::IsContinuous() const { return true; }
243
244bool HighsInterface::IsLP() const { return true; }
245
246bool HighsInterface::IsMIP() const { return solve_as_a_mip_; }
247
248std::string HighsInterface::SolverVersion() const { return "PDLP Solver"; }
249
250// TODO(user): Consider returning the SolveLog here, as it could be essential
251// for interpreting the PDLP solution.
252void* HighsInterface::underlying_solver() { return nullptr; }
253
254void HighsInterface::ExtractNewVariables() { NonIncrementalChange(); }
255
256void HighsInterface::ExtractNewConstraints() { NonIncrementalChange(); }
257
258void HighsInterface::ExtractObjective() { NonIncrementalChange(); }
259
263
264absl::Status HighsInterface::SetNumThreads(int num_threads) {
265 if (num_threads < 1) {
266 return absl::InvalidArgumentError(
267 absl::StrCat("Invalid number of threads: ", num_threads));
268 }
269 // parameters_.set_num_threads(num_threads);
270 return absl::OkStatus();
271}
272
273// These have no effect. Use SetSolverSpecificParametersAsString instead.
280
282 const std::string& parameters) {
283 // return ProtobufTextFormatMergeFromString(parameters, &parameters_);
284 return false;
285}
286
287void HighsInterface::NonIncrementalChange() {
288 // The current implementation is not incremental.
290}
291
292// Register PDLP in the global linear solver factory.
294 return new HighsInterface(solver, mip);
295}
296
297} // namespace operations_research
298#endif // #if defined(USE_HIGHS)
MPSolver::BasisStatus row_status(int constraint_index) const override
Returns the basis status of a row.
void SetConstraintBounds(int index, double lb, double ub) override
Modify bounds of an extracted variable.
absl::Status SetNumThreads(int num_threads) override
Sets the number of threads to be used by the solver.
bool IsContinuous() const override
--— Misc --—
void AddVariable(MPVariable *var) override
Add a variable.
void SetObjectiveCoefficient(const MPVariable *variable, double coefficient) override
Changes a coefficient in the linear objective.
bool IsMIP() const override
Returns true if the problem is discrete and linear.
bool SupportsDirectlySolveProto(std::atomic< bool > *interrupt) const override
--— Directly solve proto is supported without interrupt —
bool IsLP() const override
Returns true if the problem is continuous and linear.
MPSolver::ResultStatus Solve(const MPSolverParameters &param) override
--— Solve --—
void SetCoefficient(MPConstraint *constraint, const MPVariable *variable, double new_value, double old_value) override
Changes a coefficient in a constraint.
MPSolutionResponse DirectlySolveProto(LazyMutableCopy< MPModelRequest > request, std::atomic< bool > *interrupt) override
bool SetSolverSpecificParametersAsString(const std::string &parameters) override
int64_t iterations() const override
---— Query statistics on the solution and the solve ---—
void SetPresolveMode(int value) override
void SetVariableInteger(int index, bool integer) override
Modifies integrality of an extracted variable.
void SetScalingMode(int value) override
Sets the scaling mode.
void SetVariableBounds(int index, double lb, double ub) override
Modifies bounds of an extracted variable.
std::string SolverVersion() const override
Returns a string describing the underlying solver and its version.
MPSolver::BasisStatus column_status(int variable_index) const override
Returns the basis status of a constraint.
void SetDualTolerance(double value) override
void SetRelativeMipGap(double value) override
Sets each parameter in the underlying solver.
void ClearObjective() override
Clears the objective from all its terms.
HighsInterface(MPSolver *solver, bool solve_as_a_mip)
void SetParameters(const MPSolverParameters &param) override
Sets all parameters in the underlying solver.
void Reset() override
--— Model modifications and extraction --—
void ExtractNewVariables() override
Extracts the variables that have not been extracted yet.
void AddRowConstraint(MPConstraint *ct) override
Adds a linear constraint.
void SetOptimizationDirection(bool maximize) override
Sets the optimization direction (min/max).
void SetPrimalTolerance(double value) override
These have no effect. Use SetSolverSpecificParametersAsString instead.
void ClearConstraint(MPConstraint *constraint) override
Clears a constraint from all its terms.
void ExtractObjective() override
Extracts the objective.
void ExtractNewConstraints() override
Extracts the constraints that have not been extracted yet.
void SetLpAlgorithm(int value) override
void SetObjectiveOffset(double value) override
Changes the constant term in the linear objective.
void set_variable_as_extracted(int var_index, bool extracted)
friend class MPConstraint
To access the maximize_ bool and the MPSolver.
void set_constraint_as_extracted(int ct_index, bool extracted)
void ResetExtractionInformation()
Resets the extraction information.
static constexpr int64_t kUnknownNumberOfNodes
void ExtractModel()
Extracts model stored in MPSolver.
bool quiet_
Boolean indicator for the verbosity of the solver output.
void SetCommonParameters(const MPSolverParameters &param)
Sets parameters common to LP and MIP in the underlying solver.
SynchronizationStatus sync_status_
Indicates whether the model and the solution are synchronized.
@ ABNORMAL
abnormal, i.e., error of some kind.
The class for variables of a Mathematical Programming (MP) model.
In SWIG mode, we don't want anything besides these top-level includes.
MPSolverInterface * BuildHighsInterface(bool mip, MPSolver *const solver)
Register PDLP in the global linear solver factory.
absl::StatusOr< MPSolutionResponse > HighsSolveProto(LazyMutableCopy< MPModelRequest > request)
Solve the input MIP model with the HIGHS solver.
MPSolutionResponse ConvertStatusOrMPSolutionResponse(bool log_error, absl::StatusOr< MPSolutionResponse > response)
Definition proto_utils.h:37