lpinterface
 All Classes Namespaces Files Functions Variables Enumerations Enumerator
lputil_gurobi.hpp
1 #ifndef LPINTERFACE_LPUTIL_GUROBI_H
2 #define LPINTERFACE_LPUTIL_GUROBI_H
3 
4 #include "gurobi_c.h"
5 #include "lpinterface/errors.hpp"
6 
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <cassert>
10 
11 namespace lpint {
12 
13 namespace detail {
14 
15 inline GRBenv* create_gurobi_env() {
16  GRBenv* env;
17  int saved_stdout = dup(1);
18  close(1);
19  int new_stdout = open("/dev/null", O_WRONLY);
20  if (new_stdout != 1) {
21  throw std::runtime_error("Failed to redirect stdout");
22  }
23 
24  int err = GRBloadenv(&env, "");
25 
26  close(new_stdout);
27  new_stdout = dup(saved_stdout);
28  if (new_stdout != 1) {
29  throw std::runtime_error("Failed to redirect stdout");
30  }
31  close(saved_stdout);
32 
33  if (err) {
34  throw GurobiException(err, GRBgeterrormsg(env));
35  }
36  return env;
37 }
38 
39 inline GRBmodel* create_gurobi_model(GRBenv* env) {
40  GRBmodel* model;
41  if (int err = GRBnewmodel(env, &model, nullptr, 0, nullptr, nullptr, nullptr,
42  nullptr, nullptr)) {
43  throw GurobiException(err, GRBgeterrormsg(env));
44  }
45  return model;
46 }
47 
48 template <class F, class... Args>
49 inline void gurobi_function_checked(F f, GRBmodel* g, Args&&... args) {
50  if (int error = f(g, std::forward<Args>(args)...)) {
51  throw GurobiException(error, GRBgeterrormsg(GRBgetenv(g)));
52  }
53 }
54 
55 template <class F, class... Args>
56 inline void gurobi_function_checked(F f, GRBenv* g, Args&&... args) {
57  if (int error = f(g, std::forward<Args>(args)...)) {
58  throw GurobiException(error, GRBgeterrormsg(g));
59  }
60 }
61 
62 } // namespace detail
63 
64 } // namespace lpint
65 
66 #endif // LPINTERFACE_LPUTIL_GUROBI_H