-
Notifications
You must be signed in to change notification settings - Fork 1
/
MOSPOOLS.hpp
executable file
·417 lines (342 loc) · 12 KB
/
MOSPOOLS.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
57
58
59
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
88
89
90
91
92
93
94
95
96
97
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#ifndef MOSPOOLS_HPP_
#define MOSPOOLS_HPP_
#include <ilcplex/ilocplex.h>
#include <ilcplex/cplexx.h>
#include <ilcplex/ilocplexi.h>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream> // std::ifstream
#include <sstream>
#include "OptFrame/RandGen.hpp"
#include "OptFrame/Timer.hpp"
#include "OptFrame/Util/printable.h"
#include "OptFrame/MultiObjSearch.hpp"
#include "OptFrame/Util/MOMetrics.hpp"
#include <vector>
ILOSTLBEGIN
using namespace std;
using namespace optframe;
struct MIPStartSolution
{
vector<double> objValues;
string filename;
MIPStartSolution(vector<double> _obj, string _filename) :
objValues(_obj), filename(_filename)
{
}
};
class SPOOLStruct
{
public:
MOMETRICS<int> moMetrics;
vector<ParetoFitness > popObjValues;
vector<ParetoFitness > paretoSET;
vector<double> referencePointsHV;
vector<double> utopicSol;
SPOOLStruct(MOMETRICS<int> _moMetrics, vector<double> _referencePointsHV, vector<double> _utopicSol) :
moMetrics(_moMetrics), referencePointsHV(_referencePointsHV), utopicSol(_utopicSol)
{
}
virtual ~SPOOLStruct()
{
}
vector<ParetoFitness> getPopObjValues()
{
return popObjValues;
}
void updatedParetoSet()
{
paretoSET.clear();
paretoSET = moMetrics.createParetoSetAndReturnEvaluations(popObjValues);
}
vector<ParetoFitness> getParetoSet()
{
//Reset pareto set and get if from current obj values
updatedParetoSet();
return paretoSET;
}
virtual vector<double> addSolToPop(const IloNumArray& vals, const IloNumVarArray& var, int nOptObj)
{
vector<double> solObj;
for (int o = 0; o < nOptObj; o++)
{
solObj.push_back(vals[o]);
cout << "obj(" << o + 1 << "): " << solObj[o] << "\t";
}
// cout << "obj(" << 7 << "): " << finalOF[7] << "\t"; //print excess auxiliary variable
cout << "\n";
popObjValues.push_back(solObj);
return solObj;
}
int getPopSize()
{
return popObjValues.size();
}
double getParetoHyperVolume()
{
return moMetrics.hipervolumeWithExecRequested(paretoSET, referencePointsHV, true);
}
double getParetoDeltaMetric()
{
return moMetrics.deltaMetric(paretoSET, referencePointsHV, true);
}
virtual void exportParetoFrontValues(string filename, int nMILPProblems, int tLim, int nOptObj, double tNow){
stringstream ss;
ss << "./ResultadosFronteiras/" << filename << "NExec" << nMILPProblems << "TLimm" << tLim; // << "-bestMIPStart";
cout << "Writing PF at file: " << ss.str() << "..." << endl;
cout << "WARNING: Make sure that this aforementioned folder exists!" << endl;
FILE* fFronteiraPareto = fopen(ss.str().c_str(), "w");
int nParetoInd = paretoSET.size();
for (int nS = 0; nS < nParetoInd; nS++)
{
for (int nE = 0; nE < nOptObj; nE++)
{
fprintf(fFronteiraPareto, "%.5f\t", paretoSET[nS][nE]);
}
fprintf(fFronteiraPareto, "\n");
}
fprintf(fFronteiraPareto, "%.5f \n", tNow);
fprintf(fFronteiraPareto, "hv: %.5f \n", getParetoHyperVolume());
fprintf(fFronteiraPareto, "delta: %.5f \n", getParetoDeltaMetric());
fclose(fFronteiraPareto);
cout << "File wrote with success!" << endl;
}
};
class cplexMOPoolSearch
{
public:
RandGen& rg;
SPOOLStruct& spoolStruct;
cplexMOPoolSearch(RandGen& _rg, SPOOLStruct& _spoolStruct) :
rg(_rg), spoolStruct(_spoolStruct)
{
}
~cplexMOPoolSearch()
{
}
vector<vector<double> > exec(string filename, bool mipStart, vector<vector<double> > vMILPCoefs, int tLim, int nOptObj, int nCriteria, int maxTriesWithTLimUntilFirstFeasible)
{
cout << "===================================== " << endl;
cout << "Exec CPLEX MO Pool Search Matheuristic!" << endl;
cout << "Number of objectives functions: " << nOptObj << endl;
int nMILPProblems = vMILPCoefs.size();
cout << "nMILPProblems = " << nMILPProblems << endl;
vector<ParetoFitness> paretoSETEvaluationsOnly;
IloEnv env;
try
{
Timer tTotal;
IloCplex cplex(env);
IloModel model(env);
IloObjective obj;
IloNumVarArray var(env);
IloRangeArray rng(env);
string modelLPAdress = "./LP/" + filename + ".lp";
cout << "solving: " << modelLPAdress << endl;
cplex.importModel(model, modelLPAdress.c_str(), obj, var, rng);
cplex.setParam(cplex.TiLim, tLim);
vector<MIPStartSolution> poolMIPStart;
//=========================================================================================
// Calling MILP problems
for (int milpProblems = 0; milpProblems < nMILPProblems; milpProblems++)
{
cout << "=====================================\n";
cout << "Creating MILP model " << milpProblems << "/" << nMILPProblems << " with: \n";
for (int o = 0; o < nOptObj; o++)
cout << "lambda(" << o + 1 << "): " << vMILPCoefs[milpProblems][o] << "\t";
cout << "\n";
for (int o = 0; o < nOptObj; o++)
obj.setLinearCoef(var[o], vMILPCoefs[milpProblems][o]);
cout << obj << endl;
// getchar();
cplex.extract(model);
//Option that read MST of the the previous solves MILP problem -- TODO
//Maybe a list of MST can be passed as optional vector of the exec, with path directing to previous MST
//Which may be repaired
//cplex.readMIPStarts("tempMIPStart/mst0.mst");
int totalNMIPStartSolutions = poolMIPStart.size();
// =====================================================
//Read the file with the best MIP start // TODO -- for minimization problems - otherwise, it will get the worse one
if (totalNMIPStartSolutions > 0)
{
cout << "Pool of MIP start solution has: " << totalNMIPStartSolutions << " possibilities" << endl;
double bestFO;
int bestMIPStartIndex; //
//Selecting best MIP start for the current weights
for (int mipS = 0; mipS < totalNMIPStartSolutions; mipS++)
{
double currentMILPObj = 0;
for (int o = 0; o < nOptObj; o++)
currentMILPObj += vMILPCoefs[milpProblems][o] * poolMIPStart[mipS].objValues[o];
if (mipS == 0)
{
bestFO = currentMILPObj; //Initialize bestFO with the first value
bestMIPStartIndex = mipS;
}
if (currentMILPObj < bestFO)
{
bestFO = currentMILPObj;
bestMIPStartIndex = mipS;
}
}
cout << "best MIPStart solution is: " << bestFO << "\t index:" << bestMIPStartIndex << endl << endl;
cplex.readMIPStarts(poolMIPStart[bestMIPStartIndex].filename.c_str());
}
// =====================================================
//======================================================
//Calls Cplex Optimization
int nCplexPoolOfSolutions = 0;
IloBool solveBool;
if (milpProblems == 0)
{
//In the first optimization, tries several times until find first feasible
solveBool = cplex.solve();
nCplexPoolOfSolutions = cplex.getSolnPoolNsolns();
int nTries = 1;
while ((nTries < maxTriesWithTLimUntilFirstFeasible) && nCplexPoolOfSolutions == 0)
{
cout << "\n Any feasible solution was in " << nTries << "/" << maxTriesWithTLimUntilFirstFeasible << " tries! \n \n";
solveBool = cplex.solve();
nCplexPoolOfSolutions = cplex.getSolnPoolNsolns();
nTries++;
}
}
else
{
solveBool = cplex.solve();
nCplexPoolOfSolutions = cplex.getSolnPoolNsolns();
}
//======================================================
if (!solveBool)
{
// env.error() << "Failed to optimize LP" << endl;
// throw(-1);
cout << "=====================================\n";
cout << "Any solution was in the current iteration! The following parameters were used: \n";
for (int o = 0; o < nOptObj; o++)
cout << "lambda(" << o + 1 << "): " << vMILPCoefs[milpProblems][o] << "\t";
cout << "\n";
cout << "\t cplex.TiLim: " << tLim << "\n";
cout << "=====================================\n";
}
else
{
cout << "=====================================\n";
cout << "Solved with sucess! \n";
cout << nCplexPoolOfSolutions << " solutions were obtained! \n";
cout << "=====================================\n\n";
}
IloNumArray vals(env);
if (nCplexPoolOfSolutions > 0)
for (int nS = 0; nS < nCplexPoolOfSolutions; nS++)
{
cout << "=====================================\n";
cout << "Extracting solution: " << nS + 1 << "/" << nCplexPoolOfSolutions << endl;
//Extracting values from each solution
cplex.getValues(vals, var, nS);
vector<double> solObj = spoolStruct.addSolToPop(vals, var, nOptObj);
//==============================================
// Write MST solutions in different files
if (mipStart)
{
cout << "Writing MST solution...." << endl;
stringstream mstFilename;
mstFilename << "./tempMIPStart/mst" << poolMIPStart.size() << ".mst";
// cplex.writeMIPStarts(mstFilename.str().c_str(), nS, nCplexPoolOfSolutions);
cplex.writeMIPStarts(mstFilename.str().c_str(), nS);
MIPStartSolution mipStartSol(solObj, mstFilename.str());
poolMIPStart.push_back(mipStartSol);
cout << "MST Saved in file with sucess!" << endl;
//(WriteLevel, CPX_PARAM_WRITELEVEL) //0 to 4
//CPX_WRITELEVEL_ALLVARS, CPX_WRITELEVEL_DISCRETEVARS, CPX_WRITELEVEL_NONZEROVARS,CPX_WRITELEVEL_NONZERODISCRETEVARS
}
//==============================================
cout << "Solution: " << nS + 1 << "/" << nCplexPoolOfSolutions << " has been extracted with success and added to the population" << endl;
cout << "=====================================\n";
}
cout << "=====================================\n\n";
}
// All problem were called!
//=========================================================================================
int nObtainedSolutions = spoolStruct.getPopSize();
double timeeSpent = tTotal.now();
cout << "Total time spent: " << timeeSpent << endl;
cout << "Size of the obtained population:" << nObtainedSolutions << endl;
if (nObtainedSolutions > 0)
{
cout << "Printing obtained population of solutions with size: " << nObtainedSolutions << endl;
cout << spoolStruct.getPopObjValues() << endl;
paretoSETEvaluationsOnly = spoolStruct.getParetoSet();
cout << "Printing Pareto Front of size: " << paretoSETEvaluationsOnly.size() << endl;
cout << paretoSETEvaluationsOnly << endl;
spoolStruct.exportParetoFrontValues(filename,nMILPProblems,tLim,nOptObj,timeeSpent);
}
else
{
cout << "Any solution was obtained among the: " << nMILPProblems << " MILP optimizations with different weighted-sum!" << endl;
}
//cout << vals[vals.getSize()] << endl;
try
{ // basis may not exist
IloCplex::BasisStatusArray cstat(env);
cplex.getBasisStatuses(cstat, var);
env.out() << "Basis statuses = " << cstat << "\n";
} catch (...)
{
}
//env.out() << "Maximum bound violation = " << cplex.getQuality(IloCplex::MaxPrimalInfeas) << endl;
} catch (IloException& e)
{
cerr << "Concert exception caught: " << e << endl;
} catch (...)
{
cerr << "Unknown exception caught" << endl;
}
env.end();
cout << "MO Smart Pool Search finished com sucesso!" << endl;
cout << "===================================== \n" << endl;
return paretoSETEvaluationsOnly;
}
//Function for filling milp "combinations" with available object function values at "values"
void fillVectorWithAllCombinations(vector<vector<double> >& values, vector<vector<double> >& combinations)
{
vector<int> vIndex(values.size(), 0);
bool exitWhile = true;
do
{
int nObj = values.size();
for (int i = 0; i < values[0].size(); i++)
{
vector<double> coef(nObj);
for (int o = 0; o < nObj; o++)
coef[o] = values[o][vIndex[o]];
combinations.push_back(coef);
vIndex[0]++;
}
vIndex[0] = 0;
// cout << combinations << endl;
// cout << index << endl;
// getchar();
for (int o = 1; o < nObj; o++)
{
if (vIndex[o] < (values[o].size() - 1))
{
vIndex[o]++;
o = nObj;
break;
}
else
{
vIndex[o] = 0;
if (o == (nObj - 1))
exitWhile = false;
}
}
} while (exitWhile);
}
};
#endif /* MOSPOOLS_HPP_ */