static int dumpx (CPXENVptr env, CPXLPptr lp) { int cols, c, surplus, status = 0; char *name, buffer[8]; double x; cols = CPXgetnumcols (env, lp); for (c = 0; c < cols; ++c) { status = CPXgetx (env, lp, &x, c, c); if ( status ) { fprintf (stderr, "Failed to read value for column %d: %d\n", c, status); goto TERMINATE; } status = CPXgetcolname (env, lp, &name, buffer, sizeof (buffer), &surplus, c, c); if ( status ) { fprintf (stderr, "Failed to read name for column %d: %d\n", c, status); goto TERMINATE; } printf ("%8s: %15.6f\n", name, x); } TERMINATE: return status; } /* END dumpx */
void ProblemMaster::print_var_P(CEnv env, Prob lp) { cout << "PRIMAL VARIABLES: " << endl; int cur_numcols = CPXgetnumcols(env, lp); int surplus; status = CPXgetcolname(env, lp, NULL, NULL, 0, &surplus, 0, cur_numcols - 1); int cur_colnamespace = -surplus; // the space needed to save the names // allocate memory char** cur_colname = (char **) malloc(sizeof(char *) * cur_numcols); char* cur_colnamestore = (char *) malloc(cur_colnamespace); // get the names CPXgetcolname(env, lp, cur_colname, cur_colnamestore, cur_colnamespace, &surplus, 0, cur_numcols - 1); // print index, name and value of each column for (int i = 0; i < cur_numcols; i++) cout << cur_colname[i] << " = " << varVals[i] << endl; // free free(cur_colname); free(cur_colnamestore); }
void ProblemMaster::set_var_P(CEnv env, Prob lp) { int cur_numcols = CPXgetnumcols(env, lp); varVals.clear(); varVals.resize(cur_numcols); CHECKED_CPX_CALL(CPXgetx, env, lp, &varVals[0], 0, cur_numcols - 1); }
double solve() { const int numcols = vars_.size(); const int numrows = bnd_.size(); int status; lp_ = CPXcreateprob(env_, &status, "PRactIP"); if (lp_==NULL) throw std::runtime_error("failed to create LP"); unsigned int n_nonzero=0; for (unsigned int i=0; i!=m_.size(); ++i) n_nonzero += m_[i].size(); std::vector<int> matbeg(numcols, 0); std::vector<int> matcnt(numcols, 0); std::vector<int> matind(n_nonzero); std::vector<double> matval(n_nonzero); for (unsigned int i=0, k=0; i!=m_.size(); ++i) { matbeg[i] = i==0 ? 0 : matbeg[i-1]+matcnt[i-1]; matcnt[i] = m_[i].size(); for (unsigned int j=0; j!=m_[i].size(); ++j, ++k) { matind[k] = m_[i][j].first; matval[k] = m_[i][j].second; } } m_.clear(); status = CPXcopylp(env_, lp_, numcols, numrows, dir_==IP::MIN ? CPX_MIN : CPX_MAX, &coef_[0], &rhs_[0], &bnd_[0], &matbeg[0], &matcnt[0], &matind[0], &matval[0], &vlb_[0], &vub_[0], &rngval_[0] ); vlb_.clear(); vub_.clear(); status = CPXcopyctype(env_, lp_, &vars_[0]); vars_.clear(); CPXsetintparam(env_, CPXPARAM_MIP_Display, 0); CPXsetintparam(env_, CPXPARAM_Barrier_Display, 0); CPXsetintparam(env_, CPXPARAM_Tune_Display, 0); CPXsetintparam(env_, CPXPARAM_Network_Display, 0); CPXsetintparam(env_, CPXPARAM_Sifting_Display, 0); CPXsetintparam(env_, CPXPARAM_Simplex_Display, 0); status = CPXmipopt(env_, lp_); double objval; status = CPXgetobjval(env_, lp_, &objval); res_cols_.resize(CPXgetnumcols(env_, lp_)); status = CPXgetx(env_, lp_, &res_cols_[0], 0, res_cols_.size()-1); return objval; }
static int optimize_and_report (CPXENVptr env, CPXLPptr lp, int *solstat_p, double *objval_p) { int status = 0; double x[NUMCOLS]; double pi[TOTROWS]; double slack[TOTROWS]; double dj[NUMCOLS]; int i, j; int cur_numrows, cur_numcols; status = CPXqpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize QP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, solstat_p, objval_p, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", *solstat_p); printf ("Solution value = %f\n\n", *objval_p); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using what was passed to CPXcopylp. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } TERMINATE: return (status); } /* END optimize_and_report */
int CPXPUBLIC CPX_CutCallback(CPXCENVptr xenv, void *cbdata, int wherefrom, void *cbhandle, int *useraction_p) { // cout << "Entering CPX Callback\n" << flush; CPXLPptr nodelp; CPXgetcallbacknodelp(xenv, cbdata, wherefrom, &nodelp); CoinCallbacks* ccc = (CoinCallbacks*)cbhandle; int length = CPXgetnumcols(xenv,nodelp) - 1; //hey, don't ask me! some VERY WIERD PHENOMENON... crap double objVal; double* solution = new double[length]; CPXgetcallbacknodeobjval(xenv, cbdata, wherefrom, &objVal); CPXgetcallbacknodex(xenv, cbdata, wherefrom, solution, 0, length-1); OsiCuts* cuts = new OsiCuts(); CoinCallbacks::CutReturn ret = ccc->cutCallback(objVal, solution, cuts); if(ret == CoinCallbacks::CR_AddCuts) { for(int i = cuts->sizeRowCuts(); i-->0;) { const OsiRowCut& c = cuts->rowCut(i); const CoinPackedVector& vec = c.row(); if(c.globallyValid()) /* Old Cplex-Versions did NOT have the last parameter (now set to "false"). * If you compile agains an older CPLEX version, simple *REMOVE* * ", false" * from the calls to CPXcutscallbackadd */ CPXcutcallbackadd(xenv, cbdata, wherefrom, vec.getNumElements(), c.rhs(), c.sense(), vec.getIndices(), vec.getElements(), false); //default to non-purgable cuts else CPXcutcallbackaddlocal(xenv, cbdata, wherefrom, vec.getNumElements(), c.rhs(), c.sense(), vec.getIndices(), vec.getElements()); cuts->eraseRowCut(i); } if(cuts->sizeColCuts() > 0) { cerr << "ColCuts currently not supported...\n"; OGDF_THROW_PARAM(LibraryNotSupportedException, lnscFunctionNotImplemented); } } *useraction_p = ( ret == CoinCallbacks::CR_Error) ? CPX_CALLBACK_FAIL : ( ret == CoinCallbacks::CR_AddCuts ) ? CPX_CALLBACK_SET : CPX_CALLBACK_DEFAULT; delete cuts; delete[] solution; // cout << "Leaving CPX Callback\n" << flush; return 0; // success }
// solution initialisation int cplex_solver::init_solutions() { int status; int cur_numcols = CPXgetnumcols (env, lp); if (solution != (double *)NULL) free(solution); if ((solution = (double *)malloc(nb_vars*sizeof(double))) == (double *)NULL) { fprintf (stderr, "cplex_solver: init_solutions: cannot get enough memory to store solutions.\n"); exit(-1); } status = CPXgetx (env, lp, solution, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "cplex_solver: init_solutions: failed to get solutions.\n"); exit(-1); } else if (verbosity >= VERBOSE) { // Output model to file (when requested) writesol(C_STR("sol-cplex.xml")); } return 0; }
void CplexSolver::add(ColumnBuffer & buffer) { buffer.add_last_begin(); if (buffer.name().empty()) { CPXaddcols(_env, _prob, buffer.size(), buffer.nz(), buffer.rhsObj(), buffer.begin(), buffer.index(), buffer.value(), buffer.lower(), buffer.upper(), NULL); } else { assert((int )buffer.name().size() == buffer.size() && "you should provide a name for each element"); std::vector<char*> cpxName(buffer.name().size()); for (int i(0); i < buffer.name().size(); ++i) { cpxName[i] = const_cast<char*>(buffer.name()[i].c_str()); } CPXaddcols(_env, _prob, buffer.size(), buffer.nz(), buffer.rhsObj(), buffer.begin(), buffer.index(), buffer.value(), buffer.lower(), buffer.upper(), cpxName.data()); } buffer.rem_last_begin(); if (!buffer.only_continous()) { _is_mip = true; std::vector<int> sequence(buffer.size()); for (int i(0); i < buffer.size(); ++i) { sequence[i] = CPXgetnumcols(_env, _prob) - buffer.size() + i; } CPXchgctype(_env, _prob, buffer.size(), sequence.data(), buffer.type()); } }
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval, relobj; double *x = NULL; MYCB info; CPXENVptr env = NULL; CPXLPptr lp = NULL; CPXLPptr lpclone = NULL; int j; int cur_numcols; /* Check the command line arguments */ if ( argc != 2 ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn on traditional search for use with control callbacks */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_Search, CPX_MIPSEARCH_TRADITIONAL); if ( status ) goto TERMINATE; /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* We transfer a problem with semi-continuous or semi-integer variables to a MIP problem by adding variables and constraints. So in MIP callbacks, the size of the problem is changed and this example won't work for such problems */ if ( CPXgetnumsemicont (env, lp) + CPXgetnumsemiint (env, lp) ) { fprintf (stderr, "Not for problems with semi-continuous or semi-integer variables.\n"); goto TERMINATE; } /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numcols store the current number of columns */ cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "Memory allocation failed.\n"); goto TERMINATE; } /* Solve relaxation of MIP */ /* Clone original model */ lpclone = CPXcloneprob (env, lp, &status); if ( status ) { fprintf (stderr, "Failed to clone problem.\n"); goto TERMINATE; } /* Relax */ status = CPXchgprobtype (env, lpclone, CPXPROB_LP); if ( status ) { fprintf (stderr, "Failed to relax problem.\n"); goto TERMINATE; } /* Solve LP relaxation of original model using "default" LP solver */ status = CPXlpopt (env, lpclone); if ( status ) { fprintf (stderr, "Failed to solve relaxation.\n"); goto TERMINATE; } status = CPXsolution (env, lpclone, NULL, &relobj, x, NULL, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to extract solution.\n"); goto TERMINATE; } printf ("Solution status = %d", CPXgetstat(env,lpclone)); printf ("\nLP relaxation objective: %.4e\n\n", relobj); /* Set up solve callback */ info.count = 0; info.mip = lp; info.relx = x; status = CPXsetsolvecallbackfunc (env, &solvecallback, (void *) &info); if ( status ) { fprintf (stderr, "Failed to set solve callback.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Solution status %d.\n", solstat); printf ("Objective value %.10g\n", objval); status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the cloned lp as allocated by CPXcloneprob, if necessary */ if ( lpclone != NULL ) { status = CPXfreeprob (env, &lpclone); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int CPLEXAddConstraint(LinEquation* InEquation) { int Status = 0; if (InEquation->ConstraintType != QUADRATIC && InEquation->ConstraintType != LINEAR) { FErrorFile() << "This constraint type is not supported in CPLEX: " << InEquation->ConstraintType << endl; FlushErrorFile(); return FAIL; } //First I check the number of rows. If it's larger than the index, then this constraint already exists and is only being changed int NumberRows = CPXgetnumrows (CPLEXenv, CPLEXModel); if (NumberRows <= InEquation->Index) { char* Sense = new char[1]; if (InEquation->EqualityType == EQUAL) { if (InEquation->QuadOne.size() > 0) { delete [] Sense; FErrorFile() << "Quadratic constraints cannot be equivalent constraints in CPLEX." << endl; FlushErrorFile(); return FAIL; } else { Sense[0] = 'E'; } } else if (InEquation->EqualityType == LESS) { Sense[0] = 'L'; } else if (InEquation->EqualityType == GREATER) { Sense[0] = 'G'; } else { delete [] Sense; FErrorFile() << "Unrecognized constraint type: " << InEquation->ConstraintType << endl; FlushErrorFile(); return FAIL; } double* Rhs = new double[1]; Rhs[0] = InEquation->RightHandSide; int* ColInd = NULL; int* RowInd = NULL; double* Coeff = NULL; if (InEquation->Variables.size() > 0) { ColInd = new int[int(InEquation->Variables.size())]; RowInd = new int[int(InEquation->Variables.size())]; Coeff = new double[int(InEquation->Variables.size())]; for (int i=0; i < int(InEquation->Variables.size()); i++) { Coeff[i] = InEquation->Coefficient[i]; RowInd[i] = 0; ColInd[i] = InEquation->Variables[i]->Index; } } if (InEquation->QuadOne.size() > 0) { if (CPXgetprobtype(CPLEXenv, CPLEXModel) == CPXPROB_LP) { Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_QP); } else if (CPXgetprobtype(CPLEXenv, CPLEXModel) == CPXPROB_MILP) { Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_MIQP); } int *QuadCol = new int[int(InEquation->QuadOne.size())]; int *QuadRow = new int[int(InEquation->QuadTwo.size())]; double *QuadCoeff = new double[int(InEquation->QuadCoeff.size())]; for (int i=0; i < int(InEquation->QuadOne.size()); i++) { QuadCol[i] = InEquation->QuadOne[i]->Index; QuadRow[i] = InEquation->QuadTwo[i]->Index; QuadCoeff[i] = InEquation->QuadCoeff[i]; } Status = CPXaddqconstr(CPLEXenv, CPLEXModel, int(InEquation->Variables.size()), int(InEquation->QuadOne.size()), Rhs[0], int(Sense[0]), ColInd, Coeff, QuadRow, QuadCol, QuadCoeff, NULL); delete [] QuadCol; delete [] QuadRow; delete [] QuadCoeff; } else if (InEquation->Variables.size() > 0) { string StrName = GetConstraintName(InEquation); char** Name = new char*; Name[0] = new char[StrName.length()+1]; strcpy(Name[0],StrName.data()); if ((InEquation->ConstraintMeaning.compare("chemical potential constraint") == 0) && (InEquation->Loaded == false) && (GetParameter("Check potential constraints feasibility").compare("1") == 0)) { Rhs[0] = InEquation->LoadedRightHandSide; Sense[0] = 'L'; } else if ((InEquation->ConstraintMeaning.compare("chemical potential constraint") == 0) && (InEquation->Loaded == false) && (InEquation->RightHandSide > 0.9*FLAG)){ Rhs[0] = FLAG; Sense[0] = 'L'; } Status = CPXaddrows(CPLEXenv, CPLEXModel, 0, 1, int(InEquation->Variables.size()), Rhs, Sense, RowInd, ColInd, Coeff, NULL, Name); delete [] Name[0]; delete [] Name; delete [] ColInd; delete [] RowInd; delete [] Coeff; } delete [] Rhs; delete [] Sense; if (Status) { FErrorFile() << "Failed to add constraint: " << InEquation->Index << endl; FlushErrorFile(); return FAIL; } } else { if (InEquation->QuadOne.size() > 0) { FErrorFile() << "Cannot change a quadratic constraint." << endl; FlushErrorFile(); return FAIL; } else { int NumberOfColumns = CPXgetnumcols(CPLEXenv, CPLEXModel); //First I reset all of the coefficients to zero for (int i=0; i < NumberOfColumns; i++) { Status = CPXchgcoef (CPLEXenv, CPLEXModel, InEquation->Index, i, 0); if (Status) { FErrorFile() << "Failed to change constraint: " << InEquation->Index << endl; FlushErrorFile(); return FAIL; } } //Next I set all of the nonzero coefficients according to the input equation for (int i=0; i < int(InEquation->Variables.size()); i++) { Status = CPXchgcoef (CPLEXenv, CPLEXModel, InEquation->Index, InEquation->Variables[i]->Index, InEquation->Coefficient[i]); if (Status) { FErrorFile() << "Failed to change constraint: " << InEquation->Index << endl; FlushErrorFile(); return FAIL; } } char* Sense = new char[1]; if (InEquation->ConstraintMeaning.compare("chemical potential constraint") == 0 && InEquation->Loaded == false) { Sense[0] = 'L'; Status = CPXchgcoef (CPLEXenv, CPLEXModel, InEquation->Index, -1, InEquation->LoadedRightHandSide); Status = CPXchgsense (CPLEXenv, CPLEXModel, 1, &(InEquation->Index), Sense); } else { //Now I change the RHS of the constraint Status = CPXchgcoef (CPLEXenv, CPLEXModel, InEquation->Index, -1, InEquation->RightHandSide); //Also change the sense of the constraint if nec if (InEquation->EqualityType == EQUAL) { if (InEquation->QuadOne.size() > 0) { delete [] Sense; FErrorFile() << "Quadratic constraints cannot be equivalent constraints in CPLEX." << endl; FlushErrorFile(); return FAIL; } else { Sense[0] = 'E'; } } else if (InEquation->EqualityType == LESS) { Sense[0] = 'L'; } else if (InEquation->EqualityType == GREATER) { Sense[0] = 'G'; } else { delete [] Sense; FErrorFile() << "Unrecognized constraint type: " << InEquation->ConstraintType << endl; FlushErrorFile(); return FAIL; } Status = CPXchgsense (CPLEXenv, CPLEXModel, 1, &(InEquation->Index), Sense); if (Status) { FErrorFile() << "Failed to change constraint: " << InEquation->Index << endl; FlushErrorFile(); return FAIL; } } } } return SUCCESS; }
int CplexSolver::ncols() const { return CPXgetnumcols(_env, _prob); }
int main (int argc, char **argv) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double *x = NULL; double *pi = NULL; double *slack = NULL; double *dj = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int i, j; int cur_numrows, cur_numcols; /* Check the command line arguments */ if (( argc != 2 ) || ( argv[1][0] != '-' ) || ( strchr ("rcn", argv[1][1]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn on data checking */ status = CPXsetintparam (env, CPXPARAM_Read_DataCheck, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on data checking, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ lp = CPXcreateprob (env, &status, "lpex1"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. For building large problems, consider setting the row, column and nonzero growth parameters before performing this task. */ switch (argv[1][1]) { case 'r': status = populatebyrow (env, lp); break; case 'c': status = populatebycolumn (env, lp); break; case 'n': status = populatebynonzero (env, lp); break; } if ( status ) { fprintf (stderr, "Failed to populate problem.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof(double)); slack = (double *) malloc (cur_numrows * sizeof(double)); dj = (double *) malloc (cur_numcols * sizeof(double)); pi = (double *) malloc (cur_numrows * sizeof(double)); if ( x == NULL || slack == NULL || dj == NULL || pi == NULL ) { status = CPXERR_NO_MEMORY; fprintf (stderr, "Could not allocate memory for solution.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the solution */ free_and_null ((char **) &x); free_and_null ((char **) &slack); free_and_null ((char **) &dj); free_and_null ((char **) &pi); /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int CPLEXLoadObjective(LinEquation* InEquation, bool Max) { int NumCols = CPXgetnumcols(CPLEXenv, CPLEXModel); int Status = 0; if (Max) { CPXchgobjsen (CPLEXenv, CPLEXModel, CPX_MAX); } else { CPXchgobjsen (CPLEXenv, CPLEXModel, CPX_MIN); } int* Indeces = new int[NumCols]; double* Coeffs = new double[NumCols]; for (int i=0; i < NumCols; i++) { Indeces[i] = i; Coeffs[i] = 0; } for (int i=0; i < int(InEquation->Variables.size()); i++) { Coeffs[InEquation->Variables[i]->Index] = InEquation->Coefficient[i]; } Status = CPXchgobj(CPLEXenv, CPLEXModel, NumCols, Indeces, Coeffs); delete [] Indeces; delete [] Coeffs; if (Status) { cout << "Failed to set objective coefficients. " << endl; return FAIL; } if (InEquation->QuadOne.size() > 0) { if (CPXgetprobtype(CPLEXenv, CPLEXModel) == CPXPROB_LP) { Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_QP); } else if (CPXgetprobtype(CPLEXenv, CPLEXModel) == CPXPROB_MILP) { Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_MIQP); } if (Status) { FErrorFile() << "Failed to change problem type." << endl; FlushErrorFile(); return FAIL; } for (int i=0; i < NumCols; i++) { for (int j=0; j < NumCols; j++) { Status = CPXchgqpcoef(CPLEXenv, CPLEXModel, i, j, 0); if (Status) { FErrorFile() << "Failed to change quadratic coefficient." << endl; FlushErrorFile(); return FAIL; } } } for (int i=0; i < int(InEquation->QuadOne.size()); i++) { Status = CPXchgqpcoef(CPLEXenv, CPLEXModel, InEquation->QuadOne[i]->Index, InEquation->QuadTwo[i]->Index, InEquation->QuadCoeff[i]); if (Status) { FErrorFile() << "Failed to change quadratic coefficient." << endl; FlushErrorFile(); return FAIL; } } } return SUCCESS; }
int main (int argc, char *argv[]) { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int numcols; double totinv; int solstat; double objval; double *x = NULL; double rrhs[1]; char rsense[1]; int rmatbeg[1]; int *indices = NULL; double *values = NULL; char *namestore = NULL; char **nameptr = NULL; int surplus, storespace; const char * datadir = argc <= 1 ? "../../../examples/data" : argv[1]; char *prod = NULL; prod = (char *) malloc (strlen (datadir) + 1 + strlen("prod.lp") + 1); sprintf (prod, "%s/prod.lp", datadir); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, "prod.lp"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, prod, NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Tell presolve to do only primal reductions, turn off simplex logging */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Reduce, 1); if ( status ) { fprintf (stderr, "Failed to set CPXPARAM_Preprocessing_Reduce: %d\n", status); goto TERMINATE; } status = CPXsetintparam (env, CPXPARAM_Simplex_Display, 0); if ( status ) { fprintf (stderr, "Failed to set CPXPARAM_Simplex_Display: %d\n", status); goto TERMINATE; } if ( status ) { fprintf (stderr, "Failure to set parameters\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize profit LP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status || solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "Solution failed. Status %d, solstat %d.\n", status, solstat); goto TERMINATE; } printf ("Profit objective value is %g\n", objval); /* Allocate space for column names */ numcols = CPXgetnumcols (env, lp); if ( !numcols ) { fprintf (stderr, "No columns in problem\n"); goto TERMINATE; } CPXgetcolname (env, lp, NULL, NULL, 0, &surplus, 0, numcols-1); storespace = - surplus; namestore = (char *) malloc (storespace * sizeof(char)); nameptr = (char **) malloc (numcols * sizeof(char *)); if ( namestore == NULL || nameptr == NULL ) { fprintf (stderr, "No memory for column names\n"); goto TERMINATE; } status = CPXgetcolname (env, lp, nameptr, namestore, storespace, &surplus, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to get column names\n"); goto TERMINATE; } /* Allocate space for solution */ x = (double *) malloc (numcols * sizeof(double)); if ( x == NULL ) { fprintf (stderr,"No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } totinv = 0; for (j = 0; j < numcols; j++) { if ( !strncmp (nameptr[j], "inv", 3) ) totinv += x[j]; } printf ("Inventory level under profit objective is %g\n", totinv); /* Allocate space for a constraint */ indices = (int *) malloc (numcols * sizeof (int)); values = (double *) malloc (numcols * sizeof (double)); if ( indices == NULL || values == NULL ) { fprintf (stderr, "No memory for constraint\n"); goto TERMINATE; } /* Get profit objective and add it as a constraint */ status = CPXgetobj (env, lp, values, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to get profit objective. Status %d\n", status); goto TERMINATE; } for (j = 0; j < numcols; j++) { indices[j] = j; } rrhs[0] = objval - fabs (objval) * 1e-6; rsense[0] = 'G'; rmatbeg[0] = 0; status = CPXpreaddrows (env, lp, 1, numcols, rrhs, rsense, rmatbeg, indices, values, NULL); if ( status ) { fprintf (stderr, "Failed to add objective as constraint. Status %d\n", status); goto TERMINATE; } /* Set up objective to maximize negative of sum of inventory */ totinv = 0; for (j = 0; j < numcols; j++) { if ( strncmp (nameptr[j], "inv", 3) ) { values[j] = 0.0; } else { values[j] = - 1.0; } } status = CPXprechgobj (env, lp, numcols, indices, values); if ( status ) { fprintf (stderr, "Failed to change to inventory objective. Status %d\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Optimization on inventory level failed. Status %d.\n", status); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status || solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "Solution failed. Status %d, solstat %d.\n", status, solstat); goto TERMINATE; } printf("Solution status %d.\n", solstat); printf ("Inventory level after optimization is %g\n", -objval); status = CPXgetx (env, lp, x, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } printf("Found solution"); /* Write out the solution */ printf ("\n"); for (j = 0; j < numcols; j++) { printf ( "%s: Value = %17.10g\n", nameptr[j], x[j]); } TERMINATE: /* Free the filename */ free_and_null ((char **) &prod); /* Free up the basis and solution */ free_and_null ((char **) &indices); free_and_null ((char **) &values); free_and_null ((char **) &nameptr); free_and_null ((char **) &namestore); free_and_null ((char **) &x); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int j; int cur_numcols; const char * datadir = argc <= 1 ? "../../../examples/data" : argv[1]; char *noswot = NULL; noswot = (char *) malloc (strlen (datadir) + 1 + strlen("noswot.mps") + 1); sprintf (noswot, "%s/noswot.mps", datadir); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } CPXsetintparam (env, CPXPARAM_MIP_Interval, 1000); /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, "noswot"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, noswot, NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Set parameters */ /* Assure linear mappings between the presolved and original models */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Linear, 0); if ( status ) goto TERMINATE; /* Create user cuts for noswot problem */ status = addusercuts (env, lp); if ( status ) goto TERMINATE; /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ("Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the filename */ free_and_null ((char **) &noswot); /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (void) { char probname[16]; /* Problem name is max 16 characters */ /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. The error message will be printed at the end of the program. */ if ( env == NULL ) { fprintf (stderr, "Could not open CPLEX environment.\n"); goto TERMINATE; } /* Turn *off* output to the screen since we'll be producing it via the callback function. This also means we won't see any CPLEX generated errors, but we'll handle that at the end of the program. */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn off screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ strcpy (probname, "example"); lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, we wouldn't see an error message from CPXcreateprob since we turned off the CPXPARAM_ScreenOutput parameter above. The only way to see this message would be to use the CPLEX message handler, but that clutters up the simplicity of this example, which has a point of illustrating the CPLEX callback functionality. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. */ status = populatebycolumn (env, lp); if ( status ) { fprintf (stderr, "Failed to populate problem data.\n"); goto TERMINATE; } status = CPXsetlpcallbackfunc (env, mycallback, NULL); if ( status ) { fprintf (stderr, "Failed to set callback function.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXsetintparam (env, CPXPARAM_LPMethod, CPX_ALG_PRIMAL); if ( status ) { fprintf (stderr, "Failed to set the optimization method, error %d.\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } /* Turn off the callback function. This isn't strictly necessary, but is good practice. Note that the cast in front of NULL is only necessary for some compilers. */ status = CPXsetlpcallbackfunc (env, (int (CPXPUBLIC *)(CPXCENVptr, void *, int, void *)) NULL, NULL); if ( status ) { fprintf (stderr, "Failed to turn off callback function.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex4.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { int frstatus; frstatus = CPXfreeprob (env, &lp); if ( frstatus ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", frstatus); if (( !status ) && frstatus ) status = frstatus; } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { int clstatus; clstatus = CPXcloseCPLEX (&env); if ( clstatus ) { fprintf (stderr, "CPXcloseCPLEX failed, error code %d.\n", clstatus); if (( !status ) && clstatus ) status = clstatus; } } if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; /* Note that since we have turned off the CPLEX screen indicator, we'll need to print the error message ourselves. */ CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } return (status); } /* END main */
static int CPXPUBLIC rounddownheur (CPXCENVptr env, void *cbdata, int wherefrom, void *cbhandle, double *objval_p, double *x, int *checkfeas_p, int *useraction_p) { int status = 0; int j, cols; double roundobjval; int *feas = NULL; CPXCLPptr lp; double *objcoefs = NULL; *useraction_p = CPX_CALLBACK_DEFAULT; /* Heuristic motivated by knapsack constrained problems. Rounding down all fractional values will give an integer solution that is feasible, since all constraints are <= with positive coefficients */ status = CPXgetcallbacklp (env, cbdata, wherefrom, &lp); if ( status ) { fprintf (stdout, "Can't get lp pointer."); goto TERMINATE; } cols = CPXgetnumcols (env, lp); if ( cols <= 0 ) { fprintf (stdout, "numcols = %d.", cols); status = CPXERR_CALLBACK; goto TERMINATE; } objcoefs = (double *) malloc (cols * sizeof (double)); feas = (int *) malloc (cols * sizeof (int)); if ( objcoefs == NULL || feas == NULL ) { fprintf (stdout, "Out of memory."); status = CPXERR_CALLBACK; goto TERMINATE; } status = CPXgetobj (env, lp, objcoefs, 0, cols-1); if ( status ) { fprintf (stdout, "Can't get objective."); goto TERMINATE; } status = CPXgetcallbacknodeintfeas (env, cbdata, wherefrom, feas, 0, cols-1); if ( status ) { fprintf (stdout, "Can't get variable feasible status for node."); goto TERMINATE; } roundobjval = *objval_p; for (j = 0; j < cols; j++) { /* Set the fractional variable to zero and update the objective value */ if ( feas[j] == CPX_INTEGER_INFEASIBLE ) { roundobjval -= x[j] * objcoefs[j]; x[j] = 0.0; } } *objval_p = roundobjval; /* Have CPLEX check the solution for integer feasibility */ *checkfeas_p = 1; /* Tell CPLEX that a solution is being returned */ *useraction_p = CPX_CALLBACK_SET; TERMINATE: free_and_null ((char **) &objcoefs); free_and_null ((char **) &feas); return (status); } /* END rounddown */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, maximum bound violation, variable values, and basis. */ int solnstat, solnmethod, solntype; double objval, maxviol; double *x = NULL; int *cstat = NULL; int *rstat = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int cur_numrows, cur_numcols; char **cur_colname = NULL; char *cur_colnamestore = NULL; int cur_colnamespace; int surplus; int method; char *basismsg; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("podhbnsc", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ switch (argv[2][0]) { case 'o': method = CPX_ALG_AUTOMATIC; break; case 'p': method = CPX_ALG_PRIMAL; break; case 'd': method = CPX_ALG_DUAL; break; case 'n': method = CPX_ALG_NET; break; case 'h': method = CPX_ALG_BARRIER; break; case 'b': method = CPX_ALG_BARRIER; status = CPXsetintparam (env, CPXPARAM_Barrier_Crossover, CPX_ALG_NONE); if ( status ) { fprintf (stderr, "Failed to set the crossover method, error %d.\n", status); goto TERMINATE; } break; case 's': method = CPX_ALG_SIFTING; break; case 'c': method = CPX_ALG_CONCURRENT; break; default: method = CPX_ALG_NONE; break; } status = CPXsetintparam (env, CPXPARAM_LPMethod, method); if ( status ) { fprintf (stderr, "Failed to set the optimization method, error %d.\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } solnstat = CPXgetstat (env, lp); if ( solnstat == CPX_STAT_UNBOUNDED ) { printf ("Model is unbounded\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INFEASIBLE ) { printf ("Model is infeasible\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INForUNBD ) { printf ("Model is infeasible or unbounded\n"); goto TERMINATE; } status = CPXsolninfo (env, lp, &solnmethod, &solntype, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to obtain solution info.\n"); goto TERMINATE; } printf ("Solution status %d, solution method %d\n", solnstat, solnmethod); if ( solntype == CPX_NO_SOLN ) { fprintf (stderr, "Solution not available.\n"); goto TERMINATE; } status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g.\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numcols = CPXgetnumcols (env, lp); cur_numrows = CPXgetnumrows (env, lp); /* Retrieve basis, if one is available */ if ( solntype == CPX_BASIC_SOLN ) { cstat = (int *) malloc (cur_numcols*sizeof(int)); rstat = (int *) malloc (cur_numrows*sizeof(int)); if ( cstat == NULL || rstat == NULL ) { fprintf (stderr, "No memory for basis statuses.\n"); goto TERMINATE; } status = CPXgetbase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to get basis; error %d.\n", status); goto TERMINATE; } } else { printf ("No basis available\n"); } /* Retrieve solution vector */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } /* Now get the column names for the problem. First we determine how much space is used to hold the names, and then do the allocation. Then we call CPXgetcolname() to get the actual names. */ status = CPXgetcolname (env, lp, NULL, NULL, 0, &surplus, 0, cur_numcols-1); if (( status != CPXERR_NEGATIVE_SURPLUS ) && ( status != 0 ) ) { fprintf (stderr, "Could not determine amount of space for column names.\n"); goto TERMINATE; } cur_colnamespace = - surplus; if ( cur_colnamespace > 0 ) { cur_colname = (char **) malloc (sizeof(char *)*cur_numcols); cur_colnamestore = (char *) malloc (cur_colnamespace); if ( cur_colname == NULL || cur_colnamestore == NULL ) { fprintf (stderr, "Failed to get memory for column names.\n"); status = -1; goto TERMINATE; } status = CPXgetcolname (env, lp, cur_colname, cur_colnamestore, cur_colnamespace, &surplus, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "CPXgetcolname failed.\n"); goto TERMINATE; } } else { printf ("No names associated with problem. Using Fake names.\n"); } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( cur_colnamespace > 0 ) { printf ("%-16s: ", cur_colname[j]); } else { printf ("Fake%-6.6d : ", j);; } printf ("%17.10g", x[j]); if ( cstat != NULL ) { switch (cstat[j]) { case CPX_AT_LOWER: basismsg = "Nonbasic at lower bound"; break; case CPX_BASIC: basismsg = "Basic"; break; case CPX_AT_UPPER: basismsg = "Nonbasic at upper bound"; break; case CPX_FREE_SUPER: basismsg = "Superbasic, or free variable at zero"; break; default: basismsg = "Bad basis status"; break; } printf (" %s",basismsg); } printf ("\n"); } /* Display the maximum bound violation. */ status = CPXgetdblquality (env, lp, &maxviol, CPX_MAX_PRIMAL_INFEAS); if ( status ) { fprintf (stderr, "Failed to obtain bound violation.\n"); goto TERMINATE; } printf ("Maximum bound violation = %17.10g\n", maxviol); TERMINATE: /* Free up the basis and solution */ free_and_null ((char **) &cstat); free_and_null ((char **) &rstat); free_and_null ((char **) &x); free_and_null ((char **) &cur_colname); free_and_null ((char **) &cur_colnamestore); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
static int CPXPUBLIC solvecallback (CPXCENVptr env, void *cbdata, int wherefrom, void *userinfo, int *useraction_p) { int status = 0; int lpstatus = 0; CPXLPptr nodelp = NULL; double *prex = NULL; MYCBptr mycbinfo = (MYCBptr) userinfo; CPXLPptr mip = mycbinfo->mip; double *relx = mycbinfo->relx; int cols; int prestat; *useraction_p = CPX_CALLBACK_DEFAULT; /* Only use callback for solving the root relaxation (node 0) */ if ( mycbinfo->count > 0 ) { goto TERMINATE; } mycbinfo->count++; /* Extract the LP to be solved */ status = CPXgetcallbacknodelp (env, cbdata, wherefrom, &nodelp); if ( status ) goto TERMINATE; cols = CPXgetnumcols (env, nodelp); prex = (double *) malloc (cols * sizeof (double)); if ( prex == NULL ) { status = CPXERR_NO_MEMORY; goto TERMINATE; } /* Use MIP presolve to crush the original solution. Note that MIP presolve can only crush primal solutions */ status = CPXgetprestat (env, mip, &prestat, NULL, NULL, NULL, NULL); if ( status ) goto TERMINATE; /* If a presolved model exists, then relx is crushed down to prex, the corresponding solution for the presolved model; otherwise, prex is just a copy of relx */ if ( prestat ) { status = CPXcrushx (env, mip, relx, prex); if ( status ) goto TERMINATE; } else { memcpy (prex, relx, cols * sizeof (double)); } /* Feed the crushed solution into 'nodelp' */ status = CPXcopystart (env, nodelp, NULL, NULL, prex, NULL, NULL, NULL); /* Use primal to reoptimize, since we only have a primal solution */ status = CPXprimopt (env, nodelp); if ( status ) goto TERMINATE; lpstatus = CPXgetstat (env, nodelp); if ( lpstatus == CPX_STAT_OPTIMAL || lpstatus == CPX_STAT_OPTIMAL_INFEAS || lpstatus == CPX_STAT_INFEASIBLE ) { *useraction_p = CPX_CALLBACK_SET; } TERMINATE: free_and_null ((char **) &prex); return (status); } /* END solvecallback */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int i, j; double *numc=NULL; int display=0, m=0, n=0; long *lpenv=NULL, *p_lp=NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; if (nrhs != 2 || nrhs < 1) { mexErrMsgTxt("Usage: slack " "= lp_getnumcnstr(lpenv, p_lp)"); return; } if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || mxGetN(prhs[1])!=1 ) { mexErrMsgTxt("2nd argument (p_lp) must be " "a column vector."); return; } if (1 != mxGetM(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2)."); return; } p_lp = (long*) mxGetPr(prhs[1]); } if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) { if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxGetN(prhs[0])!=1 ) { mexErrMsgTxt("1st argument (lpenv) must be " "a column vector."); return; } if (1 != mxGetM(prhs[0])) { mexErrMsgTxt("Dimension error (arg 1)."); return; } lpenv = (long*) mxGetPr(prhs[0]); } /* Initialize the CPLEX environment */ env = (CPXENVptr) lpenv[0] ; lp=(CPXLPptr)p_lp[0] ; /* Turn on output to the screen */ if (display>0) status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); else status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF); if ( status ) { fprintf (STD_OUT, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } if (display>2) status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, 2); else status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, display); if ( status ) { fprintf (STD_OUT,"Failed to turn up simplex display level.\n"); goto TERMINATE; } n=CPXgetnumcols(env, lp); m=CPXgetnumrows(env, lp); plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); numc = mxGetPr(plhs[0]); *numc = m; TERMINATE: return ; }
int main (int argc, char *argv[]) { int uselogcallback = 0; LOGINFO myloginfo; int usetimelimcallback = 0; TIMELIMINFO mytimeliminfo; int useterminate = 0; volatile int terminator; CPXENVptr env = NULL; CPXLPptr lp = NULL; int solstat; int status = 0; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("lta", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } switch (argv[2][0]) { case 'l': uselogcallback = 1; break; case 't': usetimelimcallback = 1; break; case 'a': useterminate = 1; break; default: break; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( usetimelimcallback ) { double t; status = CPXgettime (env, &t); if ( status ) { fprintf (stderr, "Failed to initialize timer.\n"); goto TERMINATE; } mytimeliminfo.acceptablegap = 10.0; mytimeliminfo.aborted = 0; mytimeliminfo.timestart = t; mytimeliminfo.timelim = 1.0; status = CPXsetinfocallbackfunc (env, timelimcallback, &mytimeliminfo); if ( status ) { fprintf (stderr, "Failed to set time limit callback function.\n"); goto TERMINATE; } } else if ( uselogcallback ) { /* Set overall node limit in case callback conditions are not met */ status = CPXsetintparam (env, CPXPARAM_MIP_Limits_Nodes, 5000); if ( status ) goto TERMINATE; status = CPXgettime (env, &myloginfo.timestart); if ( status ) { fprintf (stderr, "Failed to query time.\n"); goto TERMINATE; } status = CPXgetdettime (env, &myloginfo.dettimestart); if ( status ) { fprintf (stderr, "Failed to query deterministic time.\n"); goto TERMINATE; } myloginfo.numcols = CPXgetnumcols (env, lp); myloginfo.lastincumbent = CPXgetobjsen (env, lp) * 1e+35; myloginfo.lastlog = -10000; status = CPXsetinfocallbackfunc (env, logcallback, &myloginfo); if ( status ) { fprintf (stderr, "Failed to set logging callback function.\n"); goto TERMINATE; } /* Turn off CPLEX logging */ status = CPXsetintparam (env, CPXPARAM_MIP_Display, 0); if ( status ) goto TERMINATE; } else if ( useterminate) { status = CPXsetterminate (env, &terminator); if ( status ) { fprintf (stderr, "Failed to set terminator.\n"); goto TERMINATE; } /* Typically, you would pass the terminator variable to another thread or pass it to an interrupt handler, and monitor for some event to occur. When it does, set terminator to a non-zero value. To illustrate its use without creating a thread or an interrupt handler, terminate immediately by setting terminator before the solve. */ terminator = 1; } /* Optimize the problem and obtain solution. */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { int xstatus = CPXfreeprob (env, &lp); if ( xstatus ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", xstatus); status = xstatus; } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { int xstatus = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); status = xstatus; } } return (status); } /* END main */
int main (void) { char probname[16]; /* Problem name is max 16 characters */ int cstat[NUMCOLS]; int rstat[NUMROWS]; /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ strcpy (probname, "example"); lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. */ status = populatebycolumn (env, lp); if ( status ) { fprintf (stderr, "Failed to populate problem data.\n"); goto TERMINATE; } /* We assume we know the optimal basis. Variables 1 and 2 are basic, while variable 0 is at its upper bound */ cstat[0] = CPX_AT_UPPER; cstat[1] = CPX_BASIC; cstat[2] = CPX_BASIC; /* The row statuses are all nonbasic for this problem */ rstat[0] = CPX_AT_LOWER; rstat[1] = CPX_AT_LOWER; /* Now copy the basis */ status = CPXcopybase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to copy the basis.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n", objval); printf ("Iteration count = %d\n\n", CPXgetitcnt (env, lp)); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex6.sav", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int j; int cur_numcols; int wantorig = 1; int nameind = 1; /* Check the command line arguments */ if ( argc != 2 ) { if ( argc != 3 || argv[1][0] != '-' || argv[1][1] != 'r' ) { usage (argv[0]); goto TERMINATE; } wantorig = 0; nameind = 2; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[nameind]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[nameind], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( CPXgetnumcols (env, lp) != CPXgetnumbin (env, lp) ) { fprintf (stderr, "Problem contains non-binary variables, exiting\n"); goto TERMINATE; } /* Set parameters */ if ( wantorig ) { /* Assure linear mappings between the presolved and original models */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Linear, 0); if ( status ) goto TERMINATE; /* Let MIP callbacks work on the original model */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_CallbackReducedLP, CPX_OFF); if ( status ) goto TERMINATE; } status = CPXsetdblparam (env, CPXPARAM_MIP_Tolerances_MIPGap, (double) 1e-6); if ( status ) goto TERMINATE; /* Turn on traditional search for use with control callbacks */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_Search, CPX_MIPSEARCH_TRADITIONAL); if ( status ) goto TERMINATE; /* Set up to use MIP callback */ status = CPXsetheuristiccallbackfunc (env, rounddownheur, NULL); if ( status ) goto TERMINATE; /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, and variable values. */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int j; int cur_numcols; /* Check the command line arguments */ if ( argc != 2 ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numcols stores the current number of columns. */ cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } TERMINATE: /* Free up the solution */ free_and_null ((char **) &x); /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, maximum bound violation, variable values, and basis. */ int solnstat, solnmethod, solntype; double objval, maxviol; double *x = NULL; int *cstat = NULL; int *rstat = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int cur_numrows, cur_numcols; char *basismsg; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("cfg", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( CPXgetprobtype (env, lp) != CPXPROB_QP ) { fprintf (stderr, "Input file is not a QP. Exiting.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ switch (argv[2][0]) { case 'c': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_OPTIMALCONVEX); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { if ( status == CPXERR_Q_NOT_POS_DEF ) printf ("Problem is not convex. Use argument f to get local optimum " "or g to get global optimum.\n"); else fprintf (stderr, "Failed to optimize QP.\n"); goto TERMINATE; } break; case 'f': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_FIRSTORDER); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize QP.\n"); goto TERMINATE; } break; case 'g': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_OPTIMALGLOBAL); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize noncvonex QP.\n"); goto TERMINATE; } break; default: break; } solnstat = CPXgetstat (env, lp); if ( solnstat == CPXMIP_UNBOUNDED || solnstat == CPX_STAT_UNBOUNDED ) { printf ("Model is unbounded\n"); goto TERMINATE; } else if ( solnstat == CPXMIP_INFEASIBLE || solnstat == CPX_STAT_INFEASIBLE ) { printf ("Model is infeasible\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INForUNBD ) { printf ("Model is infeasible or unbounded\n"); goto TERMINATE; } status = CPXsolninfo (env, lp, &solnmethod, &solntype, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to obtain solution info.\n"); goto TERMINATE; } printf ("Solution status %d, solution method %d\n", solnstat, solnmethod); if ( solntype == CPX_NO_SOLN ) { fprintf (stderr, "Solution not available.\n"); goto TERMINATE; } status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g.\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numcols = CPXgetnumcols (env, lp); cur_numrows = CPXgetnumrows (env, lp); /* Retrieve basis, if one is available */ if ( solntype == CPX_BASIC_SOLN ) { cstat = (int *) malloc (cur_numcols*sizeof(int)); rstat = (int *) malloc (cur_numrows*sizeof(int)); if ( cstat == NULL || rstat == NULL ) { fprintf (stderr, "No memory for basis statuses.\n"); goto TERMINATE; } status = CPXgetbase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to get basis; error %d.\n", status); goto TERMINATE; } } else { printf ("No basis available\n"); } /* Retrieve solution vector */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { printf ( "Column %d: Value = %17.10g", j, x[j]); if ( cstat != NULL ) { switch (cstat[j]) { case CPX_AT_LOWER: basismsg = "Nonbasic at lower bound"; break; case CPX_BASIC: basismsg = "Basic"; break; case CPX_AT_UPPER: basismsg = "Nonbasic at upper bound"; break; case CPX_FREE_SUPER: basismsg = "Superbasic, or free variable at zero"; break; default: basismsg = "Bad basis status"; break; } printf (" %s",basismsg); } printf ("\n"); } /* Display the maximum bound violation. */ status = CPXgetdblquality (env, lp, &maxviol, CPX_MAX_PRIMAL_INFEAS); if ( status ) { fprintf (stderr, "Failed to obtain bound violation.\n"); goto TERMINATE; } printf ("Maximum bound violation = %17.10g\n", maxviol); TERMINATE: /* Free up the basis and solution */ free_and_null ((char **) &cstat); free_and_null ((char **) &rstat); free_and_null ((char **) &x); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
extern int solve_allocation(int nodeSize, int windowSize, int timeout, sched_nodeinfo_t *node_array, solver_job_list_t *job_array) { solver_job_list_t *solver_job_ptr; int solstat; int n = windowSize, m = nodeSize; double objval; double *x = NULL; double *pi = NULL; double *slack = NULL; double *dj = NULL; double *obj = NULL; int NUMCOLS = n * (2 * m + 2); CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int i, j, k; int cur_numrows, cur_numcols; char envstr[256] = "ILOG_LICENSE_FILE=/home/seren/ILOG/CPLEX_Studio_AcademicResearch122/licenses/access.ilm"; if ( envstr != NULL ) { CPXputenv (envstr); } env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); if ( status ) { goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_DATACHECK, CPX_ON); if ( status ) { goto TERMINATE; } lp = CPXcreateprob (env, &status, "lpex1"); if ( lp == NULL ) { goto TERMINATE; } obj = (double*)malloc(NUMCOLS * sizeof(double)); status = CPXsetdblparam(env,CPX_PARAM_TILIM,5); status = populatebynonzero (env, lp, nodeSize, windowSize, timeout, node_array, job_array); if ( status ) { fprintf (stderr, "Failed to populate problem."); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP."); goto TERMINATE; } cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof(double)); slack = (double *) malloc (cur_numrows * sizeof(double)); dj = (double *) malloc (cur_numcols * sizeof(double)); pi = (double *) malloc (cur_numrows * sizeof(double)); if ( x == NULL || slack == NULL || dj == NULL || pi == NULL ) { status = CPXERR_NO_MEMORY; goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { goto TERMINATE; } /*debug3("\nSolution status = %d\n", solstat);*/ printf("Solution value = %f\n\n", objval); /* for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } */ /*debug3("sending solution results to slurm");*/ /* for (j = 0; j < windowSize; j++) { if (x[j] > 0) { solver_job_ptr = &job_array[j]; solver_job_ptr->node_bitmap = (bitstr_t *) bit_alloc (node_record_count); solver_job_ptr->job_ptr->details->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); solver_job_ptr->onnodes = (int *) xmalloc (sizeof(int)*node_record_count); solver_job_ptr->job_ptr->details->req_node_layout = (int *)xmalloc(sizeof(int) * node_record_count); solver_job_ptr->job_ptr->details->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); for (i = 0; i < nodeSize; i++) { k = (1 + i) * windowSize + j; if (x[k] > 0) { bit_set (solver_job_ptr->node_bitmap, (bitoff_t) (i)); bit_set (solver_job_ptr->job_ptr->details->req_node_bitmap, (bitoff_t) (i)); node_array[i].rem_cpus -= x[k]; node_array[i].rem_gpus -= solver_job_ptr->gpu; solver_job_ptr->onnodes[i] = x[k]; solver_job_ptr->job_ptr->details->req_node_layout[i] = solver_job_ptr->onnodes[i]; solver_job_ptr->alloc_total += x[k]; } } } else job_array[j].alloc_total = 0; } */ /* status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk."); goto TERMINATE; } */ TERMINATE: free_and_null ((char **) &x); free_and_null ((char **) &slack); free_and_null ((char **) &dj); free_and_null ((char **) &pi); if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.", status); } } if ( env != NULL ) { status = CPXcloseCPLEX (&env); if ( status ) { char errmsg[1024]; fprintf (stderr, "Could not close CPLEX environment."); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); }
//******************************************************************* long CSolver::GetNumColumns(){ if (m_lp!= NULL) return CPXgetnumcols(m_env,m_lp); else return m_nObjItems; }
OptSolutionData* CPLEXRunSolver(int ProbType) { OptSolutionData* NewSolution = NULL; int Status = 0; if (ProbType == LP) { Status = CPXsetintparam (CPLEXenv, CPX_PARAM_LPMETHOD, CPX_ALG_AUTOMATIC); if (Status) { FErrorFile() << "Failed to set the optimization method." << endl; FlushErrorFile(); return NULL; } Status = CPXsetintparam (CPLEXenv, CPX_PARAM_SIMDISPLAY, 0); if (Status) { FErrorFile() << "Failed to set the optimization method." << endl; FlushErrorFile(); return NULL; } Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_LP); Status = CPXlpopt(CPLEXenv, CPLEXModel); } else if(ProbType == MILP || ProbType == MIQP) { //Setting the bound tightening on high Status = CPXsetintparam (CPLEXenv, CPX_PARAM_BNDSTRENIND, 1); if (Status) { FErrorFile() << "Failed to set the optimization method." << endl; FlushErrorFile(); return NULL; } //Setting tolerance to 1e-9 instead of 1e-6 double tolerance = atof(GetParameter("Solver tolerance").data()); Status = CPXsetdblparam(CPLEXenv,CPX_PARAM_EPRHS, tolerance); if (Status) { FErrorFile() << "Failed to set the optimization method." << endl; FlushErrorFile(); return NULL; } Status = CPXsetdblparam(CPLEXenv,CPX_PARAM_EPINT, tolerance); if (Status) { FErrorFile() << "Failed to set the optimization method." << endl; FlushErrorFile(); return NULL; } //Deactivates all messages from MIP solver Status = CPXchgprobtype(CPLEXenv, CPLEXModel, CPXPROB_MILP); Status = CPXmipopt (CPLEXenv, CPLEXModel); } else if(ProbType == QP) { Status = CPXqpopt (CPLEXenv, CPLEXModel); } if (Status ) { cout << "Failed to optimize LP." << endl; return NULL; } int Temp = CPXgetstat (CPLEXenv, CPLEXModel); NewSolution = new OptSolutionData; if (Temp == CPX_STAT_UNBOUNDED) { cout << "Model is unbounded" << endl; FErrorFile() << "Model is unbounded" << endl; FlushErrorFile(); NewSolution->Status = UNBOUNDED; return NewSolution; } else if (Temp == CPX_STAT_INFEASIBLE) { cout << "Model is infeasible" << endl; FErrorFile() << "Model is infeasible" << endl; FlushErrorFile(); NewSolution->Status = INFEASIBLE; return NewSolution; } else if (Temp == CPX_STAT_INForUNBD ) { cout << "Model is infeasible or unbounded" << endl; FErrorFile() << "Model is infeasible or unbounded" << endl; FlushErrorFile(); NewSolution->Status = INFEASIBLE; return NewSolution; } else { NewSolution->Status = SUCCESS; } int NumberColumns = CPXgetnumcols (CPLEXenv, CPLEXModel); int NumberRows = CPXgetnumrows (CPLEXenv, CPLEXModel); NewSolution->NumVariables = NumberColumns; NewSolution->SolutionData.resize(NumberColumns); double* x = new double[NumberColumns]; if (ProbType == MILP || ProbType == MIQP) { Status = CPXgetmipobjval (CPLEXenv, CPLEXModel, &(NewSolution->Objective)); Status = CPXgetmipx (CPLEXenv, CPLEXModel, x, 0, NumberColumns-1); } else { Status = CPXsolution(CPLEXenv,CPLEXModel,NULL,&(NewSolution->Objective),x,NULL,NULL,NULL); } if ( Status ) { cout << "Failed to obtain objective value." << endl; delete [] x; NewSolution->Status = INFEASIBLE; return NewSolution; } cout << "Objective value: " << NewSolution->Objective << endl; /* string* StrNames = new string[NumberColumns]; char** Names = new char*[NumberColumns]; char* NameStore = new char[7*NumberColumns]; int Surplus = 0; Status = CPXgetcolname(CPLEXenv, CPLEXModel, Names, NameStore, 7*NumberColumns, &Surplus, 0, NumberColumns-1); if (Status) { FErrorFile() << "Failed to get column names." << endl; FlushErrorFile(); delete [] StrNames; delete [] Names; delete [] NameStore; delete [] x; delete NewSolution; return NULL; } */ for (int i=0; i < NumberColumns; i++) { //StrNames[i].assign(Names[i]); //StrNames[i] = StrNames[i].substr(1, StrNames[i].length()-1); //NewSolution->SolutionData[atoi(StrNames[i].data())-1] = x[i]; NewSolution->SolutionData[i] = x[i]; } /* delete [] StrNames; delete [] Names; delete [] NameStore; */ delete [] x; return NewSolution; }
int main (void) { /* Declare pointers for the variables and arrays that will contain the data which define the LP problem. The setproblemdata() routine allocates space for the problem data. */ char *probname = NULL; int numcols; int numrows; int objsen; double *obj = NULL; double *rhs = NULL; char *sense = NULL; int *matbeg = NULL; int *matcnt = NULL; int *matind = NULL; double *matval = NULL; double *lb = NULL; double *ub = NULL; /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Allocate memory and fill in the data for the problem. */ status = setproblemdata (&probname, &numcols, &numrows, &objsen, &obj, &rhs, &sense, &matbeg, &matcnt, &matind, &matval, &lb, &ub); if ( status ) { fprintf (stderr, "Failed to build problem data arrays.\n"); goto TERMINATE; } /* Create the problem. */ lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now copy the problem data into the lp */ status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, rhs, sense, matbeg, matcnt, matind, matval, lb, ub, NULL); if ( status ) { fprintf (stderr, "Failed to copy problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using what was passed to CPXcopylp. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } /* Free up the problem data arrays, if necessary. */ free_and_null ((char **) &probname); free_and_null ((char **) &obj); free_and_null ((char **) &rhs); free_and_null ((char **) &sense); free_and_null ((char **) &matbeg); free_and_null ((char **) &matcnt); free_and_null ((char **) &matind); free_and_null ((char **) &matval); free_and_null ((char **) &lb); free_and_null ((char **) &ub); return (status); } /* END main */
int CPLEXLoadVariables(MFAVariable* InVariable, bool RelaxIntegerVariables,bool UseTightBounds) { int Status = 0; //First I check the number of columns. If it's larger than the index, then this variable already exists and is only being changed int NumberColumns = CPXgetnumcols (CPLEXenv, CPLEXModel); if (NumberColumns <= InVariable->Index) { string StrName = GetMFAVariableName(InVariable); double* LB = new double; LB[0] = InVariable->LowerBound; double* UB = new double; UB[0] = InVariable->UpperBound; if (UseTightBounds) { LB[0] = InVariable->Min; UB[0] = InVariable->Max; } double* Obj = new double; Obj[0] = 0; char* Temp = new char; char** Name = new char*; Name[0] = new char[StrName.length()+1]; strcpy(Name[0],StrName.data()); if (InVariable->Binary && !RelaxIntegerVariables) { Temp[0] = CPX_BINARY; Status = CPXnewcols (CPLEXenv, CPLEXModel, 1, Obj, LB, UB, Temp, Name); } else if (InVariable->Integer && !RelaxIntegerVariables) { Temp[0] = CPX_INTEGER; Status = CPXnewcols (CPLEXenv, CPLEXModel, 1, Obj, LB, UB, Temp, Name); } else { Temp[0] = CPX_CONTINUOUS; Status = CPXnewcols (CPLEXenv, CPLEXModel, 1, Obj, LB, UB, Temp, Name); } delete LB; delete UB; delete Obj; delete Temp; delete [] Name[0]; delete Name; if (Status ) { FErrorFile() << "Could not add variable " << InVariable->Index << endl; FlushErrorFile(); return FAIL; } } else { double* Bounds = new double[2]; Bounds[0] = InVariable->LowerBound; Bounds[1] = InVariable->UpperBound; int* Indices = new int[2]; Indices[0] = InVariable->Index; Indices[1] = InVariable->Index; Status = CPXchgbds (CPLEXenv, CPLEXModel, 2, Indices, "LU", Bounds); delete [] Bounds; delete [] Indices; if (Status) { FErrorFile() << "Could not change bounds on variable " << InVariable->Index << endl; FlushErrorFile(); return FAIL; } } return SUCCESS; }