本文整理汇总了C++中OsiSolverInterface类的典型用法代码示例。如果您正苦于以下问题:C++ OsiSolverInterface类的具体用法?C++ OsiSolverInterface怎么用?C++ OsiSolverInterface使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OsiSolverInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: expandKnapsack
OsiSolverInterface *
expandKnapsack(CoinModel & model, int * whichColumn, int * knapsackStart,
int * knapsackRow, int &numberKnapsack,
CglStored & stored, int logLevel,
int fixedPriority, int SOSPriority, CoinModel & tightenedModel)
{
int maxTotal = numberKnapsack;
// load from coin model
OsiSolverLink *si = new OsiSolverLink();
OsiSolverInterface * finalModel = NULL;
si->setDefaultMeshSize(0.001);
// need some relative granularity
si->setDefaultBound(100.0);
si->setDefaultMeshSize(0.01);
si->setDefaultBound(100000.0);
si->setIntegerPriority(1000);
si->setBiLinearPriority(10000);
si->load(model, true, logLevel);
// get priorities
const int * priorities = model.priorities();
int numberColumns = model.numberColumns();
if (priorities) {
OsiObject ** objects = si->objects();
int numberObjects = si->numberObjects();
for (int iObj = 0; iObj < numberObjects; iObj++) {
int iColumn = objects[iObj]->columnNumber();
if (iColumn >= 0 && iColumn < numberColumns) {
#ifndef NDEBUG
OsiSimpleInteger * obj =
dynamic_cast <OsiSimpleInteger *>(objects[iObj]) ;
#endif
assert (obj);
int iPriority = priorities[iColumn];
if (iPriority > 0)
objects[iObj]->setPriority(iPriority);
}
}
if (fixedPriority > 0) {
si->setFixedPriority(fixedPriority);
}
if (SOSPriority < 0)
SOSPriority = 100000;
}
CoinModel coinModel = *si->coinModel();
assert(coinModel.numberRows() > 0);
tightenedModel = coinModel;
int numberRows = coinModel.numberRows();
// Mark variables
int * whichKnapsack = new int [numberColumns];
int iRow, iColumn;
for (iColumn = 0; iColumn < numberColumns; iColumn++)
whichKnapsack[iColumn] = -1;
int kRow;
bool badModel = false;
// analyze
if (logLevel > 1) {
for (iRow = 0; iRow < numberRows; iRow++) {
/* Just obvious one at first
positive non unit coefficients
all integer
positive rowUpper
for now - linear (but further down in code may use nonlinear)
column bounds should be tight
*/
//double lower = coinModel.getRowLower(iRow);
double upper = coinModel.getRowUpper(iRow);
if (upper < 1.0e10) {
CoinModelLink triple = coinModel.firstInRow(iRow);
bool possible = true;
int n = 0;
int n1 = 0;
while (triple.column() >= 0) {
int iColumn = triple.column();
const char * el = coinModel.getElementAsString(iRow, iColumn);
if (!strcmp("Numeric", el)) {
if (coinModel.columnLower(iColumn) == coinModel.columnUpper(iColumn)) {
triple = coinModel.next(triple);
continue; // fixed
}
double value = coinModel.getElement(iRow, iColumn);
if (value < 0.0) {
possible = false;
} else {
n++;
if (value == 1.0)
n1++;
if (coinModel.columnLower(iColumn) < 0.0)
possible = false;
if (!coinModel.isInteger(iColumn))
possible = false;
if (whichKnapsack[iColumn] >= 0)
possible = false;
}
} else {
possible = false; // non linear
}
triple = coinModel.next(triple);
}
if (n - n1 > 1 && possible) {
double lower = coinModel.getRowLower(iRow);
//.........这里部分代码省略.........
示例2: OsiGlpkSolverInterfaceUnitTest
//--------------------------------------------------------------------------
void OsiGlpkSolverInterfaceUnitTest(const std::string & mpsDir, const std::string & netlibDir)
{
// Test default constructor
{
OsiGlpkSolverInterface m;
OSIUNITTEST_ASSERT_ERROR(m.obj_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.collower_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.colupper_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.ctype_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rowsense_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rhs_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rowrange_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rowlower_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rowupper_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.colsol_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.rowsol_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.matrixByRow_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.matrixByCol_ == NULL, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(m.getApplicationData() == NULL, {}, "glpk", "default constructor");
int i=2346;
m.setApplicationData(&i);
OSIUNITTEST_ASSERT_ERROR(*((int *)(m.getApplicationData())) == i, {}, "glpk", "default constructor");
}
{
CoinRelFltEq eq;
OsiGlpkSolverInterface m;
std::string fn = mpsDir+"exmip1";
m.readMps(fn.c_str(),"mps");
{
OsiGlpkSolverInterface im;
OSIUNITTEST_ASSERT_ERROR(im.getNumCols() == 0, {}, "glpk", "default constructor");
OSIUNITTEST_ASSERT_ERROR(im.getModelPtr() != NULL, {}, "glpk", "default constructor");
// Test reset
im.reset();
OSIUNITTEST_ASSERT_ERROR(m.obj_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.collower_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.colupper_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.ctype_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rowsense_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rhs_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rowrange_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rowlower_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rowupper_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.colsol_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.rowsol_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.matrixByRow_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.matrixByCol_ == NULL, {}, "glpk", "reset");
OSIUNITTEST_ASSERT_ERROR(m.getApplicationData() == NULL, {}, "glpk", "reset");
}
// Test copy constructor and assignment operator
{
OsiGlpkSolverInterface lhs;
{
OsiGlpkSolverInterface im(m);
OsiGlpkSolverInterface imC1(im);
OSIUNITTEST_ASSERT_ERROR(imC1.getModelPtr() != im.getModelPtr(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(imC1.getNumCols() == im.getNumCols(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(imC1.getNumRows() == im.getNumRows(), {}, "glpk", "copy constructor");
OsiGlpkSolverInterface imC2(im);
OSIUNITTEST_ASSERT_ERROR(imC2.getModelPtr() != im.getModelPtr(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(imC2.getNumCols() == im.getNumCols(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(imC2.getNumRows() == im.getNumRows(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(imC1.getModelPtr() != imC2.getModelPtr(), {}, "glpk", "copy constructor");
lhs = imC2;
}
// Test that lhs has correct values even though rhs has gone out of scope
OSIUNITTEST_ASSERT_ERROR(lhs.getModelPtr() != m.getModelPtr(), {}, "glpk", "assignment operator");
OSIUNITTEST_ASSERT_ERROR(lhs.getNumCols() == m.getNumCols(), {}, "glpk", "copy constructor");
OSIUNITTEST_ASSERT_ERROR(lhs.getNumRows() == m.getNumRows(), {}, "glpk", "copy constructor");
}
// Test clone
{
OsiGlpkSolverInterface glpkSi(m);
OsiSolverInterface * siPtr = &glpkSi;
OsiSolverInterface * siClone = siPtr->clone();
OsiGlpkSolverInterface * glpkClone = dynamic_cast<OsiGlpkSolverInterface*>(siClone);
OSIUNITTEST_ASSERT_ERROR(glpkClone != NULL, {}, "glpk", "clone");
OSIUNITTEST_ASSERT_ERROR(glpkClone->getModelPtr() != glpkSi.getModelPtr(), {}, "glpk", "clone");
OSIUNITTEST_ASSERT_ERROR(glpkClone->getNumRows() == glpkSi.getNumRows(), {}, "glpk", "clone");
OSIUNITTEST_ASSERT_ERROR(glpkClone->getNumCols() == glpkSi.getNumCols(), {}, "glpk", "clone");
delete siClone;
}
// test infinity
{
OsiGlpkSolverInterface si;
//.........这里部分代码省略.........
示例3: CglProbingUnitTest
//--------------------------------------------------------------------------
// test EKKsolution methods.
void
CglProbingUnitTest(
const OsiSolverInterface * baseSiP,
const std::string mpsDir )
{
# ifdef CGL_DEBUG
int i ; // define just once
# endif
CoinRelFltEq eq(0.000001);
// Test default constructor
{
CglProbing aGenerator;
}
// Test copy & assignment
{
CglProbing rhs;
{
CglProbing bGenerator;
CglProbing cGenerator(bGenerator);
rhs=bGenerator;
}
}
{
OsiCuts osicuts;
CglProbing test1;
OsiSolverInterface * siP = baseSiP->clone();
int nColCuts;
int nRowCuts;
std::string fn = mpsDir+"p0033";
siP->readMps(fn.c_str(),"mps");
siP->initialSolve();
// just unsatisfied variables
test1.generateCuts(*siP,osicuts);
nColCuts = osicuts.sizeColCuts();
nRowCuts = osicuts.sizeRowCuts();
std::cout<<"There are "<<nRowCuts<<" probing cuts"<<std::endl;
{
std::cout<<"there are "<<nColCuts<<" probing column cuts"<<std::endl;
#ifdef CGL_DEBUG
const double * lo = siP->getColLower();
const double * up = siP->getColUpper();
for (i=0; i<nColCuts; i++){
OsiColCut ccut;
CoinPackedVector cpv;
ccut = osicuts.colCut(i);
cpv = ccut.lbs();
int n = cpv.getNumElements();
int j;
const int * indices = cpv.getIndices();
double* elements = cpv.getElements();
for (j=0;j<n;j++) {
int icol=indices[j];
if (elements[j]>lo[icol])
std::cout<<"Can increase lb on "<<icol<<" from "<<lo[icol]<<
" to "<<elements[j]<<std::endl;
}
cpv = ccut.ubs();
n = cpv.getNumElements();
indices = cpv.getIndices();
elements = cpv.getElements();
for (j=0;j<n;j++) {
int icol=indices[j];
if (elements[j]<up[icol])
std::cout<<"Can decrease ub on "<<icol<<" from "<<up[icol]<<
" to "<<elements[j]<<std::endl;
}
}
#endif
}
#ifdef CGL_DEBUG
for (i=0; i<nRowCuts; i++){
OsiRowCut rcut;
CoinPackedVector rpv;
const double * colsol = siP->getColSolution();
rcut = osicuts.rowCut(i);
rpv = rcut.row();
const int n = rpv.getNumElements();
const int * indices = rpv.getIndices();
double* elements = rpv.getElements();
double sum2=0.0;
int k=0;
double lb=rcut.lb();
double ub=rcut.ub();
for (k=0; k<n; k++){
int column=indices[k];
sum2 += colsol[column]*elements[k];
}
if (sum2 >ub + 1.0e-7 ||sum2 < lb - 1.0e-7) {
std::cout<<"Cut "<<i<<" lb "<<lb<<" solution "<<sum2<<" ub "<<ub<<std::endl;
//.........这里部分代码省略.........
示例4: generateCuts
//-----------------------------------------------------------------------------
// Generate LSGFC cuts
//-------------------------------------------------------------------
void CglFlowCover::generateCuts(const OsiSolverInterface & si, OsiCuts & cs,
const CglTreeInfo info)
{
static int count=0;
if (getMaxNumCuts() <= 0) return;
if (getNumFlowCuts() >= getMaxNumCuts()) return;
++count;
#if 0
bool preInit = false;
bool preReso = false;
si.getHintParam(OsiDoPresolveInInitial, preInit);
si.getHintParam(OsiDoPresolveInResolve, preReso);
if (preInit == false && preReso == false) { // Do once
if (doneInitPre_ == false) {
flowPreprocess(si);
doneInitPre_ = true;
}
}
else
#endif
int numberRowCutsBefore = cs.sizeRowCuts();
flowPreprocess(si);
CoinPackedMatrix matrixByRow(*si.getMatrixByRow());
const char* sense = si.getRowSense();
const double* rhs = si.getRightHandSide();
const double* elementByRow = matrixByRow.getElements();
const int* colInd = matrixByRow.getIndices();
const CoinBigIndex* rowStart = matrixByRow.getVectorStarts();
const int* rowLength = matrixByRow.getVectorLengths();
int* ind = 0;
double* coef = 0;
int iRow, iCol;
CglFlowRowType rType;
for (iRow = 0; iRow < numRows_; ++iRow) {
rType = getRowType(iRow);
if( ( rType != CGLFLOW_ROW_MIXUB ) &&
( rType != CGLFLOW_ROW_MIXEQ ) &&
( rType != CGLFLOW_ROW_NOBINUB ) &&
( rType != CGLFLOW_ROW_NOBINEQ ) &&
( rType != CGLFLOW_ROW_SUMVARUB ) &&
( rType != CGLFLOW_ROW_SUMVAREQ ) )
continue;
const int sta = rowStart[iRow]; // Start position of iRow
const int rowLen = rowLength[iRow]; // iRow length / non-zero elements
if (ind != 0) { delete [] ind; ind = 0; }
ind = new int [rowLen];
if (coef != 0) { delete [] coef; coef = 0; }
coef = new double [rowLen];
int lastPos = sta + rowLen;
for (iCol = sta; iCol < lastPos; ++iCol) {
ind[iCol - sta] = colInd[iCol];
coef[iCol - sta] = elementByRow[iCol];
}
OsiRowCut flowCut1, flowCut2, flowCut3;
double violation = 0.0;
bool hasCut = false;
if (sense[iRow] == 'E') {
hasCut = generateOneFlowCut(si, rowLen, ind, coef, 'L',
rhs[iRow], flowCut1, violation);
if (hasCut) { // If find a cut
cs.insert(flowCut1);
incNumFlowCuts();
if (getNumFlowCuts() >= getMaxNumCuts())
break;
}
hasCut = false;
hasCut = generateOneFlowCut(si, rowLen, ind, coef, 'G',
rhs[iRow], flowCut2, violation);
if (hasCut) {
cs.insert(flowCut2);
incNumFlowCuts();
if (getNumFlowCuts() >= getMaxNumCuts())
break;
}
}
if (sense[iRow] == 'L' || sense[iRow] == 'G') {
hasCut = generateOneFlowCut(si, rowLen, ind, coef, sense[iRow],
rhs[iRow], flowCut3, violation);
if (hasCut) {
cs.insert(flowCut3);
incNumFlowCuts();
if (getNumFlowCuts() >= getMaxNumCuts())
break;
//.........这里部分代码省略.........
示例5: generateCuts
//-------------------------------------------------------------------
// Generate cuts
//-------------------------------------------------------------------
void CglAllDifferent::generateCuts(const OsiSolverInterface & si, OsiCuts & cs,
const CglTreeInfo ) const
{
#ifndef NDEBUG
int nCols=si.getNumCols();
#endif
int i;
const double * lower = si.getColLower();
const double * upper = si.getColUpper();
#ifdef CGL_DEBUG
const OsiRowCutDebugger * debugger = si.getRowCutDebugger();
if (debugger&&debugger->onOptimalPath(si)) {
printf("On optimal path %d\n",nPath);
nPath++;
int nCols=si.getNumCols();
const double * solution = si.getColSolution();
const double * optimal = debugger->optimalSolution();
const double * objective = si.getObjCoefficients();
double objval1=0.0,objval2=0.0;
for (i=0;i<nCols;i++) {
#if CGL_DEBUG>1
printf("%d %g %g %g %g\n",i,lower[i],solution[i],upper[i],optimal[i]);
#endif
objval1 += solution[i]*objective[i];
objval2 += optimal[i]*objective[i];
assert(optimal[i]>=lower[i]&&optimal[i]<=upper[i]);
}
printf("current obj %g, integer %g\n",objval1,objval2);
}
#endif
int * lo = new int[numberDifferent_];
int * up = new int[numberDifferent_];
for (i=0;i<numberDifferent_;i++) {
int iColumn = originalWhich_[i];
assert (iColumn<nCols);
lo[i] = static_cast<int> (lower[iColumn]);
assert (floor(lower[iColumn]+0.5)==lower[iColumn]);
up[i] = static_cast<int> (upper[iColumn]);
assert (floor(upper[iColumn]+0.5)==upper[iColumn]);
assert (up[i]>=lo[i]);
}
// We are going to assume we can just have one big 2d array!
// Could save by going to bits
// also could skip sets where all are fixed
// could do some of above by separate first pass
// once a variable fixed - can take out of list
// so need to redo complete stuff (including temp which_) every big pass
int offset = COIN_INT_MAX;
int maxValue = -COIN_INT_MAX;
int numberLook=0;
// copies
//int * which = new int [numberTotal];
//int * start = new int [numberSets_+1];
for (i=0;i<numberSets_;i++) {
for (int j=start_[i];j<start_[i+1];j++) {
int k=which_[j];
offset = CoinMin(offset,lo[k]);
maxValue = CoinMax(maxValue,up[k]);
}
numberLook++;
int gap = maxValue-offset+1;
double size = static_cast<double> (gap) * numberDifferent_;
if (size>1.0e7) {
if (logLevel_)
printf("Only looking at %d sets\n",numberLook);
break;
}
}
// Which sets a variable is in
int * back = new int [start_[numberSets_]];
int * backStart = new int[numberDifferent_+1];
memset(backStart,0,(numberDifferent_+1)*sizeof(int));
int numberTotal = start_[numberLook];
for (i=0;i<numberTotal;i++) {
int k=which_[i];
// note +1
backStart[k+1]++;
}
int n=0;
for (i=0;i<numberDifferent_;i++) {
int nThis = backStart[i+1];
backStart[i+1]=n;
n+= nThis;
}
// at end all backStart correct!
for (i=0;i<numberLook;i++) {
for (int j=start_[i];j<start_[i+1];j++) {
int k=which_[j];
// note +1
int iPut = backStart[k+1];
back[iPut]=i;
backStart[k+1]=iPut+1;
}
}
// value is possible for variable k if possible[k*gap+value] is nonzero
int gap = maxValue-offset+1;
char * possible = new char[gap*numberDifferent_];
//.........这里部分代码省略.........
示例6: off
// This version fixes stuff and does IP
int
CbcHeuristicLocal::solutionFix(double & objectiveValue,
double * newSolution,
const int * /*keep*/)
{
/*
If when is set to off (0), or set to root (1) and we're not at the root,
return. If this heuristic discovered the current solution, don't continue.
*/
numCouldRun_++;
// See if to do
if (!when() || (when() == 1 && model_->phase() != 1))
return 0; // switched off
// Don't do if it was this heuristic which found solution!
if (this == model_->lastHeuristic())
return 0;
/*
Load up a new solver with the solution.
Why continuousSolver(), as opposed to solver()?
*/
OsiSolverInterface * newSolver = model_->continuousSolver()->clone();
const double * colLower = newSolver->getColLower();
//const double * colUpper = newSolver->getColUpper();
int numberIntegers = model_->numberIntegers();
const int * integerVariable = model_->integerVariable();
/*
The net effect here is that anything that hasn't moved from its lower bound
will be fixed at lower bound.
See comments in solution() w.r.t. asymmetric treatment of upper and lower
bounds.
*/
int i;
int nFix = 0;
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
const OsiObject * object = model_->object(i);
// get original bounds
double originalLower;
double originalUpper;
getIntegerInformation( object, originalLower, originalUpper);
newSolver->setColLower(iColumn, CoinMax(colLower[iColumn], originalLower));
if (!used_[iColumn]) {
newSolver->setColUpper(iColumn, colLower[iColumn]);
nFix++;
}
}
/*
Try a `small' branch-and-bound search. The notion here is that we've fixed a
lot of variables and reduced the amount of `free' problem to a point where a
small BaB search will suffice to fully explore the remaining problem. This
routine will execute integer presolve, then call branchAndBound to do the
actual search.
*/
int returnCode = 0;
#ifdef CLP_INVESTIGATE2
printf("Fixing %d out of %d (%d continuous)\n",
nFix, numberIntegers, newSolver->getNumCols() - numberIntegers);
#endif
if (nFix*10 <= numberIntegers) {
// see if we can fix more
int * which = new int [2*(numberIntegers-nFix)];
int * sort = which + (numberIntegers - nFix);
int n = 0;
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
if (used_[iColumn]) {
which[n] = iColumn;
sort[n++] = used_[iColumn];
}
}
CoinSort_2(sort, sort + n, which);
// only half fixed in total
n = CoinMin(n, numberIntegers / 2 - nFix);
int allow = CoinMax(numberSolutions_ - 2, sort[0]);
int nFix2 = 0;
for (i = 0; i < n; i++) {
int iColumn = integerVariable[i];
if (used_[iColumn] <= allow) {
newSolver->setColUpper(iColumn, colLower[iColumn]);
nFix2++;
} else {
break;
}
}
delete [] which;
nFix += nFix2;
#ifdef CLP_INVESTIGATE2
printf("Number fixed increased from %d to %d\n",
nFix - nFix2, nFix);
#endif
}
if (nFix*10 > numberIntegers) {
returnCode = smallBranchAndBound(newSolver, numberNodes_, newSolution, objectiveValue,
objectiveValue, "CbcHeuristicLocal");
//.........这里部分代码省略.........
示例7: CoinMin
int
CbcHeuristicNaive::solution(double & solutionValue,
double * betterSolution)
{
numCouldRun_++;
// See if to do
bool atRoot = model_->getNodeCount() == 0;
int passNumber = model_->getCurrentPassNumber();
if (!when() || (when() == 1 && model_->phase() != 1) || !atRoot || passNumber != 1)
return 0; // switched off
// Don't do if it was this heuristic which found solution!
if (this == model_->lastHeuristic())
return 0;
numRuns_++;
double cutoff;
model_->solver()->getDblParam(OsiDualObjectiveLimit, cutoff);
double direction = model_->solver()->getObjSense();
cutoff *= direction;
cutoff = CoinMin(cutoff, solutionValue);
OsiSolverInterface * solver = model_->continuousSolver();
if (!solver)
solver = model_->solver();
const double * colLower = solver->getColLower();
const double * colUpper = solver->getColUpper();
const double * objective = solver->getObjCoefficients();
int numberColumns = model_->getNumCols();
int numberIntegers = model_->numberIntegers();
const int * integerVariable = model_->integerVariable();
int i;
bool solutionFound = false;
CoinWarmStartBasis saveBasis;
CoinWarmStartBasis * basis =
dynamic_cast<CoinWarmStartBasis *>(solver->getWarmStart()) ;
if (basis) {
saveBasis = * basis;
delete basis;
}
// First just fix all integers as close to zero as possible
OsiSolverInterface * newSolver = cloneBut(7); // wassolver->clone();
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
double lower = colLower[iColumn];
double upper = colUpper[iColumn];
double value;
if (lower > 0.0)
value = lower;
else if (upper < 0.0)
value = upper;
else
value = 0.0;
newSolver->setColLower(iColumn, value);
newSolver->setColUpper(iColumn, value);
}
newSolver->initialSolve();
if (newSolver->isProvenOptimal()) {
double solValue = newSolver->getObjValue() * direction ;
if (solValue < cutoff) {
// we have a solution
solutionFound = true;
solutionValue = solValue;
memcpy(betterSolution, newSolver->getColSolution(),
numberColumns*sizeof(double));
COIN_DETAIL_PRINT(printf("Naive fixing close to zero gave solution of %g\n", solutionValue));
cutoff = solValue - model_->getCutoffIncrement();
}
}
// Now fix all integers as close to zero if zero or large cost
int nFix = 0;
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
double lower = colLower[iColumn];
double upper = colUpper[iColumn];
double value;
if (fabs(objective[i]) > 0.0 && fabs(objective[i]) < large_) {
nFix++;
if (lower > 0.0)
value = lower;
else if (upper < 0.0)
value = upper;
else
value = 0.0;
newSolver->setColLower(iColumn, value);
newSolver->setColUpper(iColumn, value);
} else {
// set back to original
newSolver->setColLower(iColumn, lower);
newSolver->setColUpper(iColumn, upper);
}
}
const double * solution = solver->getColSolution();
if (nFix) {
newSolver->setWarmStart(&saveBasis);
newSolver->setColSolution(solution);
newSolver->initialSolve();
if (newSolver->isProvenOptimal()) {
double solValue = newSolver->getObjValue() * direction ;
if (solValue < cutoff) {
// try branch and bound
//.........这里部分代码省略.........
示例8:
/*
* Class: thebeast_osi_OsiSolverJNI
* Method: resolve
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_thebeast_osi_OsiSolverJNI_resolve
(JNIEnv *, jobject, jint ptr){
OsiSolverInterface* solver = (OsiSolverInterface*) ptr;
solver->resolve();
}
示例9: assert
// Returns type
int
CbcFathomDynamicProgramming::checkPossible(int allowableSize)
{
algorithm_ = -1;
assert(model_->solver());
OsiSolverInterface * solver = model_->solver();
const CoinPackedMatrix * matrix = solver->getMatrixByCol();
int numberIntegers = model_->numberIntegers();
int numberColumns = solver->getNumCols();
size_ = 0;
if (numberIntegers != numberColumns)
return -1; // can't do dynamic programming
const double * lower = solver->getColLower();
const double * upper = solver->getColUpper();
const double * rowUpper = solver->getRowUpper();
int numberRows = model_->getNumRows();
int i;
// First check columns to see if possible
double * rhs = new double [numberRows];
CoinCopyN(rowUpper, numberRows, rhs);
// Column copy
const double * element = matrix->getElements();
const int * row = matrix->getIndices();
const CoinBigIndex * columnStart = matrix->getVectorStarts();
const int * columnLength = matrix->getVectorLengths();
bool bad = false;
/* It is just possible that we could say okay as
variables may get fixed but seems unlikely */
for (i = 0; i < numberColumns; i++) {
int j;
double lowerValue = lower[i];
assert (lowerValue == floor(lowerValue));
for (j = columnStart[i];
j < columnStart[i] + columnLength[i]; j++) {
int iRow = row[j];
double value = element[j];
if (upper[i] > lowerValue && (value <= 0.0 || value != floor(value)))
bad = true;
if (lowerValue)
rhs[iRow] -= lowerValue * value;
}
}
// check possible (at present do not allow covering)
int numberActive = 0;
bool infeasible = false;
bool saveBad = bad;
for (i = 0; i < numberRows; i++) {
if (rhs[i] < 0)
infeasible = true;
else if (rhs[i] > 1.0e5 || fabs(rhs[i] - floor(rhs[i] + 0.5)) > 1.0e-7)
bad = true;
else if (rhs[i] > 0.0)
numberActive++;
}
if (bad || infeasible) {
delete [] rhs;
if (!saveBad && infeasible)
return -2;
else
return -1;
}
// check size of array needed
double size = 1.0;
double check = COIN_INT_MAX;
for (i = 0; i < numberRows; i++) {
int n = static_cast<int> (floor(rhs[i] + 0.5));
if (n) {
n++; // allow for 0,1... n
if (numberActive != 1) {
// power of 2
int iBit = 0;
int k = n;
k &= ~1;
while (k) {
iBit++;
k &= ~(1 << iBit);
}
// See if exact power
if (n != (1 << iBit)) {
// round up to next power of 2
n = 1 << (iBit + 1);
}
size *= n;
if (size >= check)
break;
} else {
size = n; // just one constraint
}
}
}
// set size needed
if (size >= check)
size_ = COIN_INT_MAX;
else
//.........这里部分代码省略.........
示例10: CglOddHoleUnitTest
//--------------------------------------------------------------------------
// test EKKsolution methods.
void
CglOddHoleUnitTest(
const OsiSolverInterface * baseSiP,
const std::string mpsDir )
{
CoinRelFltEq eq(0.000001);
// Test default constructor
{
CglOddHole aGenerator;
}
// Test copy & assignment
{
CglOddHole rhs;
{
CglOddHole bGenerator;
CglOddHole cGenerator(bGenerator);
rhs=bGenerator;
}
}
// test on simple case
{
const int nRows=3;
const int nCols=3;
const int nEls=6;
const double elem[]={1.0,1.0,1.0,1.0,1.0,1.0};
const int row[]={0,1,0,2,1,2};
const CoinBigIndex start[]={0,2,4};
const int len[]={2,2,2};
CoinPackedMatrix matrix(true,nRows,nCols,nEls,elem,row,start,len);
const double sol[]={0.5,0.5,0.5};
const double dj[]={0,0,0};
const int which[]={1,1,1};
const int fixed[]={0,0,0};
OsiCuts cs;
CglOddHole test1;
CglTreeInfo info;
info.randomNumberGenerator=NULL;
test1.generateCuts(NULL,matrix,sol,dj,cs,which,fixed,info,true);
CoinPackedVector check;
int index[] = {0,1,2};
double el[] = {1,1,1};
check.setVector(3,index,el);
//assert (cs.sizeRowCuts()==2);
assert (cs.sizeRowCuts()==1);
// sort Elements in increasing order
CoinPackedVector rpv=cs.rowCut(0).row();
rpv.sortIncrIndex();
assert (check==rpv);
}
// Testcase /u/rlh/osl2/mps/scOneInt.mps
// Model has 3 continous, 2 binary, and 1 general
// integer variable.
{
OsiSolverInterface * siP = baseSiP->clone();
std::string fn = mpsDir+"scOneInt";
siP->readMps(fn.c_str(),"mps");
#if 0
CglOddHole cg;
int nCols=siP->getNumCols();
// Test the siP methods for detecting
// variable type
int numCont=0, numBinary=0, numIntNonBinary=0, numInt=0;
for (int thisCol=0; thisCol<nCols; thisCol++) {
if ( siP->isContinuous(thisCol) ) numCont++;
if ( siP->isBinary(thisCol) ) numBinary++;
if ( siP->isIntegerNonBinary(thisCol) ) numIntNonBinary++;
if ( siP->isInteger(thisCol) ) numInt++;
}
assert(numCont==3);
assert(numBinary==2);
assert(numIntNonBinary==1);
assert(numInt==3);
// Test initializeCutGenerator
siP->initialSolve();
assert(xstar !=NULL);
for (i=0; i<nCols; i++){
assert(complement[i]==0);
}
int nRows=siP->getNumRows();
for (i=0; i<nRows; i++){
int vectorsize = siP->getMatrixByRow()->getVectorSize(i);
assert(vectorsize==2);
}
kccg.cleanUpCutGenerator(complement,xstar);
#endif
delete siP;
}
//.........这里部分代码省略.........
示例11: c_lin
//.........这里部分代码省略.........
for(int i = 0 ; i < n ; i++){
if(variableType[i] != Bonmin::TMINLP::CONTINUOUS){
idxIntegers.push_back(i);
objective[i] = beta*(1 - 2*colsol[i]);
}
}
#if 0
// Get dual multipliers and build gradient of the lagrangean
const double * duals = nlp->getRowPrice() + 2 *n;
vector<double> grad(n, 0);
vector<int> indices(n, 0);
tminlp->eval_grad_f(n, x_sol, false, grad());
for(int i = 0 ; i < m ; i++){
if(c_lin[i] == Ipopt::TNLP::LINEAR) continue;
int nnz;
tminlp->eval_grad_gi(n, x_sol, false, i, nnz, indices(), NULL);
tminlp->eval_grad_gi(n, x_sol, false, i, nnz, NULL, grad());
for(int k = 0 ; k < nnz ; k++){
objective[indices[k]] += alpha *duals[i] * grad[k];
}
}
for(int i = 0 ; i < n ; i++){
if(variableType[i] != Bonmin::TMINLP::CONTINUOUS)
objective[i] += alpha * grad[i];
//if(fabs(objective[i]) < 1e-4) objective[i] = 0;
else objective[i] = 0;
}
std::copy(objective.begin(), objective.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout<<std::endl;
#endif
// load the problem to OSI
OsiSolverInterface *si = mip_->solver();
assert(si != NULL);
CoinMessageHandler * handler = model_->messageHandler()->clone();
si->passInMessageHandler(handler);
si->messageHandler()->setLogLevel(1);
si->loadProblem(matrix, model_->solver()->getColLower(), model_->solver()->getColUpper(), objective(),
newRowLower(), newRowUpper());
si->setInteger(idxIntegers(), static_cast<int>(idxIntegers.size()));
si->applyCuts(noGoods);
bool hasFractionnal = true;
while(hasFractionnal){
mip_->optimize(DBL_MAX, 0, 60);
hasFractionnal = false;
#if 0
bool feasible = false;
if(mip_->getLastSolution()) {
const double* solution = mip_->getLastSolution();
std::copy(solution, solution + n, newSolution.begin());
feasible = true;
}
if(feasible) {
// fix the integer variables and solve the NLP
// also add no good cut
CoinPackedVector v;
double lb = 1;
for (int iColumn=0;iColumn<n;iColumn++) {
if (variableType[iColumn] != Bonmin::TMINLP::CONTINUOUS) {
double value=newSolution[iColumn];
if (fabs(floor(value+0.5)-value)>integerTolerance) {
示例12: getVubs
//-------------------------------------------------------------------
// Given the model data, a row of the model, and a LP solution,
// this function tries to generate a violated lifted simple generalized
// flow cover.
//-------------------------------------------------------------------
bool
CglFlowCover::generateOneFlowCut( const OsiSolverInterface & si,
const int rowLen,
int* ind,
double* coef,
char sense,
double rhs,
OsiRowCut& flowCut,
double& violation )
{
bool generated = false;
const double* xlp = si.getColSolution();
const int numCols = si.getNumCols();
double* up = new double [rowLen];
double* x = new double [rowLen];
double* y = new double [rowLen];
CglFlowColType* sign = new CglFlowColType [rowLen];
int i, j;
double value, LB, UB;
CglFlowVLB VLB;
CglFlowVUB VUB;
static int count=0;
++count;
CGLFLOW_DEBUG=false;
doLift=true;
// Get integer types
const char * columnType = si.getColType ();
for (i = 0; i < rowLen; ++i) {
if ( xlp[ind[i]] - floor(xlp[ind[i]]) > EPSILON_ && ceil(xlp[ind[i]]) - xlp[ind[i]] > EPSILON_ )
break;
}
if (i != rowLen) {
for (int j = 0; j < rowLen; ++j) {
if ( fabs(coef[j])<=EPSILON_) {
doLift = false;
break;
}
}
} else {
doLift = false;
}
if (!doLift) {
delete [] sign;
delete [] up;
delete [] x;
delete [] y;
return generated;
}
//-------------------------------------------------------------------------
if (sense == 'G') flipRow(rowLen, coef, rhs); // flips everything,
// but the sense
if(CGLFLOW_DEBUG) {
std::cout << "***************************" << std::endl;
std::cout << "Generate Flow cover -- initial constraint, converted to L sense..." << std::endl;
std::cout << "Rhs = " << rhs << std::endl;
std::cout << "coef [var_index]" << " -- " << "xlp[var_index]" << '\t' << "vub_coef[vub_index] vub_lp_value OR var_index_col_ub" << std::endl;
for(int iD = 0; iD < rowLen; ++iD) {
VUB = getVubs(ind[iD]);
std::cout << std::setw(5) << coef[iD] << "[" << std::setw(5) << ind[iD] << "] -- "
<< std::setw(20) << xlp[ind[iD]] << '\t';
if (VUB.getVar() != UNDEFINED_) {
std::cout << std::setw(20) << VUB.getVal() << "[" << std::setw(5) << VUB.getVar() << "]"
<< std::setw(20) << xlp[VUB.getVar()] << std::endl;
}
else
std::cout << std::setw(20) << si.getColUpper()[ind[iD]] << " " << std::setw(20) << 1.0 << std::endl;
}
}
//-------------------------------------------------------------------------
// Generate conservation inequality and capacity equalities from
// the given row.
for (i = 0; i < rowLen; ++i) {
VLB = getVlbs(ind[i]);
LB = ( VLB.getVar() != UNDEFINED_ ) ?
VLB.getVal() : si.getColLower()[ind[i]];
VUB = getVubs(ind[i]);
UB = ( VUB.getVar() != UNDEFINED_ ) ?
VUB.getVal() : si.getColUpper()[ind[i]];
if (LB < -EPSILON_) { // Only consider rows whose variables are all
//.........这里部分代码省略.........
示例13: matrixByRow
//-------------------------------------------------------------------
// Determine row types. Find the VUBS and VLBS.
//-------------------------------------------------------------------
void
CglFlowCover::flowPreprocess(const OsiSolverInterface& si)
{
CoinPackedMatrix matrixByRow(*si.getMatrixByRow());
int numRows = si.getNumRows();
int numCols = si.getNumCols();
const char* sense = si.getRowSense();
const double* RHS = si.getRightHandSide();
const double* coefByRow = matrixByRow.getElements();
const int* colInds = matrixByRow.getIndices();
const int* rowStarts = matrixByRow.getVectorStarts();
const int* rowLengths = matrixByRow.getVectorLengths();
int iRow = -1;
int iCol = -1;
numCols_ = numCols; // Record col and row numbers for copy constructor
numRows_ = numRows;
if (rowTypes_ != 0) {
delete [] rowTypes_; rowTypes_ = 0;
}
rowTypes_ = new CglFlowRowType [numRows];// Destructor will free memory
// Get integer types
const char * columnType = si.getColType (true);
// Summarize the row type infomation.
int numUNDEFINED = 0;
int numVARUB = 0;
int numVARLB = 0;
int numVAREQ = 0;
int numMIXUB = 0;
int numMIXEQ = 0;
int numNOBINUB = 0;
int numNOBINEQ = 0;
int numSUMVARUB = 0;
int numSUMVAREQ = 0;
int numUNINTERSTED = 0;
int* ind = new int [numCols];
double* coef = new double [numCols];
for (iRow = 0; iRow < numRows; ++iRow) {
int rowLen = rowLengths[iRow];
char sen = sense[iRow];
double rhs = RHS[iRow];
CoinDisjointCopyN(colInds + rowStarts[iRow], rowLen, ind);
CoinDisjointCopyN(coefByRow + rowStarts[iRow], rowLen, coef);
CglFlowRowType rowType = determineOneRowType(si, rowLen, ind, coef,
sen, rhs);
rowTypes_[iRow] = rowType;
switch(rowType) {
case CGLFLOW_ROW_UNDEFINED:
++numUNDEFINED;
break;
case CGLFLOW_ROW_VARUB:
++numVARUB;
break;
case CGLFLOW_ROW_VARLB:
++numVARLB;
break;
case CGLFLOW_ROW_VAREQ:
++numVAREQ;
break;
case CGLFLOW_ROW_MIXUB:
++numMIXUB;
break;
case CGLFLOW_ROW_MIXEQ:
++numMIXEQ;
break;
case CGLFLOW_ROW_NOBINUB:
++numNOBINUB;
break;
case CGLFLOW_ROW_NOBINEQ:
++numNOBINEQ;
break;
case CGLFLOW_ROW_SUMVARUB:
++numSUMVARUB;
break;
case CGLFLOW_ROW_SUMVAREQ:
++numSUMVAREQ;
break;
case CGLFLOW_ROW_UNINTERSTED:
++numUNINTERSTED;
break;
default:
throw CoinError("Unknown row type", "flowPreprocess",
"CglFlowCover");
}
}
delete [] ind; ind = NULL;
//.........这里部分代码省略.........
示例14: main
//.........这里部分代码省略.........
model.setNumberStrong(10);
model.setNumberStrong(20);
//model.setNumberStrong(5);
model.setNumberBeforeTrust(5);
//model.setSizeMiniTree(2);
model.solver()->setIntParam(OsiMaxNumIterationHotStart,100);
// Switch off most output
if (model.getNumCols()<3000) {
model.messageHandler()->setLogLevel(1);
//model.solver()->messageHandler()->setLogLevel(0);
} else {
model.messageHandler()->setLogLevel(2);
model.solver()->messageHandler()->setLogLevel(1);
}
model.messageHandler()->setLogLevel(6);
model.solver()->messageHandler()->setLogLevel(1);
// If time is given then stop after that number of minutes
if (minutes>=0.0) {
std::cout<<"Stopping after "<<minutes<<" minutes"<<std::endl;
model.setDblParam(CbcModel::CbcMaximumSeconds,60.0*minutes);
}
// Default strategy will leave cut generators as they exist already
// so cutsOnlyAtRoot (1) ignored
// numberStrong (2) is 5 (default)
// numberBeforeTrust (3) is 5 (default is 0)
// printLevel (4) defaults (0)
CbcStrategyDefault strategy(true,5,5);
// Set up pre-processing to find sos if wanted
if (preProcess)
strategy.setupPreProcessing(2);
model.setStrategy(strategy);
int numberColumns = model.solver()->getNumCols();
double * bestSolution=NULL;
int * priority = new int[numberColumns];
// Do two passes
for (int iPass=0;iPass<2;iPass++) {
time1 = CoinCpuTime();
// Do hot start on second pass
if (bestSolution) {
model.setHotstartSolution(bestSolution,priority);
delete [] bestSolution;
bestSolution=NULL;
delete [] priority;
model.setMaximumNodes(40000);
} else {
model.setMaximumNodes(40000);
}
// Do complete search
model.branchAndBound();
std::cout<<mpsFileName<<" took "<<CoinCpuTime()-time1<<" seconds, "
<<model.getNodeCount()<<" nodes with objective "
<<model.getObjValue()
<<(!model.status() ? " Finished" : " Not finished")
<<std::endl;
// Print solution if finished - we can't get names from Osi! - so get from OsiClp
assert (model.getMinimizationObjValue()<1.0e50);
OsiSolverInterface * solver = model.solver();
int numberColumns = solver->getNumCols();
const double * solution = solver->getColSolution();
// save solution
if (!iPass) {
bestSolution = CoinCopyOfArray(solution,numberColumns);
for (int i=0;i<numberColumns;i++) {
if (solution[i]>0.5)
priority[i]=-1;
else
priority[i]=2;
}
}
//const double * lower = solver->getColLower();
//const double * upper = solver->getColUpper();
// Get names from solver1 (as OsiSolverInterface may lose)
std::vector<std::string> columnNames = *solver1.getModelPtr()->columnNames();
int iColumn;
std::cout<<std::setiosflags(std::ios::fixed|std::ios::showpoint)<<std::setw(14);
std::cout<<"--------------------------------------"<<std::endl;
for (iColumn=0;iColumn<numberColumns;iColumn++) {
double value=solution[iColumn];
if (fabs(value)>1.0e-7&&solver->isInteger(iColumn))
std::cout<<std::setw(6)<<iColumn<<" "
<<columnNames[iColumn]<<" "
<<value
//<<" "<<lower[iColumn]<<" "<<upper[iColumn]
<<std::endl;
}
std::cout<<"--------------------------------------"<<std::endl;
std::cout<<std::resetiosflags(std::ios::fixed|std::ios::showpoint|std::ios::scientific);
model.resetToReferenceSolver();
}
return 0;
}
示例15: getIntegerInformation
/*
First tries setting a variable to better value. If feasible then
tries setting others. If not feasible then tries swaps
Returns 1 if solution, 0 if not */
int
CbcHeuristicVND::solution(double & solutionValue,
double * betterSolution)
{
numCouldRun_++;
int returnCode = 0;
const double * bestSolution = model_->bestSolution();
if (!bestSolution)
return 0; // No solution found yet
if (numberSolutions_ < model_->getSolutionCount()) {
// new solution - add info
numberSolutions_ = model_->getSolutionCount();
int numberIntegers = model_->numberIntegers();
const int * integerVariable = model_->integerVariable();
int i;
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
const OsiObject * object = model_->object(i);
// get original bounds
double originalLower;
double originalUpper;
getIntegerInformation( object, originalLower, originalUpper);
double value = bestSolution[iColumn];
if (value < originalLower) {
value = originalLower;
} else if (value > originalUpper) {
value = originalUpper;
}
}
}
int numberNodes = model_->getNodeCount();
if (howOften_ == 100) {
if (numberNodes < lastNode_ + 12)
return 0;
// Do at 50 and 100
if ((numberNodes > 40 && numberNodes <= 50) || (numberNodes > 90 && numberNodes < 100))
numberNodes = howOften_;
}
if ((numberNodes % howOften_) == 0 && (model_->getCurrentPassNumber() == 1 ||
model_->getCurrentPassNumber() == 999999)) {
lastNode_ = model_->getNodeCount();
OsiSolverInterface * solver = model_->solver();
int numberIntegers = model_->numberIntegers();
const int * integerVariable = model_->integerVariable();
const double * currentSolution = solver->getColSolution();
OsiSolverInterface * newSolver = cloneBut(3); // was model_->continuousSolver()->clone();
//const double * colLower = newSolver->getColLower();
//const double * colUpper = newSolver->getColUpper();
double primalTolerance;
solver->getDblParam(OsiPrimalTolerance, primalTolerance);
// Sort on distance
double * distance = new double [numberIntegers];
int * which = new int [numberIntegers];
int i;
int nFix = 0;
double tolerance = 10.0 * primalTolerance;
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
const OsiObject * object = model_->object(i);
// get original bounds
double originalLower;
double originalUpper;
getIntegerInformation( object, originalLower, originalUpper);
double valueInt = bestSolution[iColumn];
if (valueInt < originalLower) {
valueInt = originalLower;
} else if (valueInt > originalUpper) {
valueInt = originalUpper;
}
baseSolution_[iColumn] = currentSolution[iColumn];
distance[i] = fabs(currentSolution[iColumn] - valueInt);
which[i] = i;
if (fabs(currentSolution[iColumn] - valueInt) < tolerance)
nFix++;
}
CoinSort_2(distance, distance + numberIntegers, which);
nDifferent_ = numberIntegers - nFix;
stepSize_ = nDifferent_ / 10;
k_ = stepSize_;
//nFix = numberIntegers-stepSize_;
for (i = 0; i < nFix; i++) {
int j = which[i];
int iColumn = integerVariable[j];
const OsiObject * object = model_->object(i);
// get original bounds
double originalLower;
double originalUpper;
getIntegerInformation( object, originalLower, originalUpper);
double valueInt = bestSolution[iColumn];
//.........这里部分代码省略.........