GurobiHelper.cc 5.46 KB
Newer Older
David Bommes's avatar
David Bommes committed
1
2
3
4
5
6
7
8
9
/*
 * GurobiHelper.cc
 *
 *  Created on: Jan 4, 2012
 *      Author: ebke
 */

#include "GurobiHelper.hh"

David Bommes's avatar
David Bommes committed
10
#if (COMISO_GUROBI_AVAILABLE && COMISO_BOOST_AVAILABLE)
David Bommes's avatar
David Bommes committed
11

12
#if (COMISO_QT_AVAILABLE)
13
14
15
16
  #include <QTemporaryFile>
  #include <QFileInfo>
#endif

David Bommes's avatar
David Bommes committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <boost/filesystem.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>

#define OUTPUT_UNCOMPRESSED_WITH_CONSTANT_COMMENT 0
#define OUTPUT_CONSTANT_AS_CONT 1

namespace COMISO {

/**
 * Helper class that ensures exception safe deletion
 * of a temporary file.
 */
class TempFileGuard {
    public:
        TempFileGuard(const std::string &_filePath) : filePath_(_filePath) {
        }

        ~TempFileGuard() {
            if (boost::filesystem::exists(filePath_))
                boost::filesystem::remove(filePath_);
        }

        const boost::filesystem::path &filePath() const { return filePath_; };

    private:
        boost::filesystem::path filePath_;
};

static void moveConstantTermIntoConstrainedVariable(GRBModel &model) {
    const double constantTerm = model.getObjective().getLinExpr().getConstant();
    //tmpModel.getObjective().addConstant(-constantTerm);
    model.getObjective() -= constantTerm;
#if OUTPUT_CONSTANT_AS_CONT
57
    model.addVar(constantTerm, constantTerm, 1, GRB_CONTINUOUS, "MIQ_synthetic_constant");
David Bommes's avatar
David Bommes committed
58
#else
59
    model.addVar(1, 1, constantTerm, GRB_INTEGER, "MIQ_synthetic_constant");
David Bommes's avatar
David Bommes committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#endif
}

static void copyFile(const char *from, const char *to) {
    FILE *inF = fopen(from, "r");
    FILE *outF = fopen(to, "w");

    const int bufsize = 4096;
    unsigned char buffer[bufsize];

    do {
        size_t readBytes = fread(buffer, 1, bufsize, inF);
        fwrite(buffer, 1, readBytes, outF);
    } while(!feof(inF));

    fclose(inF);
    fclose(outF);
}

/**
 * WARNING: Never call outputModelToMpsGz and importInitialSolutionIntoModel
 * on the same model. Both try to move the constant term into a variable and
 * consequently, the second attempt to do so will fail.
 */
void GurobiHelper::outputModelToMpsGz(GRBModel &model, const std::string &problem_output_path_) {
#if OUTPUT_UNCOMPRESSED_WITH_CONSTANT_COMMENT
    boost::scoped_ptr<TempFileGuard> tempFileGuard;
    {
88
#if (COMISO_QT_AVAILABLE)
David Bommes's avatar
David Bommes committed
89
90
91
92
93
94
95
96
        QTemporaryFile tempFile("XXXXXX.mps");
        tempFile.setAutoRemove(false);
        tempFile.open();

        // In order to minimize the likelihood of race conditions,
        // we initialize tempFileGuard right here.
        tempFileGuard.reset(new TempFileGuard(QFileInfo(tempFile).absoluteFilePath().toStdString()));
        tempFile.close();
97
#endif
David Bommes's avatar
David Bommes committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    }

    const std::string fileName = tempFileGuard->filePath().string();

    model.write(fileName);
    const double constantTerm = model.getObjective().getLinExpr().getConstant();

    FILE *inF = fopen(fileName.c_str(), "r");
    FILE *outF = fopen(problem_output_path_.c_str(), "w");

    fprintf(outF, "* Constant Term: %.16e\n", constantTerm);
    const int bufsize = 4096;
    unsigned char buffer[bufsize];
    int readBytes;
    do {
        readBytes = fread(buffer, 1, bufsize, inF);
        fwrite(buffer, 1, readBytes, outF);
    } while(!feof(inF));
    fclose(inF);
    fclose(outF);
#else
    GRBModel tmpModel(model);

    moveConstantTermIntoConstrainedVariable(tmpModel);

    tmpModel.update();
    tmpModel.write(problem_output_path_);
#endif
}

/**
 * WARNING: Never call outputModelToMpsGz and importInitialSolutionIntoModel
 * on the same model. Both try to move the constant term into a variable and
 * consequently, the second attempt to do so will fail.
 */
void GurobiHelper::importInitialSolutionIntoModel(GRBModel &model, const std::string &solution_path_) {
    boost::scoped_ptr<TempFileGuard> tempFileGuard;
    {
136
#if (COMISO_QT_AVAILABLE)
David Bommes's avatar
David Bommes committed
137
138
139
140
141
142
143
144
        QTemporaryFile tempFile("XXXXXX.mst");
        tempFile.setAutoRemove(false);
        tempFile.open();

        // In order to minimize the likelihood of race conditions,
        // we initialize tempFileGuard right here.
        tempFileGuard.reset(new TempFileGuard(QFileInfo(tempFile).absoluteFilePath().toStdString()));
        tempFile.close();
145
#endif
David Bommes's avatar
David Bommes committed
146
147
148
149
150
151
152
153
    }

    const std::string fileName = tempFileGuard->filePath().string();

    copyFile(solution_path_.c_str(), fileName.c_str());

    //moveConstantTermIntoConstrainedVariable(model);
    const double constantTerm = model.getObjective().getLinExpr().getConstant();
154
    model.addVar(constantTerm, constantTerm, 0, GRB_CONTINUOUS, "MIQ_synthetic_constant");
David Bommes's avatar
David Bommes committed
155
156
157
158
159
160
161
162
163
164
165
166

    model.update();
    model.read(fileName);
    model.update();
}

void GurobiHelper::readSolutionVectorFromSOL(std::vector<double> &out_solution_, const std::string &fileName_) {
    std::ifstream solFile(fileName_.c_str());
    //if (!solFile.good())
    //    throw std::runtime_error("Unable to open file \"" + fileName + "\".");

    static const boost::regex commentRe("\\s*#", boost::regex_constants::perl);
167
    static const boost::regex variableRe("\\s*(\\S+)\\s+([-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?)", boost::regex_constants::perl);
David Bommes's avatar
David Bommes committed
168
169
170
171
172
173

    std::string line;
    while (solFile) {
        std::getline(solFile, line);
        if (boost::regex_search(line, commentRe, boost::match_continuous)) continue;
        boost::smatch match;
174
175
        if (boost::regex_search(line, match, variableRe, boost::match_continuous) && match[1] != "MIQ_synthetic_constant") {
            out_solution_.push_back(boost::lexical_cast<double>(match[2]));
David Bommes's avatar
David Bommes committed
176
177
178
179
180
181
182
        }
    }
}

} /* namespace COMISO */

#endif