-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathdriver5.cpp
545 lines (500 loc) · 16.5 KB
/
driver5.cpp
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (C) 2007, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#include <cassert>
#include <iomanip>
#include "CoinPragma.hpp"
#include "CbcModel.hpp"
#include "OsiClpSolverInterface.hpp"
#include "CbcSolver.hpp"
#include "CbcSOS.hpp"
#include "CoinTime.hpp"
//#############################################################################
/************************************************************************
This main program shows how to take advantage of the standalone cbc in your program,
while still making major modifications.
First it reads in an integer model from an mps file
Then it initializes the integer model with cbc defaults
Then it calls CbcMain1 passing all parameters apart from first
Then it modifies all SOS objects on first CbcEvent
Then it solves
Finally it prints solution
************************************************************************/
/*
This is obviously stupid - just to show what can be done -
just branch halfway rather than use weights and solution values
*/
class CbcUserSOS : public CbcSOS {
public:
// Default Constructor
CbcUserSOS();
/* Constructor from CbcSOS
Just adds dummy integer
*/
CbcUserSOS(CbcSOS object, int dummy);
// Copy constructor
CbcUserSOS(const CbcUserSOS &);
/// Clone
virtual CbcObject *clone() const;
// Assignment operator
CbcUserSOS &operator=(const CbcUserSOS &rhs);
// Destructor
virtual ~CbcUserSOS();
/// Infeasibility - large is 0.5
virtual double infeasibility(const OsiBranchingInformation *info,
int &preferredWay) const;
/// Creates a branching object
virtual CbcBranchingObject *createCbcBranch(OsiSolverInterface *solver, const OsiBranchingInformation *info, int way);
private:
/// data
/// Dummy integer
int dummyInteger_;
};
//##############################################################################
// Default Constructor
CbcUserSOS::CbcUserSOS()
: CbcSOS()
, dummyInteger_(0)
{
}
// Constructor from CbcSOS
CbcUserSOS::CbcUserSOS(CbcSOS object, int dummyInteger)
: CbcSOS(object)
, dummyInteger_(dummyInteger)
{
}
// Copy constructor
CbcUserSOS::CbcUserSOS(const CbcUserSOS &rhs)
: CbcSOS(rhs)
{
dummyInteger_ = rhs.dummyInteger_;
}
// Clone
CbcObject *
CbcUserSOS::clone() const
{
return new CbcUserSOS(*this);
}
// Assignment operator
CbcUserSOS &
CbcUserSOS::operator=(const CbcUserSOS &rhs)
{
if (this != &rhs) {
CbcSOS::operator=(rhs);
dummyInteger_ = rhs.dummyInteger_;
}
return *this;
}
// Destructor
CbcUserSOS::~CbcUserSOS()
{
}
/*
Routine to calculate standard infeasibility of an SOS set and return a
preferred branching direction.
This is just a copy of CbcSOS
*/
double
CbcUserSOS::infeasibility(const OsiBranchingInformation *info,
int &preferredWay) const
{
int j;
int firstNonZero = -1;
int lastNonZero = -1;
OsiSolverInterface *solver = model_->solver();
const double *solution = model_->testSolution();
const double *lower = solver->getColLower();
const double *upper = solver->getColUpper();
//double largestValue=0.0;
#ifndef ZERO_ODD_TOLERANCE
#define ZERO_SOS_TOLERANCE 1.0e-14
#else
#define ZERO_SOS_TOLERANCE ZERO_ODD_TOLERANCE
#endif
//double integerTolerance =
// model_->getDblParam(CbcModel::CbcIntegerTolerance);
double integerTolerance = ZERO_SOS_TOLERANCE;
double weight = 0.0;
double sum = 0.0;
// check bounds etc
double lastWeight = -1.0e100;
for (j = 0; j < numberMembers_; j++) {
int iColumn = members_[j];
/*
The value used here (1.0e-7) is larger than the value enforced in the
constructor.
*/
if (lastWeight >= weights_[j] - 1.0e-7)
throw CoinError("Weights too close together in SOS", "infeasibility", "CbcSOS");
double value = std::max(lower[iColumn], solution[iColumn]);
value = std::min(upper[iColumn], value);
sum += value;
if (fabs(value) > integerTolerance && (upper[iColumn] > 0.0 || oddValues_)) {
weight += weights_[j] * value;
if (firstNonZero < 0)
firstNonZero = j;
lastNonZero = j;
}
}
/* ?? */
preferredWay = 1;
/*
SOS1 allows one nonzero; SOS2 allows two consecutive nonzeros. Infeasibility
is calculated as (.5)(range of nonzero values)/(number of members). So if
the first and last elements of the set are nonzero, we have maximum
infeasibility.
*/
if (lastNonZero - firstNonZero >= sosType_) {
// find where to branch
if (!oddValues_)
weight /= sum;
else
weight = 0.5 * (weights_[firstNonZero] + weights_[lastNonZero]);
if (info->defaultDual_ >= 0.0 && info->usefulRegion_ && info->columnStart_) {
assert(sosType_ == 1);
int iWhere;
for (iWhere = firstNonZero; iWhere < lastNonZero - 1; iWhere++) {
if (weight < weights_[iWhere + 1]) {
break;
}
}
int jColumnDown = members_[iWhere];
int jColumnUp = members_[iWhere + 1];
int n = 0;
CoinBigIndex j;
double objMove = info->objective_[jColumnDown];
for (j = info->columnStart_[jColumnDown];
j < info->columnStart_[jColumnDown] + info->columnLength_[jColumnDown]; j++) {
double value = info->elementByColumn_[j];
int iRow = info->row_[j];
info->indexRegion_[n++] = iRow;
info->usefulRegion_[iRow] = value;
}
for (iWhere = firstNonZero; iWhere < lastNonZero; iWhere++) {
int jColumn = members_[iWhere];
double solValue = info->solution_[jColumn];
if (!solValue)
continue;
objMove -= info->objective_[jColumn] * solValue;
for (j = info->columnStart_[jColumn];
j < info->columnStart_[jColumn] + info->columnLength_[jColumn]; j++) {
double value = -info->elementByColumn_[j] * solValue;
int iRow = info->row_[j];
double oldValue = info->usefulRegion_[iRow];
if (!oldValue) {
info->indexRegion_[n++] = iRow;
} else {
value += oldValue;
if (!value)
value = 1.0e-100;
}
info->usefulRegion_[iRow] = value;
}
}
const double *pi = info->pi_;
const double *activity = info->rowActivity_;
const double *lower = info->rowLower_;
const double *upper = info->rowUpper_;
double tolerance = info->primalTolerance_;
double direction = info->direction_;
shadowEstimateDown_ = objMove * direction;
bool infeasible = false;
for (int k = 0; k < n; k++) {
int iRow = info->indexRegion_[k];
double movement = info->usefulRegion_[iRow];
// not this time info->usefulRegion_[iRow]=0.0;
double valueP = pi[iRow] * direction;
// if move makes infeasible then make at least default
double newValue = activity[iRow] + movement;
if (newValue > upper[iRow] + tolerance || newValue < lower[iRow] - tolerance) {
shadowEstimateDown_ += fabs(movement) * std::max(fabs(valueP), info->defaultDual_);
infeasible = true;
}
}
if (shadowEstimateDown_ < info->integerTolerance_) {
if (!infeasible) {
shadowEstimateDown_ = 1.0e-10;
} else
shadowEstimateDown_ = info->integerTolerance_;
}
// And other way
// take off
objMove -= info->objective_[jColumnDown];
for (j = info->columnStart_[jColumnDown];
j < info->columnStart_[jColumnDown] + info->columnLength_[jColumnDown]; j++) {
double value = -info->elementByColumn_[j];
int iRow = info->row_[j];
double oldValue = info->usefulRegion_[iRow];
if (!oldValue) {
info->indexRegion_[n++] = iRow;
} else {
value += oldValue;
if (!value)
value = 1.0e-100;
}
info->usefulRegion_[iRow] = value;
}
// add on
objMove += info->objective_[jColumnUp];
for (j = info->columnStart_[jColumnUp];
j < info->columnStart_[jColumnUp] + info->columnLength_[jColumnUp]; j++) {
double value = info->elementByColumn_[j];
int iRow = info->row_[j];
double oldValue = info->usefulRegion_[iRow];
if (!oldValue) {
info->indexRegion_[n++] = iRow;
} else {
value += oldValue;
if (!value)
value = 1.0e-100;
}
info->usefulRegion_[iRow] = value;
}
shadowEstimateUp_ = objMove * direction;
infeasible = false;
for (int k = 0; k < n; k++) {
int iRow = info->indexRegion_[k];
double movement = info->usefulRegion_[iRow];
info->usefulRegion_[iRow] = 0.0;
double valueP = pi[iRow] * direction;
// if move makes infeasible then make at least default
double newValue = activity[iRow] + movement;
if (newValue > upper[iRow] + tolerance || newValue < lower[iRow] - tolerance) {
shadowEstimateUp_ += fabs(movement) * std::max(fabs(valueP), info->defaultDual_);
infeasible = true;
}
}
if (shadowEstimateUp_ < info->integerTolerance_) {
if (!infeasible) {
shadowEstimateUp_ = 1.0e-10;
} else
shadowEstimateUp_ = info->integerTolerance_;
}
// adjust
double downCost = shadowEstimateDown_;
double upCost = shadowEstimateUp_;
if (numberTimesDown_)
downCost *= downDynamicPseudoRatio_ / static_cast< double >(numberTimesDown_);
if (numberTimesUp_)
upCost *= upDynamicPseudoRatio_ / static_cast< double >(numberTimesUp_);
#define WEIGHT_AFTER 0.7
#define WEIGHT_BEFORE 0.1
int stateOfSearch = model_->stateOfSearch() % 10;
double returnValue = 0.0;
double minValue = std::min(downCost, upCost);
double maxValue = std::max(downCost, upCost);
if (stateOfSearch <= 2) {
// no branching solution
returnValue = WEIGHT_BEFORE * minValue + (1.0 - WEIGHT_BEFORE) * maxValue;
} else {
returnValue = WEIGHT_AFTER * minValue + (1.0 - WEIGHT_AFTER) * maxValue;
}
return returnValue;
} else {
double value = lastNonZero - firstNonZero + 1;
value *= 0.5 / static_cast< double >(numberMembers_);
return value;
}
} else {
return 0.0; // satisfied
}
}
CbcBranchingObject *
CbcUserSOS::createCbcBranch(OsiSolverInterface *solver, const OsiBranchingInformation * /*info*/, int way)
{
int j;
const double *solution = model_->testSolution();
#ifndef ZERO_SOS_TOLERANCE
double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance);
#else
double integerTolerance = ZERO_SOS_TOLERANCE;
#endif
const double *lower = solver->getColLower();
const double *upper = solver->getColUpper();
int firstNonZero = -1;
int lastNonZero = -1;
for (j = 0; j < numberMembers_; j++) {
int iColumn = members_[j];
double value = std::max(lower[iColumn], solution[iColumn]);
value = std::min(upper[iColumn], value);
if (fabs(value) > integerTolerance) {
if (firstNonZero < 0)
firstNonZero = j;
lastNonZero = j;
}
}
assert(lastNonZero - firstNonZero >= sosType_);
// find where to branch
// stupid but just to show
double separator;
int iWhere = (firstNonZero + lastNonZero) / 2;
if (sosType_ == 1) {
// SOS 1
separator = 0.5 * (weights_[iWhere] + weights_[iWhere + 1]);
} else {
// SOS 2
if (iWhere + 1 == lastNonZero)
iWhere--;
separator = weights_[iWhere + 1];
}
// create object
CbcBranchingObject *branch;
branch = new CbcSOSBranchingObject(model_, this, way, separator);
branch->setOriginalObject(this);
return branch;
}
#include "CbcEventHandler.hpp"
/** This is so user can trap events and do useful stuff.
CbcModel model_ is available as well as anything else you care
to pass in
*/
class MyEventHandler3 : public CbcEventHandler {
public:
/**@name Overrides */
//@{
virtual CbcAction event(CbcEvent whichEvent);
//@}
/**@name Constructors, destructor etc*/
//@{
/** Default constructor. */
MyEventHandler3();
/// Constructor with pointer to model (redundant as setEventHandler does)
MyEventHandler3(CbcModel *model);
/** Destructor */
virtual ~MyEventHandler3();
/** The copy constructor. */
MyEventHandler3(const MyEventHandler3 &rhs);
/// Assignment
MyEventHandler3 &operator=(const MyEventHandler3 &rhs);
/// Clone
virtual CbcEventHandler *clone() const;
//@}
protected:
// data goes here
};
//-------------------------------------------------------------------
// Default Constructor
//-------------------------------------------------------------------
MyEventHandler3::MyEventHandler3()
: CbcEventHandler()
{
}
//-------------------------------------------------------------------
// Copy constructor
//-------------------------------------------------------------------
MyEventHandler3::MyEventHandler3(const MyEventHandler3 &rhs)
: CbcEventHandler(rhs)
{
}
// Constructor with pointer to model
MyEventHandler3::MyEventHandler3(CbcModel *model)
: CbcEventHandler(model)
{
}
//-------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------
MyEventHandler3::~MyEventHandler3()
{
}
//----------------------------------------------------------------
// Assignment operator
//-------------------------------------------------------------------
MyEventHandler3 &
MyEventHandler3::operator=(const MyEventHandler3 &rhs)
{
if (this != &rhs) {
CbcEventHandler::operator=(rhs);
}
return *this;
}
//-------------------------------------------------------------------
// Clone
//-------------------------------------------------------------------
CbcEventHandler *MyEventHandler3::clone() const
{
return new MyEventHandler3(*this);
}
static bool firstTime = true;
CbcEventHandler::CbcAction
MyEventHandler3::event(CbcEvent whichEvent)
{
// If in sub tree carry on
if (!model_->parentModel()) {
if (firstTime) {
// Replace all SOS with home grown version
// Could of course do same for integers
firstTime = false;
int numberObjects = model_->numberObjects();
OsiObject **objects = model_->objects();
for (int i = 0; i < numberObjects; i++) {
CbcSOS *sosObj = dynamic_cast< CbcSOS * >(objects[i]);
if (sosObj) {
objects[i] = new CbcUserSOS(*sosObj, i);
delete sosObj;
}
}
}
}
return noAction; // carry on
}
int main(int argc, const char *argv[])
{
OsiClpSolverInterface solver1;
// Read in model using argv[1]
// and assert that it is a clean model
if (argc < 2) {
fprintf(stderr, "Need input file name.\n");
exit(1);
}
int numReadErrors;
if (!strstr(argv[1], ".lp"))
numReadErrors = solver1.readMps(argv[1], "");
else
numReadErrors = solver1.readLp(argv[1], 1.0e-10);
if (numReadErrors != 0) {
printf("%d errors reading file\n", numReadErrors);
return numReadErrors;
}
// Messy code below copied from CbcSolver.cpp
// Pass to Cbc initialize defaults
CbcModel modelA(solver1);
CbcSolverUsefulData solverData;
CbcModel *model = &modelA;
CbcMain0(modelA,solverData);
// Event handler
MyEventHandler3 eventHandler;
model->passInEventHandler(&eventHandler);
/* Now go into code for standalone solver
Could copy arguments and add -quit at end to be safe
but this will do
*/
if (argc > 2) {
CbcMain1(argc - 1, argv + 1, modelA,solverData);
} else {
const char *argv2[] = { "driver5", "-solve", "-quit" };
CbcMain1(3, argv2, modelA,solverData);
}
// Solver was cloned so get current copy
OsiSolverInterface *solver = model->solver();
// Print solution if finished (could get from model->bestSolution() as well
if (model->bestSolution()) {
const double *solution = solver->getColSolution();
int iColumn;
int numberColumns = solver->getNumCols();
std::cout << std::setiosflags(std::ios::fixed | std::ios::showpoint) << std::setw(14);
std::cout << "--------------------------------------" << std::endl;
// names may not be in current solver - use original
for (iColumn = 0; iColumn < numberColumns; iColumn++) {
double value = solution[iColumn];
if (fabs(value) > 1.0e-7)
std::cout << std::setw(6) << iColumn << " " << std::setw(8) << setiosflags(std::ios::left) << solver1.getModelPtr()->columnName(iColumn)
<< resetiosflags(std::ios::adjustfield) << std::setw(14) << " " << value << std::endl;
}
std::cout << "--------------------------------------" << std::endl;
std::cout << std::resetiosflags(std::ios::fixed | std::ios::showpoint | std::ios::scientific);
} else {
std::cout << " No solution!" << std::endl;
}
return 0;
}