int CSolver:: Optimize(int Algorthim) { m_cbData.bMip = false; CPXsetlpcallbackfunc(m_env, lpcallback, &m_cbData); switch(Algorthim) { case SIMPLEX: m_status = CPXprimopt(m_env,m_lp); break; case DUAL_SIMPLEX: m_status = CPXdualopt(m_env,m_lp); break; case BARRIER: m_status = CPXbaropt(m_env,m_lp); break; default: Message("Undefined Algorthim specified in call to Optimize -- will use simplex!"); m_status = CPXoptimize(m_env,m_lp); }; char buff[100]; if (m_status) { CPXgeterrorstring(m_env, m_status, m_error ); sprintf(buff,"Error: %d",m_status); Message( buff ); Message( m_error ); return -1; } CPXsetlpcallbackfunc(m_env,NULL, NULL); CreateSolArrays(); // get solution and place into arrays m_status = CPXsolution(m_env, m_lp, &m_lpstat, &m_obj, m_x, m_pi, m_slack, m_dj); if (m_status) { CPXgeterrorstring(m_env, m_status, m_error ); Message("Getting solution IP_FAILED."); Message( m_error ); return -1; } // save the basis to arrays m_status = CPXgetbase(m_env, m_lp, m_pCstat, m_pRstat); if ( m_status ) { CPXgeterrorstring(m_env, m_status, m_error); Message("Getting basis failed!"); Message(m_error); return -1; } return m_status; }
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 */
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* MATLAB memory structures */ const mxArray *c,*A,*b,*l,*u,*le,*ge,*maxIterPtr; /* Return arguments */ double *matlpstat,*objval,*x,*pi,*cstat,*itcnt; /* Other declarations */ char *sense,errorMsg[255]; int rows,cols,maxIter,*matbeg,*matcnt,*matind; double *c_ptr,*b_ptr,*matval,*l_ptr,*u_ptr,*slack,*dj; int matrixSize,status,i,j,le_size,ge_size,m,n; double *le_ptr = NULL,*ge_ptr = NULL; int *istat,lpstat; //CPXENVptr env; //CPXLPptr lp = NULL; /* Assign pointers to MATLAB memory stuctures */ c = prhs[C_IN]; A = prhs[A_IN]; b = prhs[B_IN]; l = prhs[L_IN]; u = prhs[U_IN]; c_ptr = mxGetPr(c); b_ptr = mxGetPr(b); l_ptr = mxGetPr(l); u_ptr = mxGetPr(u); rows = mxGetM(b); cols = mxGetM(c); /* Build the matrix of coefficients, taking sparsity into account. */ if (mxIsSparse(A)){ /* Sparse */ matbeg = mxGetJc(A); /* beginnings of each column */ matcnt = (int*)mxCalloc(cols,sizeof(int)); /* # of entries in each col */ for (i = 0; i < cols; i++) matcnt[i] = matbeg[i+1] - matbeg[i]; matind = mxGetIr(A); /* row locations */ matval = mxGetPr(A); /* actual coefficients */ } else { /* Dense */ m = mxGetM(A); n = mxGetN(A); matbeg = (int*)mxCalloc(n,sizeof(int)); matcnt = (int*)mxCalloc(n,sizeof(int)); matind = (int*)mxCalloc(m*n,sizeof(int)); matval = mxGetPr(A); for (j = 0; j < n; j++) { matbeg[j] = j*m; for (i = 0; i < m; i++) matind[j*m + i] = i; matcnt[j] = m; } } /* Initialize all constraints to be equality constraints (default). */ sense = (char*)mxCalloc(rows,sizeof(char)); for(i = 0; i < rows; i++) sense[i] = 'E'; /* If "<=" constraints given, set them up. */ if(nrhs > MANDATORY_ARGS){ le = prhs[LE_IN]; le_ptr = mxGetPr(le); le_size = mxGetM(le); for(i = 0; i < le_size; i++) sense[(int)(le_ptr[i]-1)] = 'L'; } /* If ">=" constraints given, set them up. */ if(nrhs > MANDATORY_ARGS + 1){ ge = prhs[GE_IN]; ge_ptr = mxGetPr(ge); ge_size = mxGetM(ge); for(i = 0; i < ge_size; i++) sense[(int)(ge_ptr[i]-1)] = 'G'; } /* Set up maximum number of iterations */ if (nrhs > MANDATORY_ARGS + 2) { maxIterPtr = prhs[MI_IN]; maxIter = (int)mxGetScalar(maxIterPtr); } else maxIter = MAX_ITER_DEFAULT; /* Output to MATLAB */ plhs[OBJ_OUT] = mxCreateDoubleMatrix(1,1,mxREAL); plhs[X_OUT] = mxCreateDoubleMatrix(cols,1,mxREAL); plhs[PI_OUT] = mxCreateDoubleMatrix(rows,1,mxREAL); plhs[STAT_OUT] = mxCreateDoubleMatrix(1,1,mxREAL); plhs[CSTAT_OUT] = mxCreateDoubleMatrix(cols,1,mxREAL); plhs[ITER_OUT] = mxCreateDoubleMatrix(1,1,mxREAL); objval = mxGetPr(plhs[OBJ_OUT]); x = mxGetPr(plhs[X_OUT]); pi = mxGetPr(plhs[PI_OUT]); matlpstat = mxGetPr(plhs[STAT_OUT]); cstat = mxGetPr(plhs[CSTAT_OUT]); istat = (int*)mxCalloc(cols,sizeof(int)); itcnt = mxGetPr(plhs[ITER_OUT]); if (!initialized) { mexPrintf("MEX-file: lp_cplex_mex opening cplex environment\n"); /* Open CPLEX environment */ env = CPXopenCPLEXdevelop(&status); if (!env) { printf(CPXgeterrorstring(env,status,errorMsg)); mexErrMsgTxt("\nCould not open CPLEX environment."); } /* Create CPLEX problem space */ lp = CPXcreateprob(env, &status, "matlab"); if (!lp) { printf(CPXgeterrorstring(env,status,errorMsg)); CPXcloseCPLEX(&env); mexErrMsgTxt("\nCould not create CPLEX problem."); } mexAtExit(cleanup); initialized = 1; } /* Copy LP into CPLEX environment */ status = CPXcopylp(env, lp, cols, rows, MINIMIZE, c_ptr, b_ptr, sense, matbeg, matcnt, matind, matval, l_ptr, u_ptr, NULL); if (status) { printf(CPXgeterrorstring(env,status,errorMsg)); //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); mexErrMsgTxt("\nCould not copy CPLEX problem."); } /* Set iteration limit. */ status = CPXsetintparam(env, CPX_PARAM_ITLIM, maxIter); if (status) { printf(CPXgeterrorstring(env,status,errorMsg)); //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); mexErrMsgTxt("\nCould not set number of iterations."); } /* Perform optimization */ status = CPXprimopt(env,lp); if (status) { printf(CPXgeterrorstring(env,status,errorMsg)); //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); mexErrMsgTxt("\nOptimization error."); } /* Obtain solution */ status = CPXsolution(env, lp, &lpstat, objval, x, pi, NULL, NULL); *matlpstat = lpstat; if (status) { printf(CPXgeterrorstring(env,status,errorMsg)); //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); mexErrMsgTxt("\nFailure when retrieving solution."); } /* Get status of columns */ status = CPXgetbase(env, lp, istat, NULL); if (status) { printf(CPXgeterrorstring(env,status,errorMsg)); //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); mexErrMsgTxt("\nUnable to get basis status."); } /* Copy int column values to double column values */ for (i=0; i < cols; i++) cstat[i] = istat[i]; /* Get iteration count */ *itcnt = (double)CPXgetitcnt(env,lp); /* Clean up problem */ //CPXfreeprob(env,&lp); //CPXcloseCPLEX(&env); }
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 */
int cg_solver(int m, MyRow* rows) { CPXENVptr env = NULL; CPXLPptr model = NULL; int status = 0; int error = 0; int i, j; int cur_numrows, cur_numcols; int n_cuts, cut; int solstat; double objval; double *x; double *z; int *cstat; int n0 = rows[0].n; int n1 = rows[0].n+m-1; /// One slack variable for constraint int h = (m-1)*n0 + m-1; /// Number of nonzeros double obj[n1]; double rhs[m-1]; /// The first row is for the cost vector char sense[m-1]; int jnd[h]; int ind[h]; double val[h]; int idx = 0; int* rmatbeg; int* rmatind; double* rmatval; double* b_bar; char* gc_sense; double* gc_rhs; /// Create environment env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment. Status: %d\n", status); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto QUIT; } /// Disable presolve POST_CMD( CPXsetintparam (env, CPX_PARAM_PREIND, CPX_OFF) ); /// Create problem model = CPXcreateprob (env, &error, "gomory"); if (error) goto QUIT; /// Minimization problem POST_CMD( CPXchgobjsen (env, model, CPX_MIN) ); /// Add rows (remember first row is cost vector) for ( i = 0; i < m-1; ++i ) { sense[i]='E'; rhs[i] = rows[i+1].rhs; } POST_CMD( CPXnewrows(env, model, m-1, rhs, sense, NULL, NULL) ); /// Add problem variables for ( j = 0; j < n0; ++j ) obj[j] = rows[0].lhs[j]; /// Add slack variables for ( j = n0; j < n1; ++j ) obj[j] = 0; POST_CMD( CPXnewcols(env, model, n1, obj, NULL, NULL, NULL, NULL) ); /// Write the full matrix A into the LP (WARNING: should use only nonzeros entries) for ( i = 1; i < m; ++i ) { for ( j = 0; j < n0; ++j ) { jnd[idx] = i-1; ind[idx] = rows[i].ind[j]; val[idx] = rows[i].lhs[j]; idx++; } /// Add a slack variable per constraint jnd[idx] = i-1; ind[idx] = n0+i-1; val[idx] = 1.0; idx++; } POST_CMD( CPXchgcoeflist(env, model, idx, jnd, ind, val) ); /// Optimize the problem POST_CMD( CPXlpopt(env, model) ); /// Check the results cur_numrows = CPXgetnumrows (env, model); cur_numcols = CPXgetnumcols (env, model); x = (double *) malloc (cur_numcols * sizeof(double)); z = (double *) malloc (cur_numcols * sizeof(double)); cstat = (int *) malloc (cur_numcols * sizeof(int)); b_bar = (double *) malloc (cur_numrows * sizeof(double)); POST_CMD( CPXsolution (env, model, &solstat, &objval, x, NULL, NULL, NULL) ); if ( solstat != 1 ) { printf("The solver did not find an optimal solution\nSolver status code: %d\n",solstat); exit(0); } /// Write the output to the screen printf ("\nSolution status = %d\t\t", solstat); printf ("Solution value = %f\n\n", objval); /// If the solution is integer, is the optimum -> exit the loop if ( isInteger(cur_numcols, x) ) { fprintf(stdout,"The solution is already integer!\n"); goto QUIT; } /// Dump the problem model to 'gomory.lp' for debbuging POST_CMD( CPXwriteprob(env, model, "gomory.lp", NULL) ); /// Get the base statuses POST_CMD( CPXgetbase(env, model, cstat, NULL) ); print_solution(cur_numcols, x, cstat); printf("\nOptimal base inverted matrix:\n"); for ( i = 0; i < cur_numrows; ++i ) { b_bar[i] = 0; POST_CMD( CPXbinvrow(env, model, i, z) ); for ( j = 0; j < cur_numrows; ++j ) { printf("%.1f ", z[j]); b_bar[i] += z[j]*rhs[j]; } printf("\n"); } printf("\nOptimal solution (non basic variables are equal to zero):\n"); idx = 0; /// Compute the nonzeros n_cuts = 0; /// Number of fractional variables (cuts to be generated) for ( i = 0; i < m-1; ++i ) { POST_CMD( CPXbinvarow(env, model, i, z) ); for ( j = 0; j < n1; ++j ) { if ( z[j] >= 0 ) printf("+"); printf("%.1f x%d ", z[j], j+1); if ( floor(z[j]+0.5) != 0 ) idx++; } printf("= %.1f\n", b_bar[i]); /// Count the number of cuts to be generated if ( floor(b_bar[i]) != b_bar[i] ) n_cuts++; } /// Allocate memory for the new data structure gc_sense = (char*) malloc ( n_cuts * sizeof(char) ); gc_rhs = (double*) malloc ( n_cuts * sizeof(double) ); rmatbeg = (int*) malloc ( n_cuts * sizeof(int) ); rmatind = (int*) malloc ( idx * sizeof(int) ); rmatval = (double*) malloc ( idx * sizeof(double) ); printf("\nGenerate Gomory cuts:\n"); idx = 0; cut = 0; /// Index of cut to be added for ( i = 0; i < m-1; ++i ) if ( floor(b_bar[i]) != b_bar[i] ) { printf("Row %d gives cut -> ", i+1); POST_CMD( CPXbinvarow(env, model, i, z) ); rmatbeg[cut] = idx; for ( j = 0; j < n1; ++j ) { z[j] = floor(z[j]); /// DANGER! if ( z[j] != 0 ) { rmatind[idx] = j; rmatval[idx] = z[j]; idx++; } /// Print the cut if ( z[j] >= 0 ) printf("+"); printf("%.1f x%d ", z[j], j+1); } gc_rhs[cut] = floor(b_bar[i]); /// DANGER! gc_sense[cut] = 'L'; printf("<= %.1f\n", gc_rhs[cut]); cut++; } /// Add the new cuts POST_CMD( CPXaddrows (env, model, 0, n_cuts, idx, gc_rhs, gc_sense, rmatbeg, rmatind, rmatval, NULL, NULL) ); /// Solve the new LP POST_CMD( CPXlpopt(env, model) ); /// Check the results cur_numrows = CPXgetnumrows (env, model); cur_numcols = CPXgetnumcols (env, model); POST_CMD( CPXsolution (env, model, &solstat, &objval, x, NULL, NULL, NULL) ); if ( solstat != 1 ) { printf("The solver did not find an optimal solution\nSolver status code: %d\n",solstat); exit(0); } /// Write the output to the screen printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); POST_CMD( CPXgetbase(env, model, cstat, NULL) ); print_solution(cur_numcols, x, cstat); free_and_null ((char **) &x); free_and_null ((char **) &z); free_and_null ((char **) &cstat); free_and_null ((char **) &rmatbeg); free_and_null ((char **) &rmatind); free_and_null ((char **) &rmatval); QUIT: free_and_null ((char **) &x); free_and_null ((char **) &z); free_and_null ((char **) &cstat); if ( error ) { char errmsg[CPXMESSAGEBUFSIZE]; CPXgeterrorstring (env, error, errmsg); fprintf (stderr, "%s", errmsg); } /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( model != NULL ) { status = CPXfreeprob (env, &model); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); if ( error ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); }