本文整理汇总了C++中OsiSolverInterface::setInteger方法的典型用法代码示例。如果您正苦于以下问题:C++ OsiSolverInterface::setInteger方法的具体用法?C++ OsiSolverInterface::setInteger怎么用?C++ OsiSolverInterface::setInteger使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OsiSolverInterface
的用法示例。
在下文中一共展示了OsiSolverInterface::setInteger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: problem_convert_to_osi
void* problem_convert_to_osi(Problem *p)
{
int i;
double rowLb, rowUb;
OsiSolverInterface *solver = new OsiClpSolverInterface();
CoinBuild cb;
solver->setIntParam(OsiNameDiscipline, 2);
solver->messageHandler()->setLogLevel(0);
solver->setHintParam(OsiDoReducePrint,true,OsiHintTry);
for(i = 0; i < p->numCols; i++)
{
solver->addCol(0, NULL, NULL, p->colLb[i], p->colUb[i], p->objCoef[i]);
solver->setColName(i, p->colName[i]);
if(p->colType[i] == CONTINUOUS)
solver->setContinuous(i);
else
solver->setInteger(i);
}
for(i = 0; i < p->numRows; i++)
{
switch(p->rowSense[i])
{
case 'E':
rowLb = p->rhs[i];
rowUb = p->rhs[i];
break;
case 'L':
rowLb = -p->infty;
rowUb = p->rhs[i];
break;
case 'G':
rowLb = p->rhs[i];
rowUb = p->infty;
break;
default:
fprintf(stderr, "Error: invalid type of constraint!\n");
exit(EXIT_FAILURE);
}
cb.addRow(p->rowNElements[i], p->idxsByRow[i], p->coefsByRow[i], rowLb, rowUb);
}
solver->addRows(cb);
for(i = 0; i < p->numRows; i++)
solver->setRowName(i, p->rowName[i]);
return solver;
}
示例2: objSense
//#############################################################################
void
MibSHeuristic::lowerObjHeuristic()
{
/*
optimize wrt to lower-level objective
over current feasible lp feasible region
*/
MibSModel * model = MibSModel_;
OsiSolverInterface * oSolver = model->getSolver();
//OsiSolverInterface * hSolver = new OsiCbcSolverInterface();
OsiSolverInterface* hSolver = new OsiSymSolverInterface();
double objSense(model->getLowerObjSense());
int lCols(model->getLowerDim());
int uCols(model->getUpperDim());
int * lColIndices = model->getLowerColInd();
int * uColIndices = model->getUpperColInd();
double * lObjCoeffs = model->getLowerObjCoeffs();
//int tCols(lCols + uCols);
int tCols(oSolver->getNumCols());
//assert(tCols == oSolver->getNumCols());
hSolver->loadProblem(*oSolver->getMatrixByCol(),
oSolver->getColLower(), oSolver->getColUpper(),
oSolver->getObjCoefficients(),
oSolver->getRowLower(), oSolver->getRowUpper());
int j(0);
for(j = 0; j < tCols; j++){
if(oSolver->isInteger(j))
hSolver->setInteger(j);
}
double * nObjCoeffs = new double[tCols];
int i(0), index(0);
CoinZeroN(nObjCoeffs, tCols);
for(i = 0; i < lCols; i++){
index = lColIndices[i];
nObjCoeffs[index] = lObjCoeffs[i];
}
//MibS objective sense is the opposite of OSI's!
hSolver->setObjSense(objSense);
hSolver->setObjective(nObjCoeffs);
//double cutoff(model->getCutoff());
double cutoff(model->getKnowledgeBroker()->getIncumbentValue());
if(model->getNumSolutions()){
CoinPackedVector objCon;
//double rhs(cutoff * objSense);
//double smlTol(1.0);
double rhs(cutoff);
for(i = 0; i < tCols; i++){
objCon.insert(i, oSolver->getObjCoefficients()[i]
* oSolver->getObjSense());
}
hSolver->addRow(objCon, - hSolver->getInfinity(), rhs);
}
if(0)
hSolver->writeLp("lobjheurstic");
if(0){
dynamic_cast<OsiCbcSolverInterface *>
(hSolver)->getModelPtr()->messageHandler()->setLogLevel(0);
}
else{
dynamic_cast<OsiSymSolverInterface *>
(hSolver)->setSymParam("prep_level", -1);
dynamic_cast<OsiSymSolverInterface *>
(hSolver)->setSymParam("verbosity", -2);
dynamic_cast<OsiSymSolverInterface *>
(hSolver)->setSymParam("max_active_nodes", 1);
}
hSolver->branchAndBound();
if(hSolver->isProvenOptimal()){
double upperObjVal(0.0);
/*****************NEW ******************/
MibSSolution *mibSol = NULL;
OsiSolverInterface * lSolver = model->bS_->setUpModel(hSolver, true);
//.........这里部分代码省略.........
示例3: uObjSense
//#############################################################################
mcSol
MibSHeuristic::solveSubproblem(double beta)
{
/*
optimize wrt to weighted upper-level objective
over current feasible lp feasible region
*/
MibSModel * model = MibSModel_;
OsiSolverInterface * oSolver = model->getSolver();
//OsiSolverInterface * sSolver = new OsiCbcSolverInterface();
OsiSolverInterface* sSolver = new OsiSymSolverInterface();
//sSolver = oSolver->clone();
//OsiSolverInterface * sSolver = tmpSolver;
//OsiSolverInterface * tmpSolver = new OsiSolverInterface(oSolver);
double uObjSense(oSolver->getObjSense());
double lObjSense(model->getLowerObjSense());
int lCols(model->getLowerDim());
int uCols(model->getUpperDim());
int * lColIndices = model->getLowerColInd();
int * uColIndices = model->getUpperColInd();
double * lObjCoeffs = model->getLowerObjCoeffs();
const double * uObjCoeffs = oSolver->getObjCoefficients();
double etol(etol_);
int tCols(uCols + lCols);
assert(tCols == oSolver->getNumCols());
sSolver->loadProblem(*oSolver->getMatrixByCol(),
oSolver->getColLower(), oSolver->getColUpper(),
oSolver->getObjCoefficients(),
oSolver->getRowLower(), oSolver->getRowUpper());
int j(0);
for(j = 0; j < tCols; j++){
if(oSolver->isInteger(j))
sSolver->setInteger(j);
}
double * nObjCoeffs = new double[tCols];
int i(0), index(0);
CoinZeroN(nObjCoeffs, tCols);
/* Multiply the UL columns of the UL objective by beta */
for(i = 0; i < uCols; i++){
index = uColIndices[i];
if(fabs(uObjCoeffs[index]) > etol)
nObjCoeffs[index] = beta * uObjCoeffs[index] * uObjSense;
else
nObjCoeffs[index] = 0.0;
}
/* Multiply the LL columns of the UL objective by beta */
for(i = 0; i < lCols; i++){
index = lColIndices[i];
if(fabs(uObjCoeffs[index]) > etol)
nObjCoeffs[index] = beta* uObjCoeffs[index] * uObjSense;
else
nObjCoeffs[index] = 0.0;
}
/* Add the LL columns of the LL objective multiplied by (1 - beta) */
for(i = 0; i < lCols; i++){
index = lColIndices[i];
if(fabs(lObjCoeffs[i]) > etol)
nObjCoeffs[index] += (1 - beta) * lObjCoeffs[i] * lObjSense;
}
sSolver->setObjective(nObjCoeffs);
//int i(0);
if(0){
for(i = 0; i < sSolver->getNumCols(); i++){
std::cout << "betaobj " << sSolver->getObjCoefficients()[i] << std::endl;
}
}
if(0){
sSolver->writeLp("afterbeta");
//sSolver->writeMps("afterbeta");
}
if(0){
for(i = 0; i < sSolver->getNumCols(); i++){
std::cout << "obj " << sSolver->getObjCoefficients()[i] << std::endl;
std::cout << "upper " << sSolver->getColUpper()[i] << std::endl;
std::cout << "lower " << sSolver->getColLower()[i] << std::endl;
}
}
if(0){
dynamic_cast<OsiCbcSolverInterface *>
(sSolver)->getModelPtr()->messageHandler()->setLogLevel(0);
//.........这里部分代码省略.........
示例4: main
int main (int argc, const char *argv[])
{
/* Define your favorite OsiSolver.
CbcModel clones the solver so use solver1 up to the time you pass it
to CbcModel then use a pointer to cloned solver (model.solver())
*/
OsiClpSolverInterface solver1;
/* From now on we can build model in a solver independent way.
You can add rows one at a time but for large problems this is slow so
this example uses CoinBuild or CoinModel
*/
OsiSolverInterface * solver = &solver1;
// Data (is exmip1.mps in Mps/Sample
// Objective
double objValue[]={1.0,2.0,0.0,0.0,0.0,0.0,0.0,-1.0};
// Lower bounds for columns
double columnLower[]={2.5,0.0,0.0,0.0,0.5,0.0,0.0,0.0};
// Upper bounds for columns
double columnUpper[]={COIN_DBL_MAX,4.1,1.0,1.0,4.0,
COIN_DBL_MAX,COIN_DBL_MAX,4.3};
// Lower bounds for row activities
double rowLower[]={2.5,-COIN_DBL_MAX,-COIN_DBL_MAX,1.8,3.0};
// Upper bounds for row activities
double rowUpper[]={COIN_DBL_MAX,2.1,4.0,5.0,15.0};
// Matrix stored packed
int column[] = {0,1,3,4,7,
1,2,
2,5,
3,6,
4,7};
double element[] = {3.0,1.0,-2.0,-1.0,-1.0,
2.0,1.1,
1.0,1.0,
2.8,-1.2,
1.0,1.9};
int starts[]={0,5,7,9,11,13};
// Integer variables (note upper bound already 1.0)
int whichInt[]={2,3};
int numberRows=(int) (sizeof(rowLower)/sizeof(double));
int numberColumns=(int) (sizeof(columnLower)/sizeof(double));
#define BUILD 2
#if BUILD==1
// Using CoinBuild
// First do columns (objective and bounds)
int i;
// We are not adding elements
for (i=0;i<numberColumns;i++) {
solver->addCol(0,NULL,NULL,columnLower[i],columnUpper[i],
objValue[i]);
}
// mark as integer
for (i=0;i<(int) (sizeof(whichInt)/sizeof(int));i++)
solver->setInteger(whichInt[i]);
// Now build rows
CoinBuild build;
for (i=0;i<numberRows;i++) {
int startRow = starts[i];
int numberInRow = starts[i+1]-starts[i];
build.addRow(numberInRow,column+startRow,element+startRow,
rowLower[i],rowUpper[i]);
}
// add rows into solver
solver->addRows(build);
#else
/* using CoinModel - more flexible but still beta.
Can do exactly same way but can mix and match much more.
Also all operations are on building object
*/
CoinModel build;
// First do columns (objective and bounds)
int i;
for (i=0;i<numberColumns;i++) {
build.setColumnBounds(i,columnLower[i],columnUpper[i]);
build.setObjective(i,objValue[i]);
}
// mark as integer
for (i=0;i<(int) (sizeof(whichInt)/sizeof(int));i++)
build.setInteger(whichInt[i]);
// Now build rows
for (i=0;i<numberRows;i++) {
int startRow = starts[i];
int numberInRow = starts[i+1]-starts[i];
build.addRow(numberInRow,column+startRow,element+startRow,
rowLower[i],rowUpper[i]);
}
// add rows into solver
solver->loadFromCoinModel(build);
#endif
// Pass to solver
CbcModel model(*solver);
model.solver()->setHintParam(OsiDoReducePrint,true,OsiHintTry);
// Set up some cut generators and defaults
// Probing first as gets tight bounds on continuous
//.........这里部分代码省略.........
示例5: model
//.........这里部分代码省略.........
}
numberContinuous++;
} else {
if (fabs(value - floor(value + 0.5)) > 1.0e-12)
allIntegerCoeff = false;
}
} else {
sumFixed += lower[jColumn] * value;
}
}
double low = rowLower[iRow];
if (low > -1.0e20) {
low -= sumFixed;
if (fabs(low - floor(low + 0.5)) > 1.0e-12)
allIntegerCoeff = false;
}
double up = rowUpper[iRow];
if (up < 1.0e20) {
up -= sumFixed;
if (fabs(up - floor(up + 0.5)) > 1.0e-12)
allIntegerCoeff = false;
}
if (!allIntegerCoeff)
continue; // can't do
if (numberContinuous == 1) {
// see if really integer
// This does not allow for complicated cases
if (low == up) {
if (fabs(value1) > 1.0e-3) {
value1 = 1.0 / value1;
if (fabs(value1 - floor(value1 + 0.5)) < 1.0e-12) {
// integer
changed[numberChanged++] = jColumn1;
solver->setInteger(jColumn1);
if (upper[jColumn1] > 1.0e20)
solver->setColUpper(jColumn1, 1.0e20);
if (lower[jColumn1] < -1.0e20)
solver->setColLower(jColumn1, -1.0e20);
}
}
} else {
if (fabs(value1) > 1.0e-3) {
value1 = 1.0 / value1;
if (fabs(value1 - floor(value1 + 0.5)) < 1.0e-12) {
// This constraint will not stop it being integer
ignore[iRow] = 1;
}
}
}
} else if (numberContinuous == 2) {
if (low == up) {
/* need general theory - for now just look at 2 cases -
1 - +- 1 one in column and just costs i.e. matching objective
2 - +- 1 two in column but feeds into G/L row which will try and minimize
*/
if (fabs(value1) == 1.0 && value1*value2 == -1.0 && !lower[jColumn1]
&& !lower[jColumn2]) {
int n = 0;
int i;
double objChange = direction * (objective[jColumn1] + objective[jColumn2]);
double bound = CoinMin(upper[jColumn1], upper[jColumn2]);
bound = CoinMin(bound, 1.0e20);
for ( i = columnStart[jColumn1]; i < columnStart[jColumn1] + columnLength[jColumn1]; i++) {
int jRow = row[i];
double value = element[i];
if (jRow != iRow) {
示例6: mat
void
HeuristicInnerApproximation::extractInnerApproximation(Bonmin::OsiTMINLPInterface & nlp, OsiSolverInterface &si,
const double * x, bool getObj) {
printf("************ Start extracting inner approx");
int n;
int m;
int nnz_jac_g;
int nnz_h_lag;
Ipopt::TNLP::IndexStyleEnum index_style;
Bonmin::TMINLP2TNLP * problem = nlp.problem();
//Get problem information
problem->get_nlp_info(n, m, nnz_jac_g, nnz_h_lag, index_style);
Bonmin::vector<int> jRow(nnz_jac_g);
Bonmin::vector<int> jCol(nnz_jac_g);
Bonmin::vector<double> jValues(nnz_jac_g);
problem->eval_jac_g(n, NULL, 0, m, nnz_jac_g, jRow(), jCol(), NULL);
if(index_style == Ipopt::TNLP::FORTRAN_STYLE)//put C-style
{
for(int i = 0 ; i < nnz_jac_g ; i++){
jRow[i]--;
jCol[i]--;
}
}
//get Jacobian
problem->eval_jac_g(n, x, 1, m, nnz_jac_g, NULL, NULL,
jValues());
Bonmin::vector<double> g(m);
problem->eval_g(n, x, 1, m, g());
Bonmin::vector<int> nonLinear(m);
//store non linear constraints (which are to be removed from IA)
int numNonLinear = 0;
const double * rowLower = nlp.getRowLower();
const double * rowUpper = nlp.getRowUpper();
const double * colLower = nlp.getColLower();
const double * colUpper = nlp.getColUpper();
assert(m == nlp.getNumRows());
double infty = si.getInfinity();
double nlp_infty = nlp.getInfinity();
Bonmin::vector<Ipopt::TNLP::LinearityType> constTypes(m);
Bonmin::vector<Ipopt::TNLP::LinearityType> varTypes(n);
problem->get_constraints_linearity(m, constTypes());
problem->get_variables_linearity(n, varTypes());
for (int i = 0; i < m; i++) {
if (constTypes[i] == Ipopt::TNLP::NON_LINEAR) {
nonLinear[numNonLinear++] = i;
}
}
Bonmin::vector<double> rowLow(m - numNonLinear);
Bonmin::vector<double> rowUp(m - numNonLinear);
int ind = 0;
for (int i = 0; i < m; i++) {
if (constTypes[i] != Ipopt::TNLP::NON_LINEAR) {
if (rowLower[i] > -nlp_infty) {
// printf("Lower %g ", rowLower[i]);
rowLow[ind] = (rowLower[i]);
} else
rowLow[ind] = -infty;
if (rowUpper[i] < nlp_infty) {
// printf("Upper %g ", rowUpper[i]);
rowUp[ind] = (rowUpper[i]);
} else
rowUp[ind] = infty;
ind++;
}
}
CoinPackedMatrix mat(true, jRow(), jCol(), jValues(), nnz_jac_g);
mat.setDimensions(m, n); // In case matrix was empty, this should be enough
//remove non-linear constraints
mat.deleteRows(numNonLinear, nonLinear());
int numcols = nlp.getNumCols();
Bonmin::vector<double> obj(numcols);
for (int i = 0; i < numcols; i++)
obj[i] = 0.;
si.loadProblem(mat, nlp.getColLower(), nlp.getColUpper(),
obj(), rowLow(), rowUp());
const Bonmin::TMINLP::VariableType* variableType = problem->var_types();
for (int i = 0; i < n; i++) {
if ((variableType[i] == Bonmin::TMINLP::BINARY) || (variableType[i] == Bonmin::TMINLP::INTEGER))
si.setInteger(i);
}
if (getObj) {
bool addObjVar = false;
if (problem->hasLinearObjective()) {
double zero;
Bonmin::vector<double> x0(n, 0.);
problem->eval_f(n, x0(), 1, zero);
si.setDblParam(OsiObjOffset, -zero);
//Copy the linear objective and don't create a dummy variable.
problem->eval_grad_f(n, x, 1, obj());
si.setObjective(obj());
} else {
//.........这里部分代码省略.........
示例7: mexFunction
// mex function usage:
// [x,y,status] = mexosi(n_vars,n_cons,A,x_lb,x_ub,c,Ax_lb,Ax_ub,isMIP,isQP,vartype,Q,options)
// 0 1 2 3 4 5 6 7 8 9 10 11 12
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
// Enable printing in MATLAB
int loglevel = 0;
DerivedHandler *mexprinter = new DerivedHandler(); // assumed open
mexprinter->setLogLevel(loglevel);
// check that we have the right number of inputs
if(nrhs < 10) mexErrMsgTxt("At least 10 inputs required in call to mexosi. Bug in osi.m?...");
// check that we have the right number of outputs
if(nlhs < 3) mexErrMsgTxt("At least 3 ouptuts required in call to mexosi. Bug in osi.m?...");
// Get pointers to input values
const int n_vars = (int)*mxGetPr(prhs[0]);
const int n_cons = (int)*mxGetPr(prhs[1]);
const mxArray *A = prhs[2];
const double *x_lb = mxGetPr(prhs[3]);
const double *x_ub = mxGetPr(prhs[4]);
const double *c = mxGetPr(prhs[5]);
const double *Ax_lb = mxGetPr(prhs[6]);
const double *Ax_ub = mxGetPr(prhs[7]);
const bool isMIP = (bool)*(mxLogical*)mxGetData(prhs[8]);
const bool isQP = (bool)*(mxLogical*)mxGetData(prhs[9]);
mxLogical *isinteger = (mxLogical*)mxGetData(prhs[10]);
const mxArray* Q = prhs[11];
// process the options
int returnStatus = 0;
// extract row/col/value data from A
const mwIndex * A_col_starts = mxGetJc(A);
const mwIndex * A_row_index = mxGetIr(A);
const double * A_data = mxGetPr(A);
// figure out the number of non-zeros in A
int nnz = (int)(A_col_starts[n_vars] - A_col_starts[0]); // number of non-zeros
//mexPrintf("nnz = %d, n_vars = %d, n_cons = %d\n",nnz,n_vars,n_cons);
// we need to convert these into other types of indices for Coin to use them
std::vector<CoinBigIndex> A_col_starts_coin(A_col_starts,A_col_starts+n_vars+1);
std::vector<int> A_row_index_coin(A_row_index,A_row_index+nnz);
// declare the solver
OsiSolverInterface* pSolver;
// initialize the solver
if ( isMIP ) {
pSolver = new OsiCbcSolverInterface;
} else {
pSolver = new OsiClpSolverInterface;
}
// OsiCbcSolverInterface is deprecated and CbcModel should be used instead but don't
// know how to get that working with loadProblem.
// OsiCbcSolverInterface solver1;
// CbcModel model(solver1);
// CbcMain0(model);
// OsiSolverInterface * pSolver = model.solver();
if (nrhs>12) { // get stuff out of the options structure if provided
// Finish me
}
// mexPrintf("Setting Log Level to 0.\n");
// load the problem
mexPrintf("Loading the problem.\n");
pSolver->loadProblem( n_vars, n_cons, // problem size
&A_col_starts_coin[0], &A_row_index_coin[0], A_data, // the A matrix
x_lb, x_ub, c, // the objective and bounds
Ax_lb, Ax_ub ); // the constraint bounds
// pSolver->messageHandler()->setLogLevel(0); // This doesn't seem to work
pSolver->setHintParam(OsiDoReducePrint,true,OsiHintTry);
// deal with integer inputs
if ( isMIP ) {
for(int i=0;i<n_vars;i++) {
if (isinteger[i]) pSolver->setInteger(i);
}
}
if (isQP) {
error("QP is not working yet");
// need to call loadQuadraticObjective here ???
}
// CbcModel model(pSolver);
// model.solver()->setHintParam(OsiDoReducePrint,true,OsiHintTry);
// solve the problem
//mexPrintf("Trying to solve the problem.\n");
if (isMIP) {
pSolver->branchAndBound();
// model.branchAndBound();
} else {
// model.initialSolve();
pSolver->initialSolve();
}
// Allocate memory for return data
plhs[0] = mxCreateDoubleMatrix(n_vars,1, mxREAL); // for the solution
plhs[1] = mxCreateDoubleMatrix(n_cons,1, mxREAL); // for the constraint prices
//.........这里部分代码省略.........
示例8: main
int main (int argc, const char *argv[])
{
OsiClpSolverInterface solver1;
//#define USE_OSI_NAMES
#ifdef USE_OSI_NAMES
// Say we are keeping names (a bit slower this way)
solver1.setIntParam(OsiNameDiscipline,1);
#endif
// Read in model using argv[1]
// and assert that it is a clean model
std::string mpsFileName;
#if defined(SAMPLEDIR)
mpsFileName = SAMPLEDIR "/p0033.mps";
#else
if (argc < 2) {
fprintf(stderr, "Do not know where to find sample MPS files.\n");
exit(1);
}
#endif
if (argc>=2) mpsFileName = argv[1];
int numMpsReadErrors = solver1.readMps(mpsFileName.c_str(),"");
assert(numMpsReadErrors==0);
// Strip off integer information and save
int numberColumns = solver1.getNumCols();
char * integer = new char[numberColumns];
int i;
for (i=0;i<numberColumns;i++) {
if (solver1.isInteger(i)) {
integer[i]=1;
solver1.setContinuous(i);
} else {
integer[i]=0;
}
}
// Pass to Cbc initialize defaults
CbcModel model(solver1);
CbcMain0(model);
// Solve just to show there are no integers
model.branchAndBound();
// Set cutoff etc back in model and solver
model.resetModel();
// Solver was cloned so get it
OsiSolverInterface * solver = model.solver();
// Put back integers. Here the user could do anything really
#define ADD_DIRECTLY
#ifndef ADD_DIRECTLY
for (i=0;i<numberColumns;i++) {
if (integer[i])
solver->setInteger(i);
}
#else
CbcObject ** objects = new CbcObject * [ numberColumns];
int n=0;
for (i=0;i<numberColumns;i++) {
if (integer[i]) {
CbcSimpleIntegerDynamicPseudoCost * newObject =
new CbcSimpleIntegerDynamicPseudoCost(&model,i);
objects[n++]=newObject;
}
}
model.addObjects(n,objects);
for (i=0;i<n;i++)
delete objects[i];
delete [] objects;
#endif
delete [] integer;
/* 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,model);
} else {
const char * argv2[]={"driver3","-solve","-quit"};
CbcMain1(3,argv2,model);
}
// Print solution if finished (could get from model.bestSolution() as well
if (solver->getObjValue()*solver->getObjSense()<1.0e50) {
const double * solution = solver->getColSolution();
int iColumn;
std::cout<<std::setiosflags(std::ios::fixed|std::ios::showpoint)<<std::setw(14);
std::cout<<"--------------------------------------"<<std::endl;
#ifdef USE_OSI_NAMES
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<<" "<<std::setw(8)<<setiosflags(std::ios::left)<<solver->getColName(iColumn)
<<resetiosflags(std::ios::adjustfield)<<std::setw(14)<<" "<<value<<std::endl;
}
#else
// names may not be in current solver - use original
//.........这里部分代码省略.........
示例9: etol
//.........这里部分代码省略.........
index1 = lRowIndices[i];
start = matStarts[index1];
end = start + matrix->getVectorSize(index1);
for(j = start; j < end; j++){
index2 = matIndices[j];
//tmp = findIndex(index, lCols, lColIndices);
tmp = binarySearch(0, lCols - 1, index2, lColIndices);
if(tmp > -1)
row.insert(tmp, matElements[j]);
}
newMat->appendRow(row);
}
*/
for(i = 0; i < lRows; i++){
CoinPackedVector row;
index1 = lRowIndices[i];
for(j = 0; j < lCols; j++){
index2 = lColIndices[j];
tmp = matrix->getCoefficient(index1, index2);
row.insert(j, tmp);
}
newMat->appendRow(row);
}
/*
nSolver->assignProblem(newMat, colLb, colUb,
objCoeffs, rowLb, rowUb);
*/
nSolver->loadProblem(*newMat, colLb, colUb,
objCoeffs, rowLb, rowUb);
for(i = 0; i < intCnt; i++){
nSolver->setInteger(integerVars[i]);
}
//nSolver->setInteger(integerVars, intCnt);
nSolver->setObjSense(objSense); //1 min; -1 max
nSolver->setHintParam(OsiDoReducePrint, true, OsiHintDo);
#if 0
if(0){
dynamic_cast<OsiCbcSolverInterface *>
(nSolver)->getModelPtr()->messageHandler()->setLogLevel(0);
}
else{
dynamic_cast<OsiSymSolverInterface *>
(nSolver)->setSymParam("prep_level", -1);
dynamic_cast<OsiSymSolverInterface *>
(nSolver)->setSymParam("verbosity", -2);
dynamic_cast<OsiSymSolverInterface *>
(nSolver)->setSymParam("max_active_nodes", 1);
}
#endif
delete [] integerVars;
}else{
nSolver = solver_;
}
#define SYM_VERSION_IS_WS strcmp(SYMPHONY_VERSION, "WS")
#if SYMPHONY_VERSION_IS_WS
示例10: mat
void
HeuristicInnerApproximation::extractInnerApproximation(OsiTMINLPInterface & nlp, OsiSolverInterface &si,
const double * x, bool getObj) {
int n;
int m;
int nnz_jac_g;
int nnz_h_lag;
Ipopt::TNLP::IndexStyleEnum index_style;
TMINLP2TNLP * problem = nlp.problem();
//Get problem information
problem->get_nlp_info(n, m, nnz_jac_g, nnz_h_lag, index_style);
vector<int> jRow(nnz_jac_g);
vector<int> jCol(nnz_jac_g);
vector<double> jValues(nnz_jac_g);
problem->eval_jac_g(n, NULL, 0, m, nnz_jac_g, jRow(), jCol(), NULL);
if(index_style == Ipopt::TNLP::FORTRAN_STYLE)//put C-style
{
for(int i = 0 ; i < nnz_jac_g ; i++){
jRow[i]--;
jCol[i]--;
}
}
//get Jacobian
problem->eval_jac_g(n, x, 1, m, nnz_jac_g, NULL, NULL,
jValues());
vector<double> g(m);
problem->eval_g(n, x, 1, m, g());
vector<int> nonLinear(m);
//store non linear constraints (which are to be removed from IA)
int numNonLinear = 0;
const double * rowLower = nlp.getRowLower();
const double * rowUpper = nlp.getRowUpper();
const double * colLower = nlp.getColLower();
const double * colUpper = nlp.getColUpper();
assert(m == nlp.getNumRows());
double infty = si.getInfinity();
double nlp_infty = nlp.getInfinity();
vector<Ipopt::TNLP::LinearityType> constTypes(m);
problem->get_constraints_linearity(m, constTypes());
for (int i = 0; i < m; i++) {
if (constTypes[i] == Ipopt::TNLP::NON_LINEAR) {
nonLinear[numNonLinear++] = i;
}
}
vector<double> rowLow(m - numNonLinear);
vector<double> rowUp(m - numNonLinear);
int ind = 0;
for (int i = 0; i < m; i++) {
if (constTypes[i] != Ipopt::TNLP::NON_LINEAR) {
if (rowLower[i] > -nlp_infty) {
// printf("Lower %g ", rowLower[i]);
rowLow[ind] = (rowLower[i]);
} else
rowLow[ind] = -infty;
if (rowUpper[i] < nlp_infty) {
// printf("Upper %g ", rowUpper[i]);
rowUp[ind] = (rowUpper[i]);
} else
rowUp[ind] = infty;
ind++;
}
}
CoinPackedMatrix mat(true, jRow(), jCol(), jValues(), nnz_jac_g);
mat.setDimensions(m, n); // In case matrix was empty, this should be enough
//remove non-linear constraints
mat.deleteRows(numNonLinear, nonLinear());
int numcols = nlp.getNumCols();
vector<double> obj(numcols);
for (int i = 0; i < numcols; i++)
obj[i] = 0.;
si.loadProblem(mat, nlp.getColLower(), nlp.getColUpper(),
obj(), rowLow(), rowUp());
const Bonmin::TMINLP::VariableType* variableType = problem->var_types();
for (int i = 0; i < n; i++) {
if ((variableType[i] == TMINLP::BINARY) || (variableType[i]
== TMINLP::INTEGER))
si.setInteger(i);
}
if (getObj) {
bool addObjVar = false;
if (problem->hasLinearObjective()) {
double zero;
vector<double> x0(n, 0.);
problem->eval_f(n, x0(), 1, zero);
si.setDblParam(OsiObjOffset, -zero);
//Copy the linear objective and don't create a dummy variable.
problem->eval_grad_f(n, x, 1, obj());
si.setObjective(obj());
} else {
addObjVar = true;
}
//.........这里部分代码省略.........
示例11: eq
//.........这里部分代码省略.........
// -7x1 + 4x2 <= 1
// x1, x2 >= 0 and x1, x2 integer
// Slacks are s1, s2, s3, s4
//Test that problem is correct
// Optimal Basis is x1, x2, s3, s4 with tableau
// x1 0.25 s1 -0.25 s2 = 0.5
// x2 0.25 s1 0.25 s2 = 1
// -2.75 s1 0.75 s2 s3 = 0.5
// 0.75 s1 -2.75 s2 s4 = 0.5
// z= -0.25 s1 -0.25 s2 = -1
// Gomory cut from variable x1 is x2 <= 0.5
// Can be improved by first pivoting s2 in and s4 out, then s1 in and s3 out
// to x2 <= 0.25
{
int start[2] = {0,4};
int length[2] = {4,4};
int rows[8] = {0,1,2,3,0,1,2,3};
double elements[8] = {2.0,-2.0,7.0,-7.0,2.0,2.0,4.0,4.0};
CoinPackedMatrix columnCopy(true,4,2,8,elements,rows,start,length);
double rowLower[4]={-COIN_DBL_MAX,-COIN_DBL_MAX,
-COIN_DBL_MAX,-COIN_DBL_MAX};
double rowUpper[4]={3.,1.,8.,1.};
double colLower[2]={0.0,0.0};
double colUpper[2]={1.0,1.0};
double obj[2]={-1,-1};
int intVar[2]={0,1};
OsiSolverInterface * siP = si->clone();
siP->loadProblem(columnCopy, colLower, colUpper, obj, rowLower, rowUpper);
siP->setInteger(intVar,2);
CglLandP test;
test.setLogLevel(2);
test.parameter().sepSpace = CglLandP::Full;
siP->resolve();
// Test generateCuts method
{
OsiCuts cuts;
test.generateCuts(*siP,cuts);
cuts.printCuts();
assert(cuts.sizeRowCuts()==1);
OsiRowCut aCut = cuts.rowCut(0);
assert(eq(aCut.lb(), -.0714286));
CoinPackedVector row = aCut.row();
if (row.getNumElements() == 1)
{
assert(row.getIndices()[0]==1);
assert(eq(row.getElements()[0], -4*.0714286));
}
else if (row.getNumElements() == 2)
{
assert(row.getIndices()[0]==0);
assert(eq(row.getElements()[0], 0.));
assert(row.getIndices()[1]==1);
assert(eq(row.getElements()[1], -1));
}
OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
siP->resolve();
}
if (0)
{
OsiCuts cuts;
示例12: eq
//.........这里部分代码省略.........
CoinBigIndex * start = new CoinBigIndex [ncol+1];
memset(start,0,ncol*sizeof(CoinBigIndex ));
int * row = new int[nel];
int i;
for (i=0;i<nel;i++) {
x=fscanf(fp,"%d %lg %lg",col1+i,el1+i,sol1+i);
if (x<=0)
throw("bad fscanf");
printf("[%d, e=%g, v=%g] ",col1[i],el1[i],sol1[i]);
start[col1[i]]=1;
row[i]=0;
}
printf("\n");
// Setup
OsiSolverInterface * siP = baseSiP->clone();
double lo=-1.0e30;
double * upper = new double[ncol];
start[ncol]=nel;
int last=0;
for (i=0;i<ncol;i++) {
upper[i]=1.0;
int marked=start[i];
start[i]=last;
if (marked)
last++;
}
siP->loadProblem(ncol,1,start,row,el1,NULL,upper,NULL,&lo,&up);
// use upper for solution
memset(upper,0,ncol*sizeof(double));
for (i=0;i<nel;i++) {
int icol=col1[i];
upper[icol]=sol1[i];
siP->setInteger(icol);
}
siP->setColSolution(upper);
delete [] sol1;
delete [] el1;
delete [] col1;
delete [] start;
delete [] row;
delete [] upper;
CglKnapsackCover kccg;
OsiCuts cuts;
// Test generateCuts method
kccg.generateCuts(*siP,cuts);
// print out and compare to known cuts
int numberCuts = cuts.sizeRowCuts();
if (numberCuts) {
for (i=0;i<numberCuts;i++) {
OsiRowCut * thisCut = cuts.rowCutPtr(i);
int n=thisCut->row().getNumElements();
printf("Cut %d has %d entries, rhs %g %g =>",i,n,thisCut->lb(),
thisCut->ub());
int j;
const int * index = thisCut->row().getIndices();
const double * element = thisCut->row().getElements();
for (j=0;j<n;j++) {
printf(" (%d,%g)",index[j],element[j]);
}
printf("\n");
}
}
fclose(fp);
示例13: finalModelX
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);
//.........这里部分代码省略.........
示例14: cpropagation_preprocess
OsiSolverInterface* cpropagation_preprocess(CPropagation *cp, int nindexes[])
{
if(cp->varsToFix == 0)
{
/* printf("There are no variables to remove from the problem!\n"); */
return NULL; /* returns a pointer to original solver */
}
const double *colLb = problem_vars_lower_bound(cp->problem), *colUb = problem_vars_upper_bound(cp->problem);
const double *objCoef = problem_vars_obj_coefs(cp->problem);
const char *ctype = problem_vars_type(cp->problem);
double sumFixedObj = 0.0; /* stores the sum of objective coefficients of all variables fixed to 1 */
OsiSolverInterface *preProcSolver = new OsiClpSolverInterface();
preProcSolver->setIntParam(OsiNameDiscipline, 2);
preProcSolver->messageHandler()->setLogLevel(0);
preProcSolver->setHintParam(OsiDoReducePrint,true,OsiHintTry);
//preProcSolver->setObjName(cp->solver->getObjName());
for(int i = 0, j = 0; i < problem_num_cols(cp->problem); i++)
{
nindexes[i] = -1;
if(cp->isToFix[i] == UNFIXED)
{
preProcSolver->addCol(0, NULL, NULL, colLb[i], colUb[i], objCoef[i]);
preProcSolver->setColName(j, problem_var_name(cp->problem, i));
if(problem_var_type(cp->problem, i) == CONTINUOUS)
preProcSolver->setContinuous(j);
else
preProcSolver->setInteger(j);
nindexes[i] = j++;
}
else if(cp->isToFix[i] == ACTIVATE)
sumFixedObj += objCoef[i];
}
if(fabs(sumFixedObj) > EPS)
{
/* adding a variable with cost equals to the sum of all coefficients of variables fixed to 1 */
preProcSolver->addCol(0, NULL, NULL, 1.0, 1.0, sumFixedObj);
preProcSolver->setColName(preProcSolver->getNumCols()-1, "sumFixedObj");
preProcSolver->setInteger(preProcSolver->getNumCols()-1);
}
for(int idxRow = 0; idxRow < problem_num_rows(cp->problem); idxRow++)
{
const int nElements = problem_row_size(cp->problem, idxRow);
const int *idxs = problem_row_idxs(cp->problem, idxRow);
const double *coefs = problem_row_coefs(cp->problem, idxRow);
vector< int > vidx; vidx.reserve(problem_num_cols(cp->problem));
vector< double > vcoef; vcoef.reserve(problem_num_cols(cp->problem));
double activeCoefs = 0.0;
for(int i = 0; i < nElements; i++)
{
if(cp->isToFix[idxs[i]] == UNFIXED)
{
assert(nindexes[idxs[i]] >= 0 && nindexes[idxs[i]] < problem_num_cols(cp->problem));
vidx.push_back(nindexes[idxs[i]]);
vcoef.push_back(coefs[i]);
}
else if(cp->isToFix[idxs[i]] == ACTIVATE)
activeCoefs += coefs[i];
}
if(!vidx.empty())
{
double rlb, rub;
const char sense = problem_row_sense(cp->problem, idxRow);
if(sense == 'E')
{
rlb = problem_row_rhs(cp->problem, idxRow) - activeCoefs;
rub = problem_row_rhs(cp->problem, idxRow) - activeCoefs;
}
else if(sense == 'L')
{
rlb = preProcSolver->getInfinity();
rub = problem_row_rhs(cp->problem, idxRow) - activeCoefs;
}
else if(sense == 'G')
{
rlb = problem_row_rhs(cp->problem, idxRow) - activeCoefs;
rub = preProcSolver->getInfinity();
}
else
{
fprintf(stderr, "Error: invalid type of constraint!\n");
exit(EXIT_FAILURE);
}
preProcSolver->addRow((int)vcoef.size(), &vidx[0], &vcoef[0], rlb, rub);
preProcSolver->setRowName(idxRow, problem_row_name(cp->problem, idxRow));
}
}
return preProcSolver;
}
示例15: matrix
//.........这里部分代码省略.........
// 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) {
#ifdef DEBUG_BON_HEURISTIC_DIVE_MIP
cout<<"It should be infeasible because: "<<endl;
cout<<"variable "<<iColumn<<" is not integer"<<endl;
#endif
feasible = false;
break;
}
else {