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; char *ctype = NULL; /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, and row slacks. */ int solstat; double objval; double x[NUMCOLS]; double slack[NUMROWS]; 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; } /* Fill in the data for the problem. */ status = setproblemdata (&probname, &numcols, &numrows, &objsen, &obj, &rhs, &sense, &matbeg, &matcnt, &matind, &matval, &lb, &ub, &ctype); 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; } /* Now copy the ctype array */ status = CPXcopyctype (env, lp, ctype); if ( status ) { fprintf (stderr, "Failed to copy ctype\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); /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"No MIP objective value available. Exiting...\n"); goto TERMINATE; } 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); status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to get optimal integer x.\n"); goto TERMINATE; } status = CPXgetslack (env, lp, slack, 0, cur_numrows-1); if ( status ) { fprintf (stderr, "Failed to get optimal slack values.\n"); goto TERMINATE; } for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f\n", i, slack[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f\n", j, x[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "mipex1.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); free_and_null ((char **) &ctype); 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; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int cur_numrows, 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; } if ( CPXgetprobtype (env, lp) != CPXPROB_MIQP ) { fprintf (stderr, "Input file is not a MIQP. Exiting.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_OPTIMALGLOBAL); if ( status ) goto TERMINATE; status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize nonconvex MIQP.\n"); goto TERMINATE; } 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 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]); 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 **) &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 (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 */
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. */ time_t start, end; /* returns elapsed time in sec */ // clock_t start, end; /* for elapsed CPU time */ double total_time; start = clock(); 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; int method; char *basismsg; /* Check the command line arguments */ if (( argc != 4 ) || ( 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 CPX_PARAM_SCRIND 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, CPX_PARAM_SCRIND, 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 CPX_PARAM_SCRIND 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, CPX_PARAM_BARCROSSALG, 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, CPX_PARAM_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; } status = CPXsolwrite(env,lp,argv[3]); /* 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 CPX_PARAM_SCRIND 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); } } end = clock(); total_time = (double)( end - start )/(double)CLOCKS_PER_SEC ; printf( "\nElapsed time : %0.3f \n", total_time ); return (status); } /* END main */
int main (void) { /* Declare variables and arrays where we will store the optimization results including the status, objective value, and variable values. */ int solstat; double objval; int colcnt = 0; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int m, p; /* 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; } /* Formulate and solve the problem */ lp = CPXcreateprob (env, &status, "food manufacturing"); /* 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; } /* Build the model */ status = buildmodel (env, lp); if ( status ) { fprintf (stderr, "Failed to build model.\n"); goto TERMINATE; } /* Write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "foodmanu.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\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); /* Write solution status, objective and solution vector to the screen. */ printf ("\nSolution status = %d\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"No MIP objective value available. Exiting...\n"); goto TERMINATE; } printf ("Solution value (maximum profit) = %f\n\n", objval); colcnt = NUMVARS*NUMMONTHS*NUMPRODUCTS; x = (double *) malloc (colcnt * sizeof(double)); if ( x == NULL ) { status = CPXERR_NO_MEMORY; fprintf (stderr, "Could not allocate memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, colcnt - 1); if ( status ) { fprintf (stderr, "Failed to get optimal integer x.\n"); goto TERMINATE; } for (m = 0; m < NUMMONTHS; m++) { printf ("Month %d \n", m); printf (" . buy "); for (p = 0; p < NUMPRODUCTS; p++) printf ("%f\t", x[varindex(m, p, BUY)]); printf ("\n"); printf (" . use "); for (p = 0; p < NUMPRODUCTS; p++) printf ("%f\t", x[varindex (m, p, USE)]); printf ("\n"); printf (" . store "); for (p = 0; p < NUMPRODUCTS; p++) printf ("%f\t", x[varindex (m, p, STORE)]); printf ("\n"); } /* Free problem */ status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); goto TERMINATE; } TERMINATE: 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) { char ejes[100]; char labels[100]; char test[100]; archivoInput = argv[1]; randomness = argv[2]; porcentajeParticiones = atof(argv[3]); algoritmo = argv[4]; epsilonClique = atof(argv[5]); epsilonAgujero = atof(argv[6]); numeroDeModelo = atoi(argv[7]); RECORRIDO_ARBOL = atoi(argv[8]); VARIABLE_CORTE = atoi(argv[9]); semilla = atoi(argv[10]); srand(semilla); if(not freopen(archivoInput.c_str(), "r", stdin)){ cout << "No pude abrir archivo: " << archivoInput << endl; return 1; } sprintf(ejes, "ejes.out"); sprintf(labels, "labels.out"); if(randomness == "notrandom") { sprintf(test, "%s%s", argv[1], argv[2]); } else if (randomness == "random") { sprintf(test, "%s%s", argv[1], argv[3]); } else{ cout << "Paramtros mal introducidos" << endl; return 0; } read(randomness); // cada elemento de la particion conformado por un unico nodo // Le paso por parametro el algoritmo a implementar: bb = branch and bound, cb = cut and branch if(algoritmo != "bb" && algoritmo != "cb") { cout << "Error introduciendo parametro de algoritmo a ser aplicado " << endl; return 0; } // ============================================================================================== // Genero el problema de cplex. int status; // Creo el entorno. CPXENVptr env = CPXopenCPLEX(&status); // Puntero al entorno. CPXLPptr lp; // Puntero al LP if (env == NULL) { cerr << "Error creando el entorno" << endl; exit(1); } ///Iniciio el reloj CPXgettime(env, &inittime); // Creo el LP. lp = CPXcreateprob(env, &status, "instancia coloreo de grafo particionado"); if (lp == NULL) { cerr << "Error creando el LP" << endl; exit(1); } // Definimos las variables. En total, son P + N*P variables ( las W[j] y las X[i][j] ) int cantVariables = P + N*P; double *ub, *lb, *objfun; // Cota superior, cota inferior, coeficiente de la funcion objetivo. char *xctype, **colnames; // tipo de la variable , string con el nombre de la variable. ub = new double[cantVariables]; lb = new double[cantVariables]; objfun = new double[cantVariables]; xctype = new char[cantVariables]; colnames = new char*[cantVariables]; for (int i = 0; i < cantVariables; i++) { ub[i] = 1.0; // seteo upper y lower bounds de cada variable lb[i] = 0.0; if(i < P) { // agrego el costo en la funcion objetivo de cada variables objfun[i] = 1; // busco minimizar Sum(W_j) para j=0..P (la cantidad de colores utilizados). } else { objfun[i] = 0; // los X[i][j] no contribuyen a la funcion objetivo } xctype[i] = 'B'; // 'C' es continua, 'B' binaria, 'I' Entera. colnames[i] = new char[10]; } /* Defino el tipo de variable BoolVarMatrix, que sera utilizado en la resolucion * recordar: X_v_j = 1 sii el color j es asignado al vertice v * recordar: W_j = 1 si X_v_j = 1 para al menos un vertice v */ for(int j=0; j<P; j++) { sprintf(colnames[j], "W_%d", j); // cout << colnames[j] << endl; } for(int i=0; i<N; i++) { for(int j=0; j<P; j++) { sprintf(colnames[xijIndice(i,j)], "X_%d_%d", i, j); // cout << colnames[xijIndice(i,j)] << endl; } } // ========================== Agrego las columnas. =========================== // if(algoritmo == "cb"){ // si quiero resolver la relajacion, agregar los cortes y despues resolver el MIP, no agrego xctype status = CPXnewcols(env, lp, cantVariables, objfun, lb, ub, NULL, colnames); } else if (algoritmo == "bb"){ // si quiero hacer MIP, directamente, con brancha and bound, agrego xctype status = CPXnewcols(env, lp, cantVariables, objfun, lb, ub, xctype, colnames); } else { cout << "Error: parametro de algoritmo bb/cb mal introducido" << endl; return 0; } if (status) { cerr << "Problema agregando las variables CPXnewcols" << endl; exit(1); } // Libero las estructuras. for (int i = 0; i < cantVariables; i++) { delete[] colnames[i]; } delete[] ub; delete[] lb; delete[] objfun; delete[] xctype; delete[] colnames; // CPLEX por defecto minimiza. Le cambiamos el sentido a la funcion objetivo si se quiere maximizar. // CPXchgobjsen(env, lp, CPX_MAX); // ================================================================================================ // // ===================================== Restricciones ============================================ // // i) Asigno exactamente un color a exactamente un vertice de cada particion ( P restricciones ) // ii) Dos vertices adyacentes no pueden tener el mismo color ( E restricciones ) // iii) Los W_j estan bien armados, en funcion de X_v_j ( 2*P restricciones ) // ccnt = numero nuevo de columnas en las restricciones. // rcnt = cuantas restricciones se estan agregando. // nzcnt = # de coeficientes != 0 a ser agregados a la matriz. Solo se pasan los valores que no son cero. int ccnt = 0; int rcnt; if(numeroDeModelo == 0){ rcnt = P + (E*P)/2 + 2*P; // Cota maxima a la cantidad de restricciones } else{ rcnt = P + (E*P)/2 + N*P; } // (E/2 porque en la entrada se supone que en la entrada me pasan 2 veces cada eje) int nzcnt = 0; // al ppio es cero (para cada valor q agrego, lo voy a incrementar en 1) char sense[rcnt]; // Sentido de la desigualdad. 'G' es mayor o igual y 'E' para igualdad, 'L' menor o igual double *rhs = new double[rcnt]; // Termino independiente de las restricciones. int *matbeg = new int[rcnt]; //Posicion en la que comienza cada restriccion en matind y matval. int *matind = new int[rcnt*cantVariables]; // Array con los indices de las variables con coeficientes != 0 en la desigualdad. double *matval = new double[rcnt*cantVariables]; // Array que en la posicion i tiene coeficiente ( != 0) de la variable matind[i] en la restriccion. // CPLEX va a leer hasta la cantidad nzcnt que le pasemos. int cantRestricciones = 0; // r = numero de restriccion // i) P restricciones - exactamente un color a cada vertice (una restriccion por cada particion) for(int particion = 0; particion < P; particion++) { matbeg[cantRestricciones] = nzcnt; rhs[cantRestricciones] = 1; sense[cantRestricciones] = 'E'; for(int e = 0; e < S[particion].size(); e++) { for(int color = 0; color < P; color++) { matind[nzcnt] = xijIndice(S[particion][e], color); matval[nzcnt] = 1; nzcnt++; } } cantRestricciones++; } // ii) Cota superior de (E*P)/2 restricciones mas // Una para cada par de vecinos i j, para cada color pero solo cuando i < j, y estan en distinta particion for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { if(M[i][j] == 1 and dameParticion(i) != dameParticion(j)){ for(int color = 0; color < P; color++) { matbeg[cantRestricciones] = nzcnt; rhs[cantRestricciones] = 1; sense[cantRestricciones] = 'L'; matind[nzcnt] = xijIndice(i,color); matval[nzcnt] = 1; nzcnt++; matind[nzcnt] = xijIndice(j,color); matval[nzcnt] = 1; nzcnt++; cantRestricciones++; } } } } if(numeroDeModelo == 0){ // iii) 2*P restricciones mas // - P * wj + sigma xij <= 0 for(int k=0; k<P; k++) { // para cada color matbeg[cantRestricciones] = nzcnt; rhs[cantRestricciones] = 0; sense[cantRestricciones] = 'L'; matind[nzcnt] = k; matval[nzcnt] = -1 * P; nzcnt++; for(int i=0; i<N; i++) { matind[nzcnt] = xijIndice(i,k); matval[nzcnt] = 1; nzcnt++; } cantRestricciones++; } // - wj + sigma xij >= 0 for(int k=0; k<P; k++) { matbeg[cantRestricciones] = nzcnt; rhs[cantRestricciones] = 0; sense[cantRestricciones] = 'G'; matind[nzcnt] = k; matval[nzcnt] = -1; nzcnt++; for(int i=0; i<N; i++) { matind[nzcnt] = xijIndice(i,k); matval[nzcnt] = 1; nzcnt++; } cantRestricciones++; } } else{ // iii) N*P restricciones mas // -wj + xij <= 0 for(int color = 0; color < P; color++) { for(int i = 0; i < N; i++) { matbeg[cantRestricciones] = nzcnt; rhs[cantRestricciones] = 0; sense[cantRestricciones] = 'L'; matind[nzcnt] = color; matval[nzcnt] = -1; nzcnt++; matind[nzcnt] = xijIndice(i, color); matval[nzcnt] = 1; nzcnt++; cantRestricciones++; } } } //Actualizo rcnt. rcnt = cantRestricciones; // =================================================================================================== // Agregamos las restricciones al lp. status = CPXaddrows(env, lp, ccnt, rcnt, nzcnt, rhs, sense, matbeg, matind, matval, NULL, NULL); if (status) { cerr << "Problema agregando restricciones." << endl; exit(1); } delete[] rhs; delete[] matbeg; delete[] matind; delete[] matval; // ============================================================================================== // // ================================== Optimizamos el problema. ================================== // // Seteo de algunos parametros. // Para desactivar la salida poner CPX_OFF. status = CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); if (status) { cerr << "Problema seteando SCRIND" << endl; exit(1); } // Setea el tiempo limite de ejecucion. status = CPXsetdblparam(env, CPX_PARAM_TILIM, TIEMPO_LIMITE); // setear limite de tiempo en 3600 !!!!!!! if (status) { cerr << "Problema seteando el tiempo limite" << endl; exit(1); } // Escribimos el problema a un archivo .lp. // status = CPXwriteprob(env, lp, "test.lp", NULL); if (status) { cerr << "Problema escribiendo modelo" << endl; exit(1); } // Seteamos algunos parametros para resolver con branch and bound CPXsetintparam(env, CPX_PARAM_MIPSEARCH, CPX_MIPSEARCH_TRADITIONAL); // Para facilitar la comparación evitamos paralelismo: CPXsetintparam(env, CPX_PARAM_THREADS, 1); //Para que no se adicionen planos de corte: CPXsetintparam(env,CPX_PARAM_EACHCUTLIM, 0); CPXsetintparam(env, CPX_PARAM_FRACCUTS, -1); CPXsetintparam(env, CPX_PARAM_LANDPCUTS, -1); // Para que no haga preprocesamientos CPXsetintparam(env, CPX_PARAM_PRESLVND, -1); CPXsetintparam(env, CPX_PARAM_REPEATPRESOLVE, 0); CPXsetintparam(env, CPX_PARAM_RELAXPREIND, 0); CPXsetintparam(env, CPX_PARAM_REDUCE, 0); // Recorrido del arbol CPXsetintparam(env, CPX_PARAM_NODESEL, RECORRIDO_ARBOL); // Seleccion de variable CPXsetintparam(env, CPX_PARAM_VARSEL, VARIABLE_CORTE); CPXgettime(env, &endtime); tiempoPreparar = endtime - inittime; inittime = endtime; // ========================================================================================================= // resuelvo con cut and branch (con los cortes definidos por nosotros) o con branch and bound (y sin cortes) // ========================================================================================================= if(algoritmo == "cb") { // while (algo) ... resolver el lp, chequear si la restr inducida por la clique actual es violada. Seguir //cout << "antes" << endl; for(int ciclocb=0; ciclocb<CANT_CICLOS_CB; ciclocb++) { status = CPXlpopt(env, lp); //cout << "despues" << endl; double objval; status = CPXgetobjval(env, lp, &objval); // Aca, deberia agregar los cortes requeridos, en funcion de "cliques" y "objval" // mostrameValores(env, lp); double *sol = new double[cantVariables]; CPXgetx(env, lp, sol, 0, cantVariables - 1); //CPXwriteprob (env, lp, "antesDeClique.lp", "LP"); // BUSCAR Y AGREGAR CLIQUE vector < vector<int> > agregados; for(int color=0; color<P; color++) { for(int i=0; i<CANT_RESTR_CLIQUES; i++) { bool iteracionRandom = (i!=0); vector<int> clique = dameClique(sol, color, iteracionRandom); sort(clique.begin(), clique.end()); bool incluido = find(agregados.begin(), agregados.end(), clique) != agregados.end(); if (not incluido and not clique.empty()) { agregados.push_back(clique); agregarRestriccionClique(env, lp, clique); cantidadCortesClique++; // cout << "AGREGO RESTRICCION DE CLIQUE de random " << iteracionRandom << " y de color #"<< color << ": "; // for(int j=0; j<clique.size(); j++) { // cout << clique[j] << " "; // } // cout << endl; } } } // BUSCAR Y AGREGAR AGUJERO agregados.clear(); for(int color=0; color<P; color++) { for(int i=0; i<CANT_RESTR_AGUJEROS; i++) { vector<int> agujero = dameAgujero(sol, color); bool incluido = find(agregados.begin(), agregados.end(), agujero) != agregados.end(); if (not incluido and not agujero.empty()) { agregados.push_back(agujero); agregarRestriccionAgujero(env, lp, agujero); cantidadCortesAgujero++; // cout << "AGREGO RESTRICCION DE AGUJERO de color #"<< color << ": "; // for(int j=0; j<agujero.size(); j++) { // cout << agujero[j] << " "; // } // cout << endl; } } } delete [] sol; } // CPXwriteprob (env, lp, "lpCB.lp", "LP"); ///Cuando salimos, pasamos a binaria y corremos un branch and bound char *ctype = new char[cantVariables]; for (int i = 0; i < cantVariables; i++) { ctype[i] = 'B'; } // cout << "Antes cambiar tipo" << endl; status = CPXcopyctype (env, lp, ctype); // cout << "Despues cambiar tipo" << endl; delete[] ctype; CPXgettime(env, &endtime); tiempoCutAndBranch = endtime - inittime; inittime = endtime; } ///Corremos el BB, ya sea porque esto es lo que queriamos originalemente, o porque terminamos con los planos de corte // cout << "ANTES" << endl; //CPXwriteprob (env, lp, "antesDeMip.lp", "LP"); CPXmipopt(env,lp); // cout << "DESPUES" << endl; CPXgettime(env, &endtime); tiempoBranchAndBound = endtime - inittime; // inittime = endtime; status = CPXgettime(env, &endtime); if (status) { cerr << "Problema optimizando CPLEX" << endl; exit(1); } // Chequeamos el estado de la solucion. int solstat; char statstring[510]; CPXCHARptr p; solstat = CPXgetstat(env, lp); p = CPXgetstatstring(env, solstat, statstring); string statstr(statstring); cout << endl << "Resultado de la optimizacion: " << statstring << endl; if(solstat!=CPXMIP_OPTIMAL && solstat!=CPXMIP_OPTIMAL_TOL && solstat!=CPXMIP_NODE_LIM_FEAS && solstat!=CPXMIP_TIME_LIM_FEAS){ cout << "No hay solucion" << endl; } else{ double objval; status = CPXgetobjval(env, lp, &objval); if (status) { cerr << "Problema obteniendo valor de mejor solucion." << endl; exit(1); } cout << "Datos de la resolucion: " << "\t" << objval << "\t" << tiempoPreparar + tiempoCutAndBranch + tiempoBranchAndBound << endl; cout << "Tiempo en preparar: " << "\t" << tiempoPreparar << endl; cout << "Tiempo en CB: " << "\t" << tiempoCutAndBranch << endl; cout << "Tiempo en BB: " << "\t" << tiempoBranchAndBound << endl; // Tomamos los valores de todas las variables. Estan numeradas de 0 a n-1. double *sol = new double[cantVariables]; status = CPXgetx(env, lp, sol, 0, cantVariables - 1); if (status) { cerr << "Problema obteniendo la solucion del LP." << endl; exit(1); } impresionModelo(env, lp); // Solo escribimos las variables distintas de cero (tolerancia, 1E-05). //solfile << "Status de la solucion: " << statstr << endl; // for(int j=0; j<P; j++) { // if(sol[j] > TOL) { // cout << "W_" << j << " = " << sol[j] << endl; // } // } // for(int i=0; i<N; i++) { // for(int j=0; j<P; j++) { // if(sol[P + P*i + j] > TOL) { // cout << "X_" << i << "_" << j << " = " << sol[P+P*i+j] << endl; // } // } // } //solfile.close(); // ==================== Devuelvo el grafo resultante coloreado, para graficar! ====================== // // ofstream streamEjes, streamLabels; //ofstream streamParticiones; // Tomamos los valores de la solucion y los escribimos a un archivo. // streamEjes.open(ejes); // for(int v1=0; v1<N; v1++) { // for(int v2=v1+1; v2<N; v2++) { // if (M[v1][v2] == 1) { // streamEjes << v1+1 << " " << v2+1 << endl; // } // } // } streamEjes.close(); // cout << ejes << endl; // streamLabels.open(labels); // bool estaColoreado; // for(int v=0; v<N; v++){ // estaColoreado = false; // for(int j=0; j<P; j++){ // if (sol[P + P*v + j] == 1) { // streamLabels << v+1 << " " << j+1 << endl; // estaColoreado = true; // } // } // if(not estaColoreado) { // streamLabels << v+1 << " " << 0 << endl; // } // } // streamLabels.close(); // delete [] sol; } return 0; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int i, j; double *c=NULL, *b=NULL, *A=NULL, *H=NULL, *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ; int *nzA=NULL, *nzH=NULL ; int *iA=NULL, *kA=NULL ; int *iH=NULL, *kH=NULL ; #ifndef MX_COMPAT_32 long *iA_=NULL, *kA_=NULL ; long *iH_=NULL, *kH_=NULL ; #endif int neq=0, m=0, n=0, display=0; long *cpenv=NULL, *p_qp=NULL; char *Sense=NULL ; CPXENVptr env = NULL; CPXLPptr qp = NULL; int status, qpstat; double objval; double * p_qpstat ; char opt_method[128]="auto" ; if (nrhs > 10 || nrhs < 1) { mexErrMsgTxt("Usage: [x,lambda,how,p_qp] " "= qp_solve(cpenv,Q,c,A,b,l,u,neq,disp,method)"); return; } switch (nrhs) { case 10: if (mxGetM(prhs[9]) != 0 || mxGetN(prhs[9]) != 0) { if (mxIsNumeric(prhs[9]) || mxIsComplex(prhs[9]) || !mxIsChar(prhs[9]) || mxIsSparse(prhs[9]) || !(mxGetM(prhs[9])==1 && mxGetN(prhs[9])>=1)) { mexErrMsgTxt("10th argument (method) must be " "a string."); return; } mxGetString(prhs[9], opt_method, 128) ; } case 9: if (mxGetM(prhs[8]) != 0 || mxGetN(prhs[8]) != 0) { if (!mxIsNumeric(prhs[8]) || mxIsComplex(prhs[8]) || mxIsSparse(prhs[8]) || !(mxGetM(prhs[8])==1 && mxGetN(prhs[8])==1)) { mexErrMsgTxt("9th argument (display) must be " "an integer scalar."); return; } display = *mxGetPr(prhs[8]); } case 8: if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) { if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7]) || mxIsSparse(prhs[7]) || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) { mexErrMsgTxt("8th argument (neqcstr) must be " "an integer scalar."); return; } neq = *mxGetPr(prhs[7]); } case 7: if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) { if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6]) || mxIsSparse(prhs[6]) || !mxIsDouble(prhs[6]) || mxGetN(prhs[6])!=1 ) { mexErrMsgTxt("7th argument (u) must be " "a column vector."); return; } u = mxGetPr(prhs[6]); n = mxGetM(prhs[6]); } case 6: if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) { if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) || mxIsSparse(prhs[5]) || !mxIsDouble(prhs[5]) || mxGetN(prhs[5])!=1 ) { mexErrMsgTxt("6th argument (l) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[5])) { mexErrMsgTxt("Dimension error (arg 6 and later)."); return; } l = mxGetPr(prhs[5]); n = mxGetM(prhs[5]); } case 5: if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) { if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 ) { mexErrMsgTxt("5th argument (b) must be " "a column vector."); return; } if (m != 0 && m != mxGetM(prhs[4])) { mexErrMsgTxt("Dimension error (arg 5 and later)."); return; } b = mxGetPr(prhs[4]); m = mxGetM(prhs[4]); } case 4: if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || !mxIsSparse(prhs[3]) ) { mexErrMsgTxt("4th argument (A) must be " "a sparse matrix."); return; } if (m != 0 && m != mxGetM(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } if (n != 0 && n != mxGetN(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } m = mxGetM(prhs[3]); n = mxGetN(prhs[3]); A = mxGetPr(prhs[3]); #ifdef MX_COMPAT_32 iA = mxGetIr(prhs[3]); kA = mxGetJc(prhs[3]); #else iA_ = mxGetIr(prhs[3]); kA_ = mxGetJc(prhs[3]); iA = (int*)malloc(mxGetNzmax(prhs[3])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[3]); i++) iA[i]=iA_[i] ; kA = (int*)malloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kA[i]=kA_[i] ; #endif nzA=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzA[i]=kA[i+1]-kA[i] ; Sense=myMalloc((m+1)*sizeof(char)) ; for (i=0; i<m; i++) if (i<neq) Sense[i]='E' ; else Sense[i]='L' ; Sense[m]=0 ; } case 3: if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) { if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2]) || mxGetN(prhs[2])!=1 ) { mexErrMsgTxt("3rd argument (c) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } c = mxGetPr(prhs[2]); n = mxGetM(prhs[2]); } case 2: if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || !mxIsSparse(prhs[1]) ) { mexErrMsgTxt("2nd argument (H) must be " "a sparse matrix."); return; } if (n != 0 && n != mxGetM(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } if (n != 0 && n != mxGetN(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } n = mxGetN(prhs[1]); H = mxGetPr(prhs[1]); #ifdef MX_COMPAT_32 iH = mxGetIr(prhs[1]); kH = mxGetJc(prhs[1]); #else iH_ = mxGetIr(prhs[1]); kH_ = mxGetJc(prhs[1]); iH = (int*)malloc(mxGetNzmax(prhs[1])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[1]); i++) iH[i]=iH_[i] ; kH = (int*)malloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kH[i]=kH_[i] ; #endif nzH=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzH[i]=kH[i+1]-kH[i] ; } case 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 (cpenv) must be " "a column vector."); return; } if (1 != mxGetM(prhs[0])) { mexErrMsgTxt("Dimension error (arg 1)."); return; } cpenv = (long*) mxGetPr(prhs[0]); } } /*if (display>3) */ fprintf(STD_OUT,"argument processing finished") ; /* Initialize the CPLEX environment */ env = (CPXENVptr) cpenv[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; } status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, display); if ( status ) { fprintf (STD_OUT,"Failed to turn up simplex display level.\n"); goto TERMINATE; } if (nlhs > 4 || nlhs < 1) { mexErrMsgTxt("Usage: [x,lambda,how,p_qp] " "= qp_solve(cpenv,H,c,A,b,l,u,neqcstr)"); return; } if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ; switch (nlhs) { case 4: plhs[3] = mxCreateDoubleMatrix(1, 1, mxREAL); p_qp = (long*) mxGetPr(plhs[3]); case 3: /* plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL); p_qpstat = mxGetPr(plhs[2]);*/ case 2: plhs[1] = mxCreateDoubleMatrix(m, 1, mxREAL); lambda = mxGetPr(plhs[1]); case 1: plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL); x = mxGetPr(plhs[0]); break; } if (display>2) fprintf(STD_OUT, "argument processing finished\n") ; if (strcmp(opt_method, "primal") && strcmp(opt_method, "dual") && strcmp(opt_method, "net") && strcmp(opt_method, "bar") && strcmp(opt_method, "sift") && strcmp(opt_method, "con") && strcmp(opt_method, "auto")) mexErrMsgTxt("method \\in " "{'auto','primal','dual','bar','net','sift','con'}\n") ; if (strcmp(opt_method, "primal")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 1); else if (strcmp(opt_method, "dual")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 2); else if (strcmp(opt_method, "net")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 3); else if (strcmp(opt_method, "bar")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 4); else if (strcmp(opt_method, "sift")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 5); else if (strcmp(opt_method, "con")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 6); else if (strcmp(opt_method, "auto")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 0); else status = 1 ; if ( status ) { fprintf (STD_OUT,"Failed to set QP method.\n"); goto TERMINATE; } /* Create the problem */ if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ; qp = CPXcreateprob (env, &status, "xxx"); if ( qp == NULL ) { fprintf (STD_OUT,"Failed to create subproblem\n"); status = 1; goto TERMINATE; } if (p_qp) *p_qp=(long) qp ; /* Copy network part of problem. */ /*if (display>2) */ fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ; status = CPXcopylp(env, qp, n, m, CPX_MIN, c, b, Sense, kA, nzA, iA, A, l, u, NULL); if ( status ) { fprintf (STD_OUT, "CPXcopylp failed.\n"); goto TERMINATE; } /*if (display>2) */ fprintf(STD_OUT, "calling CPXcopyquad \n") ; status = CPXcopyquad (env, qp, kH, nzH, iH, H); if ( status ) { fprintf (STD_OUT, "CPXcopyquad failed.\n"); goto TERMINATE; } /*if (display>2) */ fprintf(STD_OUT, "calling optimizer 'bar'\n") ; status = CPXqpopt (env, qp); if (display>3) fprintf(STD_OUT, "CPXbaropt=%i\n", status) ; if ( status ) { fprintf (STD_OUT,"CPXbaropt failed.\n"); goto TERMINATE; } if (display>2) fprintf(STD_OUT, "calling CPXsolution\n") ; status = CPXsolution (env, qp, &qpstat, &objval, x, lambda, NULL, NULL); if ( status ) { fprintf (STD_OUT,"CPXsolution failed.\n"); goto TERMINATE; } if (display>1) fprintf (STD_OUT, "Solution status: %i,%s\n", qpstat, err_str[qpstat]); if (display>2) fprintf (STD_OUT, "Objective value %g\n", objval); if (nlhs >= 3) if (qpstat==1) plhs[2] = mxCreateString(err_str[0]) ; else plhs[2] = mxCreateString(err_str[qpstat]) ; /* if (nlhs >= 3) if (qpstat==1) *p_qpstat = 0 ; else *p_qpstat = qpstat ;*/ TERMINATE: if (status) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (STD_OUT, "%s", errmsg); if (nlhs >= 3) plhs[2] = mxCreateString(errmsg) ; } ; if (nzA) myFree(nzA) ; if (nzH) myFree(nzH) ; if (Sense) myFree(Sense) ; #ifndef MX_COMPAT_32 if (iA) myFree(iA) ; if (kA) myFree(kA) ; if (iH) myFree(iH) ; if (kH) myFree(kH) ; #endif if (!p_qp) { if ( qp != NULL ) { if (display>2) fprintf(STD_OUT, "calling CPXfreeprob\n") ; status = CPXfreeprob (env, &qp); if ( status ) { fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status); } } } return ; }
reducemex(double M[], double costs[], double stats[], double ikeep[], double m[], int matbeg[], int matcnt[], int matind[], double matval[], char sense[], int objsen, double lb[], double ub[], int numrows, int numcols, double tol) { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; char probname[16]; double *pi; double *slack; double *dj; double *obj; int solstat; double objval; double *x; double newval; int *indices; int kc, i; obj = mxCalloc(numcols,sizeof(double)); x = mxCalloc(numcols,sizeof(double)); indices = mxCalloc(numcols,sizeof(int)); pi = mxCalloc(numrows,sizeof(double)); slack = mxCalloc(numrows,sizeof(double)); dj = mxCalloc(numcols,sizeof(double)); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[1024]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn off output to the screen */ status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn off pre-processor status = CPXsetintparam (env, CPX_PARAM_PREIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn off pre-processor, error %d.\n", status); goto TERMINATE; } /* Turn off aggregator status = CPXsetintparam (env, CPX_PARAM_AGGIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn of aggregator, error %d.\n", status); goto TERMINATE; }*/ /* Create the problem. */ strcpy(probname,"LPnoname"); lp = CPXcreateprob (env, &status, probname); if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Initialize data */ for (kc = 0; kc <= numcols-1; kc++) { indices[kc] = kc; } /* Now copy the problem data into the lp */ status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, m, sense, matbeg, matcnt, matind, matval, lb, ub, NULL); if ( status ) { fprintf (stderr, "Failed to copy problem data.\n"); goto TERMINATE; } /**********MAIN LOOP************/ for(i = 0; i <= numrows-1; i++) { for (kc = 0; kc <= numcols-1; kc++) { obj[kc] = M[i+kc*numrows]; } CPXchgobj(env, lp, numcols, indices, obj); newval = m[i] + 10; CPXchgrhs(env, lp, 1, &i, &newval); /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); /*status = CPX[prim/dual]opt (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; } ikeep[i] = 0; if (objval > m[i] + tol) /* keep row */ { ikeep[i] = 1; newval = m[i]; CPXchgrhs(env, lp, 1, &i, &newval); } /* Write the output to the screen. */ /* printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); */ costs[i] = objval; stats[i] = solstat; } 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); if ( status ) { char errmsg[1024]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } }
EXPORT int fit(const double * X_p, const double * Yl_p, double* w, int postags, int numSamples, int numFeatures, double C, double epsilon, int numBoxConstraints, const double * boxValues, const int64_t * boxIndices, const double * boxMatrix) { int i,j,k; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; char probname[] = "Testproblem"; int numrows = postags + numSamples; int numcols = numFeatures + 1 + numrows; int nnzcol = numFeatures + 2; int numEntries = nnzcol * numrows; char *sense = (char*) malloc((numrows) * sizeof(char)); double *lb = (double*) malloc(numcols * sizeof(double)); double *ub = (double*) malloc(numcols * sizeof(double)); double *obj = (double*) malloc(numcols * sizeof(double)); double *rhs = (double*) malloc(numrows * sizeof(double)); double *tagarray = (double*) malloc(numrows * sizeof(double)); int *matbeg = (int*) malloc(numcols * sizeof(int)); int *matcnt = (int*) malloc(numcols * sizeof(int)); int *matind = (int*) malloc(numEntries * sizeof(int)); double *matval = (double* ) malloc(numEntries * sizeof(double)); double *qsepvec = (double*) malloc((numcols + 2 * numBoxConstraints) * sizeof(double)); int numBoxSamples = 0; double *dens = NULL; double *boxConstraints = NULL; int *boxrmatbeg = NULL; int *boxrmatind = NULL; char *boxSense = NULL; int *hmatbeg = NULL; int *hmatind = NULL; double *hmatval = NULL; char *hSense = NULL; env = CPXopenCPLEX (&status); lp = CPXcreateprob (env, &status, probname); status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF); status = CPXsetintparam (env, CPX_PARAM_BARCOLNZ, 2); if ( status ) { fprintf (stderr, "Failure to create CPLEX environment, error %d.\n", status); goto TERMINATE; } if (sense == NULL || lb == NULL || ub == NULL || obj == NULL || rhs == NULL || tagarray == NULL || qsepvec == NULL) { status = 1; goto TERMINATE; } for (i = 0; i < postags; ++i) { tagarray[i] = 1; sense[i] = 'G'; } for (i = postags; i < numrows; ++i) { tagarray[i] = -1; sense[i] = 'L'; } for (i = 0; i < postags; ++i) { rhs[i] = Yl_p[i] - tagarray[i] * epsilon ; } for (i = postags; i < numrows; ++i) { rhs[i] = Yl_p[i - postags] - tagarray[i] * epsilon ; } for (i = 0; i < numFeatures + 1; ++i) { lb[i] = -CPX_INFBOUND; ub[i] = CPX_INFBOUND; matbeg[i] = i * (numrows); matcnt[i] = numrows; } for (i = numFeatures + 1; i < numcols; ++i) { lb[i] = 0; ub[i] = CPX_INFBOUND; matbeg[i] = (numFeatures + 1) * numrows + (i - numFeatures - 1); matcnt[i] = 1; } for (j = 0; j < numFeatures; ++j) { for (i = 0; i < postags; ++i) { matind[j * numrows + i] = i; matval[j * (numrows) + i] = X_p[i * numFeatures + j]; } for (i = postags; i < numrows; ++i) { matind[j * numrows + i] = i; matval[j * (numrows) + i] = X_p[(i - postags) * numFeatures + j]; } } /* printf("Status ok\n");*/ for (i = 0; i < numrows; ++i) { matind[numFeatures * numrows + i] = i; matval[numFeatures * numrows + i] = 1; } for (i = 0; i < numrows; ++i) { matind[(numFeatures + 1) * numrows + i] = i; matval[(numFeatures + 1) * numrows + i] = tagarray[i]; } for (i = 0; i < numFeatures; ++i){ qsepvec[i] = 1; obj[i] = 0; } obj[numFeatures] = 0; qsepvec[numFeatures] = 0; for (i = numFeatures + 1; i < numcols; ++i){ qsepvec[i] = 2 * C; obj[i] = 0; } /*printf("Status ok\n");*/ status = CPXcopylp (env, lp, numcols, numrows, 1, obj, rhs, sense, matbeg, matcnt, matind, matval, lb, ub, NULL); status = CPXcopyqpsep (env, lp, qsepvec); status = CPXwriteprob (env, lp, "qpex1.lp", NULL); status = CPXqpopt (env, lp); status = CPXgetx (env, lp, w, 0, numFeatures); if (numBoxConstraints > 0) { numBoxSamples = (int) boxIndices[numBoxConstraints]; dens = (double*) malloc(numBoxSamples * sizeof(double)); boxConstraints = (double*) calloc(numBoxConstraints * (numFeatures + 2), sizeof(double)); boxrmatbeg = (int*) malloc(numBoxConstraints * sizeof(int)); boxrmatind = (int*) malloc(numBoxConstraints * (numFeatures + 2) * sizeof(int)); boxSense = (char*) malloc(numBoxConstraints * sizeof(char)); hmatbeg = (int*) malloc(numBoxSamples * sizeof(int)); hmatind = (int*) malloc(numBoxSamples * (numFeatures + 1) * sizeof(int)); hmatval = (double* ) malloc(numBoxSamples * (numFeatures + 1) * sizeof(double)); hSense = (char* ) malloc(numBoxSamples * sizeof(char)); if (dens == NULL || boxConstraints == NULL || boxrmatbeg == NULL || boxrmatind == NULL || boxSense == NULL) { status = 1; goto TERMINATE; } if (hmatbeg == NULL || hmatind == NULL || hmatval == NULL || hSense == NULL) { status = 1; goto TERMINATE; } /*for every entry in the box features, check if it's background or foreground double *boxrmatval = (double* ) malloc( * sizeof(double));*/ for (i = 0; i < numBoxSamples; ++i) { dens[i] = w[numFeatures]; for (j = 0; j < numFeatures; ++j) { dens[i] += boxMatrix[i * numFeatures + j] * w[j]; } } for (i = 0; i < numBoxSamples; ++i) { if (dens[i] > 0){ dens[i] = 1; } else { dens[i] = 0; } /* printf("Density: %f\n", dens[i]); */ } /*printfarray(boxConstraints, numBoxConstraints, numFeatures + 2, "boxConstraints"); */ for (k = 0; k < numBoxConstraints; ++k) { boxrmatbeg[k] = k * (numFeatures + 2); for (i = (int) boxIndices[k]; i < boxIndices[k + 1]; ++i){ for (j = 0; j < numFeatures; ++j){ boxConstraints[k * (numFeatures + 2) + j] += dens[i] * boxMatrix[i * numFeatures + j]; } boxConstraints[k * (numFeatures + 2) + numFeatures] += dens[i]; } } for (i = 0; i < numBoxConstraints; ++i) { for (j = 0; j < numFeatures + 1; ++j) { boxrmatind[i * (numFeatures + 2) + j] = j; } boxrmatind[i * (numFeatures + 2) + numFeatures + 1] = numcols + i; } for (i = 0; i < numBoxConstraints; ++i) { boxSense[i] = 'L'; } for (i = 0; i < numBoxConstraints; ++i) { boxConstraints[i * (numFeatures + 2) + numFeatures+1] = - 1; } status = CPXaddrows(env, lp, numBoxConstraints, numBoxConstraints, numBoxConstraints * (numFeatures + 2), boxValues, boxSense, boxrmatbeg, boxrmatind, boxConstraints, NULL, NULL); for (i = 0; i < numBoxConstraints; ++i) { boxrmatind[i * (numFeatures + 2) + numFeatures + 1] = numcols + numBoxConstraints + i; } for (i = 0; i < numBoxConstraints; ++i) { boxSense[i] = 'G'; } for (i = 0; i < numBoxConstraints; ++i) { boxConstraints[i * (numFeatures + 2) + numFeatures+1] = + 1; } status = CPXaddrows(env, lp, numBoxConstraints, numBoxConstraints, numBoxConstraints * (numFeatures + 2), boxValues, boxSense, boxrmatbeg, boxrmatind, boxConstraints, NULL, NULL); for (i = 0; i < numBoxConstraints; ++i) { qsepvec[numcols + i] = 2 * C / (boxIndices[i + 1] - boxIndices[i]); qsepvec[numcols + i + numBoxConstraints] = 2 * C / (boxIndices[i + 1] - boxIndices[i]); /* printf("%d, %d\n",boxIndices[i], boxIndices[i + 1]); printf("%f, %f\n", qsepvec[numcols+i], qsepvec[numcols + i + numBoxConstraints]); */ } /*adding hard constraints:*/ for (i = 0; i < numBoxSamples; ++i) { hmatbeg[i] = i * (numFeatures + 1); for (j = 0; j < numFeatures; ++j) { hmatind[i * (numFeatures + 1) + j] = j; hmatval[i * (numFeatures + 1) + j] = boxMatrix[i * numFeatures + j]; } hmatind[i * (numFeatures + 1) + numFeatures] = numFeatures; hmatval[i * (numFeatures + 1) + numFeatures] = 1; if (dens[i] == 0){ hSense[i] = 'L'; } else { hSense[i] = 'G'; } } /* printf("Density: %f\n", dens[i]); printf("Close, but no cigar\n"); printiarray(hmatind, backgroundcount, numFeatures + 1, ""); printf("Close, but no cigar\n"); */ status = CPXaddrows(env, lp, 0, numBoxSamples, numBoxSamples* (numFeatures + 1), NULL, hSense, hmatbeg, hmatind, hmatval, NULL, NULL); /* printf("WHY IS NOTHING HAPPENING\n") */ printf ("Number of Columns in Problem: %d\n", CPXgetnumcols(env, lp)); printf("%d\n", numcols + (2 * numBoxConstraints)); status = CPXcopyqpsep (env, lp, qsepvec); status = CPXwriteprob (env, lp, "qpex1.lp", NULL); status = CPXqpopt (env, lp); status = CPXgetx (env, lp, w, 0, numFeatures); /*for (i = 0; i < numBoxSamples; ++i) { density[i] = w[numFeatures]; for (j = 0; j < numFeatures; ++j) { density[i] += boxMatrix[i * numFeatures + j] * w[j]; } } */ } /*printf("Objective value: %f\n", sol); double * slack = malloc((numcols + 2 * numBoxConstraints) * sizeof(double)); status = CPXgetx (env, lp, slack, 0, numcols + 2 * numBoxConstraints - 1); printfarray(slack, numcols + 2 * numBoxConstraints, 1, "Slack"); */ TERMINATE:; free_and_null ((char **) &obj); free_and_null ((char **) &rhs); free_and_null ((char **) &sense); free_and_null ((char **) &tagarray); free_and_null ((char **) &lb); free_and_null ((char **) &ub); free_and_null ((char **) &matbeg); free_and_null ((char **) &matcnt); free_and_null ((char **) &matind); free_and_null ((char **) &matval); free_and_null ((char **) &qsepvec); free_and_null ((char **) &dens); free_and_null ((char **) &boxConstraints); free_and_null ((char **) &boxrmatbeg); free_and_null ((char **) &boxrmatind); free_and_null ((char **) &hmatbeg); free_and_null ((char **) &hmatind); free_and_null ((char **) &hmatval); free_and_null ((char **) &hSense); /*free_and_null ((char **) &slack); */ return (status); }
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 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); }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int display=0, i=0; long *lpenv=NULL ; CPXENVptr env = NULL; int status ; double value ; char param_name[128] ; int param_code=-1, dblfound=0, strfound=0 ; if (nrhs > 7 || nrhs < 1) { mexErrMsgTxt("Usage: [how] " "= lp_set_param(lpenv, param_name, value, display)"); return; } switch (nrhs) { case 4: if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !(mxGetM(prhs[3])==1 && mxGetN(prhs[3])==1)) { mexErrMsgTxt("4th argument (display) must be " "an integer scalar."); return; } display = *mxGetPr(prhs[3]); } case 3: if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) { if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !(mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1)) { mexErrMsgTxt("3rd argument (value) must be " "an integer scalar."); return; } value = *mxGetPr(prhs[2]); } case 2: if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsChar(prhs[1]) || !(mxGetM(prhs[1])==1) && mxGetN(prhs[1])>=1) { mexErrMsgTxt("2nd argument (param) must be " "a string."); return; } mxGetString(prhs[1], param_name, 128); } case 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]); } } if (nlhs > 1 || nlhs < 1) { mexErrMsgTxt("Usage: [how] " "= lp_set_param(lpenv,param_name,value,disp)"); return; } if (display>2) fprintf(STD_OUT, "argument processing finished\n") ; /* Initialize the CPLEX environment */ env = (CPXENVptr) lpenv[0] ; for (i=0; i<NUM_PARAMS; i++) if (strcmp(param_info[i].name, param_name)==0) param_code=param_info[i].code ; if (display>3) fprintf(STD_OUT, "(param=%s(%i), value=%f) \n", param_name, param_code, value) ; if (param_code==-1) mxErrMsgTxt("illegal parameter name") ; for (i=0; i<NUM_DBLPARAMS; i++) if (param_code==dblParams[i]) dblfound=1 ; for (i=0; i<NUM_STRPARAMS; i++) if (param_code==strParams[i]) strfound=1 ; if (dblfound==1) { if (display>2) fprintf(STD_OUT, "calling CPXsetdblparam\n") ; status = CPXsetdblparam(env, param_code, value); if ( status ) { fprintf (STD_OUT, "CPXsetdblparam failed.\n"); goto TERMINATE; } } else if (strfound==1) { fprintf(STD_OUT, "sorry not implemented\n") ; } else { if (display>2) fprintf(STD_OUT, "calling CPXsetintparam\n") ; status = CPXsetintparam(env, param_code, (int)value); if ( status ) { fprintf (STD_OUT, "CPXsetintparam failed.\n"); goto TERMINATE; } } ; TERMINATE: if (status) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (STD_OUT, "%s", errmsg); if (nlhs >= 1) plhs[0] = mxCreateString(errmsg) ; } else if (nlhs >= 1) plhs[0] = mxCreateString("OK") ; ; return ; }
int main (void) { int status, solstat; CPXENVptr env; CPXLPptr lp; int i; double x[NUMCOLS]; double cpi[NUMCOLS]; double rpi[NUMROWS]; double qpi[NUMQS]; double slack[NUMROWS], qslack[NUMQS]; double kktsum[NUMCOLS]; /* ********************************************************************** * * * * S E T U P P R O B L E M * * * * ********************************************************************** */ /* Create CPLEX environment and enable screen output. */ env = CPXopenCPLEX (&status); if ( status != 0 ) goto TERMINATE; status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) goto TERMINATE; /* Create the problem object and populate it. */ lp = CPXcreateprob (env, &status, "qcpdual"); if ( status != 0 ) goto TERMINATE; status = CPXnewcols (env, lp, NUMCOLS, obj, lb, ub, NULL, cname); if ( status != 0 ) goto TERMINATE; status = CPXaddrows (env, lp, 0, NUMROWS, NUMNZS, rhs, sense, rmatbeg, rmatind, rmatval, NULL, rname); if ( status != 0 ) goto TERMINATE; for (i = 0; i < NUMQS; ++i) { int const linend = (i == NUMQS - 1) ? NUMLINNZ : linbeg[i + 1]; int const quadend = (i == NUMQS - 1) ? NUMQUADNZ : quadbeg[i + 1]; status = CPXaddqconstr (env, lp, linend - linbeg[i], quadend - quadbeg[i], qrhs[i], qsense[i], &linind[linbeg[i]], &linval[linbeg[i]], &quadrow[quadbeg[i]], &quadcol[quadbeg[i]], &quadval[quadbeg[i]], qname[i]); if ( status != 0 ) goto TERMINATE; } /* ********************************************************************** * * * * O P T I M I Z E P R O B L E M * * * * ********************************************************************** */ status = CPXsetdblparam (env, CPXPARAM_Barrier_QCPConvergeTol, 1e-10); if ( status != 0 ) goto TERMINATE; /* Solve the problem. */ status = CPXbaropt (env, lp); if ( status != 0 ) goto TERMINATE; solstat = CPXgetstat (env, lp); if ( solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "No optimal solution found!\n"); goto TERMINATE; } /* ********************************************************************** * * * * Q U E R Y S O L U T I O N * * * * ********************************************************************** */ /* Optimal solution and slacks for linear and quadratic constraints. */ status = CPXgetx (env, lp, x, 0, NUMCOLS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetslack (env, lp, slack, 0, NUMROWS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetqconstrslack (env, lp, qslack, 0, NUMQS - 1); if ( status != 0 ) goto TERMINATE; /* Dual multipliers for linear constraints and bound constraints. */ status = CPXgetdj (env, lp, cpi, 0, NUMCOLS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetpi (env, lp, rpi, 0, NUMROWS - 1); if ( status != 0 ) goto TERMINATE; status = getqconstrmultipliers (env, lp, x, qpi, ZEROTOL); if ( status != 0 ) goto TERMINATE; /* ********************************************************************** * * * * C H E C K K K T C O N D I T I O N S * * * * Here we verify that the optimal solution computed by CPLEX (and * * the qpi[] values computed above) satisfy the KKT conditions. * * * * ********************************************************************** */ /* Primal feasibility: This example is about duals so we skip this test. */ /* Dual feasibility: We must verify * - for <= constraints (linear or quadratic) the dual * multiplier is non-positive. * - for >= constraints (linear or quadratic) the dual * multiplier is non-negative. */ for (i = 0; i < NUMROWS; ++i) { switch (sense[i]) { case 'E': /* nothing */ break; case 'R': /* nothing */ break; case 'L': if ( rpi[i] > ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for <= row %d: %f\n", i, rpi[i]); status = -1; goto TERMINATE; } break; case 'G': if ( rpi[i] < -ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for >= row %d: %f\n", i, rpi[i]); status = -1; goto TERMINATE; } break; } } for (i = 0; i < NUMQS; ++i) { switch (qsense[i]) { case 'E': /* nothing */ break; case 'L': if ( qpi[i] > ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for <= quad %d: %f\n", i, qpi[i]); status = -1; goto TERMINATE; } break; case 'G': if ( qpi[i] < -ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for >= quad %d: %f\n", i, qpi[i]); status = -1; goto TERMINATE; } break; } } /* Complementary slackness. * For any constraint the product of primal slack and dual multiplier * must be 0. */ for (i = 0; i < NUMROWS; ++i) { if ( sense[i] != 'E' && fabs (slack[i] * rpi[i]) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for row %d: %f\n", i, fabs (slack[i] * rpi[i])); status = -1; goto TERMINATE; } } for (i = 0; i < NUMQS; ++i) { if ( qsense[i] != 'E' && fabs (qslack[i] * qpi[i]) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for quad %d: %f\n", i, fabs (qslack[i] * qpi[i])); status = -1; goto TERMINATE; } } for (i = 0; i < NUMCOLS; ++i) { if ( ub[i] < CPX_INFBOUND ) { double const slk = ub[i] - x[i]; double const dual = cpi[i] < -ZEROTOL ? cpi[i] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for ub %d: %f\n", i, fabs (slk * dual)); status = -1; goto TERMINATE; } } if ( lb[i] > -CPX_INFBOUND ) { double const slk = x[i] - lb[i]; double const dual = cpi[i] > ZEROTOL ? cpi[i] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { printf ("lb=%f, x=%f, cpi=%f\n", lb[i], x[i], cpi[i]); fprintf (stderr, "Complementary slackness test failed for lb %d: %f\n", i, fabs (slk * dual)); status = -1; goto TERMINATE; } } } /* Stationarity. * The difference between objective function and gradient at optimal * solution multiplied by dual multipliers must be 0, i.e., for the * optimal solution x * 0 == c * - sum(r in rows) r'(x)*rpi[r] * - sum(q in quads) q'(x)*qpi[q] * - sum(c in cols) b'(x)*cpi[c] * where r' and q' are the derivatives of a row or quadratic constraint, * x is the optimal solution and rpi[r] and qpi[q] are the dual * multipliers for row r and quadratic constraint q. * b' is the derivative of a bound constraint and cpi[c] the dual bound * multiplier for column c. */ /* Objective function. */ for (i = 0; i < NUMCOLS; ++i) kktsum[i] = obj[i]; /* Linear constraints. * The derivative of a linear constraint ax - b (<)= 0 is just a. */ for (i = 0; i < NUMROWS; ++i) { int const end = (i == NUMROWS - 1) ? NUMNZS : rmatbeg[i + 1]; int k; for (k = rmatbeg[i]; k < end; ++k) kktsum[rmatind[k]] -= rpi[i] * rmatval[k]; } /* Quadratic constraints. * The derivative of a constraint xQx + ax - b <= 0 is * Qx + Q'x + a. */ for (i = 0; i < NUMQS; ++i) { int j; int k; for (j = linbeg[i]; j < linbeg[i] + linnzcnt[i]; ++j) kktsum[linind[j]] -= qpi[i] * linval[j]; for (k = quadbeg[i]; k < quadbeg[i] + quadnzcnt[i]; ++k) { kktsum[quadrow[k]] -= qpi[i] * x[quadcol[k]] * quadval[k]; kktsum[quadcol[k]] -= qpi[i] * x[quadrow[k]] * quadval[k]; } } /* Bounds. * The derivative for lower bounds is -1 and that for upper bounds * is 1. * CPLEX already returns dj with the appropriate sign so there is * no need to distinguish between different bound types here. */ for (i = 0; i < NUMCOLS; ++i) { kktsum[i] -= cpi[i]; } for (i = 0; i < NUMCOLS; ++i) { if ( fabs (kktsum[i]) > ZEROTOL ) { fprintf (stderr, "Stationarity test failed at index %d: %f\n", i, kktsum[i]); status = -1; goto TERMINATE; } } /* KKT conditions satisfied. Dump out the optimal solutions and * the dual values. */ printf ("Optimal solution satisfies KKT conditions.\n"); printf (" x[] ="); for (i = 0; i < NUMCOLS; ++i) printf (" %7.3f", x[i]); printf ("\n"); printf ("cpi[] ="); for (i = 0; i < NUMCOLS; ++i) printf (" %7.3f", cpi[i]); printf ("\n"); printf ("rpi[] ="); for (i = 0; i < NUMROWS; ++i) printf (" %7.3f", rpi[i]); printf ("\n"); printf ("qpi[] ="); for (i = 0; i < NUMQS; ++i) printf (" %7.3f", qpi[i]); printf ("\n"); TERMINATE: /* ********************************************************************** * * * * C L E A N U P * * * * ********************************************************************** */ status = CPXfreeprob (env, &lp); if ( status != 0 ) { fprintf (stderr, "WARNING: Failed to free problem: %d\n", status); } status = CPXcloseCPLEX (&env); if ( status != 0 ) { fprintf (stderr, "WARNING: Failed to close CPLEX: %d\n", status); } return status; }
int main (void) { /* Declare variables and arrays where we will store the optimization results including the status, objective value, and variable values. */ int solstat; double objval; double x[2*NUMEDGES]; /* One flow variable and one fixed charge indicator for each edge */ CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int j; /* 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. */ lp = CPXcreateprob (env, &status, "fixnet"); /* 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; } /* Build the fixed-charge network flow model using indicator constraints. */ status = buildnetwork (env, lp); if ( status ) { fprintf (stderr, "Failed to build network.\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); /* Write solution status and objective to the screen. */ printf ("\nSolution status = %d\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "No MIP objective value available. Exiting...\n"); goto TERMINATE; } printf ("Solution value = %f\n", objval); printf ("Solution vector:\n"); dumpx (env, lp); status = CPXgetx (env, lp, x, 0, 2*NUMEDGES-1); if ( status ) { fprintf (stderr, "Failed to get optimal integer x.\n"); goto TERMINATE; } /* Make sure flow satisfies fixed-charge constraints */ for (j = 0; j < NUMEDGES; j++) { if ( x[j] > 0.0001 && x[NUMEDGES+j] < 0.9999 ) { printf ("WARNING : Edge from %d to %d has non-zero flow %.3f\n", orig[j], dest[j], x[j]); printf (" : fixed-charge indicator has value %.6f.\n", x[NUMEDGES+j]); } } printf("\n"); /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "fixnet.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } /* Free problem */ status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); 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 */
/* This routine initializes the cplex enviorement, sets screen as an output for cplex errors and notifications, and sets parameters for cplex. It calls for a mixed integer program solution and frees the environment. To Do: Declare the parameters for the problem and fill them accordingly. After creating the program thus, copy it into cplex. Define any integer or binary variables as needed, and change their type before the call to CPXmipopt to solve problem. Use CPXwriteprob to output the problem in lp format, in the name of cluster_editing.lp. Read solution (both objective function value and variables assignment). Communicate to pass the problem and the solution between the modules in the best way you see. */ int cluster() { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value and variable values. */ CPXENVptr p_env = NULL; CPXLPptr p_lp = NULL; int status; /* Initialize the CPLEX environment */ p_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 CPX_PARAM_SCRIND indicator is set to CPX_ON. */ if ( p_env == NULL ) { char errmsg[1024]; fprintf (stderr, "Error: Could not open CPLEX environment.\n"); CPXgeterrorstring (p_env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (p_env, CPX_PARAM_SCRIND, CPX_ON); if ( status ) { fprintf (stderr, "Error: Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ p_lp = CPXcreateprob (p_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. The setting of the parameter CPX_PARAM_SCRIND causes the error message to appear on stdout. */ if ( p_lp == NULL ) { fprintf (stderr, "Error: Failed to create problem.\n"); goto TERMINATE; } /* Use CPXcopylp to transfer the ILP part of the problem data into the cplex pointer lp */ CPXcopylp (p_env, p_lp, numcols, numrows, objsen, obj, rhs, sense, matbeg, matcnt, matind, matval, lb, ub, 0); CPXchgctype(p_env, p_lp, cnt, indices, ctype); /* Optimize the problem. */ status = CPXmipopt (p_env, p_lp); if ( status ) { fprintf (stderr, "Error: Failed to optimize problem.\n"); goto TERMINATE; } status = CPXsolution(p_env, p_lp, &solstat, &objval, x, NULL, NULL, NULL); if ( status ) { fprintf (stderr, "Error: Failed to get solution variables.\n"); goto TERMINATE; } /* Write a copy of the problem to a file. Please put into probname the following string: Output Directory + "clustering_solution.lp" to create clustering_solution.lp in your output directory */ status = CPXwriteprob (p_env, p_lp, probname, NULL); if ( status ) { fprintf (stderr, "Error: Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( p_lp != NULL ) { status = CPXfreeprob (p_env, &p_lp); if ( status ) { fprintf (stderr, "Error: CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( p_env != NULL ) { status = CPXcloseCPLEX (&p_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 CPX_PARAM_SCRIND indicator is set to CPX_ON. */ if ( status ) { char errmsg[1024]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (p_env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); }
long GenModelCplex::Init(string name) { //strParam.count("log_file") //dblParam.count("relative_mip_gap_tolerance") //dblParam.count("absolute_mip_gap_tolerance") //dblParam.count("time_limit") //dblParam.count("bounds_feasibility_tolerance") //dblParam.count("optimality_tolerance") //dblParam.count("markowitz_tolerance")) //longParam.count("threads") //longParam.count("cutpass") //longParam.count("pumplevel") //longParam.count("mipemphasis") //longParam.count("probinglevel") //longParam.count("max_iteration_limit"); //boolParam.count("preprocoff") : turn on/off preprocessing //boolParam.count("datacheckoff") //boolParam.count("screen_output") //boolParam.count("usecutcb") if(solverdata == NULL) solverdata = new CplexData(); else { static_cast<CplexData*>(solverdata)->Delete(); static_cast<CplexData*>(solverdata)->Reset(); } CplexData* d = static_cast<CplexData*>(solverdata); int status = 0; d->env = CPXopenCPLEX (&status); // If an error occurs if ( d->env == NULL ) return ThrowError(getcplexerror(d->env, status)+string(". ")+string("Could not open CPLEX environment")); hassolution = false; // Log file if(strParam.count("log_file") > 0) { d->cpxfileptr = CPXfopen(strParam["log_file"].c_str(), "w"); status = CPXsetlogfile(d->env, d->cpxfileptr); if ( status ) return ThrowError(getcplexerror(d->env, status)+string(". ")+string("Failure to set the log file")); } // General settings boolParam["log_output_stdout"] = true; SetParam("log_output_stdout", CPX_PARAM_SCRIND, "bool", "Failure to turn on/off log output to stdout"); SetParam("log_level", CPX_PARAM_MIPDISPLAY, "long", "Failure to set log level"); SetParam("use_data_checking", CPX_PARAM_DATACHECK, "bool", "Failure to turn on/off data checking"); SetParam("nb_threads", CPX_PARAM_THREADS, "long", "Failure to set the number of threads"); if(boolParam.count("use_preprocessor") > 0 && !boolParam["use_preprocessor"]) { SetDirectParam(CPX_PARAM_AGGFILL, long2param(0), "long", "Failure to use preprocessor (CPX_PARAM_AGGFILL)"); SetDirectParam(CPX_PARAM_PREPASS, long2param(0), "long", "Failure to use preprocessor (CPX_PARAM_PREPASS)"); SetDirectParam(CPX_PARAM_AGGIND, long2param(CPX_OFF), "long", "Failure to use preprocessor (CPX_PARAM_AGGIND)"); SetDirectParam(CPX_PARAM_DEPIND, long2param(0), "long", "Failure to use preprocessor (CPX_PARAM_DEPIND)"); SetDirectParam(CPX_PARAM_PRELINEAR, long2param(0), "long", "Failure to use preprocessor (CPX_PARAM_PRELINEAR)"); SetDirectParam(CPX_PARAM_PREDUAL, long2param(-1), "long", "Failure to use preprocessor (CPX_PARAM_PREDUAL)"); SetDirectParam(CPX_PARAM_REDUCE, long2param(0), "long", "Failure to use preprocessor (CPX_PARAM_REDUCE)"); SetDirectParam(CPX_PARAM_PREIND, long2param(CPX_OFF), "long", "Failure to use preprocessor (CPX_PARAM_PREIND)"); } // MIP settings SetParam("nb_cut_pass", CPX_PARAM_CUTPASS, "long", "Failure to set the number of cut pass"); SetParam("feasibility_pump_level", CPX_PARAM_FPHEUR, "long", "Failure to set the feasibility pump level"); SetParam("probing_level", CPX_PARAM_PROBE, "long", "Failure to set the probing level"); SetParam("mip_emphasis", CPX_PARAM_MIPEMPHASIS, "long", "Failure to set the MIP emphasis"); SetParam("mip_search", CPX_PARAM_MIPSEARCH, "long", "Failure to set the MIP search strategy"); SetParam("starting_algo", CPX_PARAM_STARTALG, "long", "Failure to set the starting algo parameter"); SetParam("node_algo", CPX_PARAM_SUBALG, "long", "Failure to set the node algo parameter"); if(boolParam.count("use_cut_callback") > 0 && boolParam["use_cut_callback"]) { SetDirectParam(CPX_PARAM_PRELINEAR, long2param(0), "long", "Failure to use cut callback (CPX_PARAM_PRELINEAR)"); SetDirectParam(CPX_PARAM_MIPCBREDLP, long2param(0), "long", "Failure to use cut callback (CPX_PARAM_MIPCBREDLP)"); } // Tolerance and limits SetParam("time_limit", CPX_PARAM_TILIM, "dbl", "Failure to set time limit"); SetParam("max_iteration_limit", CPX_PARAM_ITLIM, "long", "Failure to set the maximal number of simplex iterations"); SetParam("bounds_feasibility_tolerance", CPX_PARAM_EPRHS, "dbl", "Failure to set bounds feasibility tolerance"); SetParam("optimality_tolerance", CPX_PARAM_EPOPT, "dbl", "Failure to set optimality tolerance"); SetParam("markowitz_tolerance", CPX_PARAM_EPMRK, "dbl", "Failure to set Markowitz tolerance"); SetParam("absolute_mip_gap_tolerance", CPX_PARAM_EPAGAP, "dbl", "Failure to set absolute gap tolerance"); SetParam("relative_mip_gap_tolerance", CPX_PARAM_EPGAP, "dbl", "Failure to set relative gap tolerance"); if(boolParam.count("maximize") > 0 && boolParam["maximize"]) SetParam("lp_objective_limit", CPX_PARAM_OBJULIM, "dbl", "Failure to set lp objective limit"); else SetParam("lp_objective_limit", CPX_PARAM_OBJLLIM, "dbl", "Failure to set lp objective limit"); // MIP Emphasis if(longParam.count("mipemphasis")) { status = CPXsetintparam (d->env, CPX_PARAM_MIPEMPHASIS, longParam["mipemphasis"]); } // Probing level if(longParam.count("probinglevel")) { status = CPXsetintparam (d->env, CPX_PARAM_PROBE, longParam["probinglevel"]); } if ( status ) { fprintf (stderr, "Failure to set cut callback parameters, error %d->\n", status); return 1; } binit = true; if(dblParam.count("feastol")) status = CPXsetdblparam (d->env, CPX_PARAM_EPRHS, dblParam["feastol"]); if ( status ) { fprintf (stderr, "Failure to change feasibility tolerance, error %d->\n", status); return 1; } if(dblParam.count("opttol")) status = CPXsetdblparam (d->env, CPX_PARAM_EPOPT, dblParam["opttol"]); if ( status ) { fprintf (stderr, "Failure to change optimality tolerance, error %d->\n", status); return 1; } if(dblParam.count("marktol")) status = CPXsetdblparam (d->env, CPX_PARAM_EPMRK, dblParam["marktol"]); if ( status ) { fprintf (stderr, "Failure to change Markowitz tolerance, error %d->\n", status); return 1; } if(longParam.count("threads")) { printf("Threads: %ld\n", longParam["threads"]); status = CPXsetintparam (d->env, CPX_PARAM_THREADS, longParam["threads"]); if ( status ) { fprintf (stderr, "Failure to change the number of threads, error %d->\n", status); return 1; } } // Turn off preprocessing if(boolParam.count("preprocoff") > 0 && boolParam["preprocoff"]) { status = CPXsetintparam (d->env, CPX_PARAM_AGGFILL, 0); status = status && CPXsetintparam (d->env, CPX_PARAM_PREPASS, 0); status = status && CPXsetintparam (d->env, CPX_PARAM_AGGIND, CPX_OFF); status = status && CPXsetintparam (d->env, CPX_PARAM_DEPIND, 0); status = status && CPXsetintparam (d->env, CPX_PARAM_PRELINEAR, 0); status = status && CPXsetintparam (d->env, CPX_PARAM_PREDUAL, -1); status = status && CPXsetintparam (d->env, CPX_PARAM_REDUCE, 0); status = status && CPXsetintparam (d->env, CPX_PARAM_PREIND, CPX_OFF); } if ( status ) { fprintf (stderr, "Failure to turn off preprocessing, error %d->\n", status); return 1; } // Turn on data checking if(boolParam.count("datacheckoff") > 0 && boolParam["datacheckoff"]) status = CPXsetintparam (d->env, CPX_PARAM_DATACHECK, CPX_OFF); else status = CPXsetintparam (d->env, CPX_PARAM_DATACHECK, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on data checking, error %d->\n", status); return 1; } // Sets a relative tolerance on the gap between the best integer objective and the objective of the best node remaining (between 0.0 and 1.0) if(dblParam.count("epgap")) { //printf("setting epgap\n"); status = CPXsetdblparam (d->env, CPX_PARAM_EPGAP, dblParam["epgap"]); if ( status ) { fprintf (stderr, "Failure to set relative gap tolerance, error %d->\n", status); return 1; } } // Create the problem d->lp = CPXcreateprob (d->env, &status, name.c_str()); if ( d->lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); return 1; } fflush(stdout); return 0; }
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 (void) { CPXENVptr env; CPXLPptr lp = NULL; int *cone = NULL; int status; CPXCHANNELptr resc, warnc, errc, logc; int retval = -1; /* Initialize CPLEX and get a reference to the output channels. * If any of this fails immediately terminate the program. */ env = CPXopenCPLEX (&status); if ( env == NULL || status != 0 ) abort (); status = CPXgetchannels (env, &resc, &warnc, &errc, &logc); if ( status != 0 ) abort (); /* CPLEX is fully setup. Enable output. */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) goto TERMINATE; /* Create model. */ lp = CPXcreateprob (env, &status, "xsocpex1"); if ( lp == NULL || status != 0 ) goto TERMINATE; if ( !createmodel (env, lp, &cone) ) goto TERMINATE; /* Solve the problem to optimality. */ CPXmsg (logc, "Optimizing ...\n"); status = CPXsetdblparam (env, CPXPARAM_Barrier_QCPConvergeTol, CONVTOL); if ( status != 0 ) goto TERMINATE; if ( (status = CPXhybbaropt (env, lp, CPX_ALG_NONE)) != 0 ) goto TERMINATE; if ( CPXgetstat (env, lp) != CPX_STAT_OPTIMAL ) { CPXmsg (errc, "Cannot test KKT conditions on non-optimal solution.\n"); goto TERMINATE; } /* Now test KKT conditions on the result. */ if ( !checkkkt (env, lp, cone, TESTTOL) ) { CPXmsg (logc, "Testing of KKT conditions failed.\n"); CPXmsg (errc, "Testing of KKT conditions failed.\n"); goto TERMINATE; } CPXmsg (resc, "KKT conditions are satisfied.\n"); retval = 0; TERMINATE: free (cone); if ( lp != NULL ) CPXfreeprob (env, &lp); CPXcloseCPLEX (&env); return retval; }
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; char errmsg[CPXMESSAGEBUFSIZE]; CPXCHANNELptr cpxerror = NULL; CPXCHANNELptr cpxwarning = NULL; CPXCHANNELptr cpxresults = NULL; CPXCHANNELptr ourchannel = NULL; char errorlabel[] = "cpxerror"; char warnlabel[] = "cpxwarning"; char reslabel[] = "cpxresults"; char ourlabel[] = "Our Channel"; char ourmessage[] = "Our Message"; CPXFILEptr fpout = NULL; /* 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. */ /* Since the message handler is yet to be set up, we'll call our messaging function directly to print out any errors */ if ( env == NULL ) { ourmsgfunc (ourmessage, "Could not open CPLEX environment.\n"); goto TERMINATE; } /* Now get the standard channels. If an error, just call our message function directly. */ status = CPXgetchannels (env, &cpxresults, &cpxwarning, &cpxerror, NULL); if ( status ) { ourmsgfunc (ourmessage, "Could not get standard channels.\n"); CPXgeterrorstring (env, status, errmsg); ourmsgfunc (ourmessage, errmsg); goto TERMINATE; } /* Now set up the error channel first. The label will be "cpxerror" */ status = CPXaddfuncdest (env, cpxerror, errorlabel, ourmsgfunc); if ( status ) { ourmsgfunc (ourmessage, "Could not set up error message handler.\n"); CPXgeterrorstring (env, status, errmsg); ourmsgfunc (ourmessage, errmsg); } /* Now that we have the error message handler set up, all CPLEX generated errors will go through ourmsgfunc. So we don't have to use CPXgeterrorstring to determine the text of the message. We can also use CPXmsg to do any other printing. */ status = CPXaddfuncdest (env, cpxwarning, warnlabel, ourmsgfunc); if ( status ) { CPXmsg (cpxerror, "Failed to set up handler for cpxwarning.\n"); goto TERMINATE; } status = CPXaddfuncdest (env, cpxresults, reslabel, ourmsgfunc); if ( status ) { CPXmsg (cpxerror, "Failed to set up handler for cpxresults.\n"); goto TERMINATE; } /* Now turn on the iteration display. */ status = CPXsetintparam (env, CPXPARAM_Simplex_Display, 2); if ( status ) { CPXmsg (cpxerror, "Failed to turn on simplex display level.\n"); 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 ) { CPXmsg (cpxerror, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. */ status = populatebycolumn (env, lp); if ( status ) { CPXmsg (cpxerror, "Failed to populate problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { CPXmsg (cpxerror, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { CPXmsg (cpxerror, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. We will also write it to a file as well by setting up a file destination and a function destination. */ ourchannel = CPXaddchannel (env); if ( ourchannel == NULL ) { CPXmsg (cpxerror, "Failed to set up our private channel.\n"); goto TERMINATE; } fpout = CPXfopen ("lpex5.msg", "w"); if ( fpout == NULL ) { CPXmsg (cpxerror, "Failed to open lpex5.msg file for output.\n"); goto TERMINATE; } status = CPXaddfpdest (env, ourchannel, fpout); if ( status ) { CPXmsg (cpxerror, "Failed to set up output file destination.\n"); goto TERMINATE; } status = CPXaddfuncdest (env, ourchannel, ourlabel, ourmsgfunc); if ( status ) { CPXmsg (cpxerror, "Failed to set up our output function.\n"); goto TERMINATE; } /* Now any message to channel ourchannel will go into the file and into the file opened above. */ CPXmsg (ourchannel, "\nSolution status = %d\n", solstat); CPXmsg (ourchannel, "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++) { CPXmsg (ourchannel, "Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { CPXmsg (ourchannel, "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, "lpex5.lp", NULL); if ( status ) { CPXmsg (cpxerror, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* First check if ourchannel is open */ if ( ourchannel != NULL ) { int chanstat; chanstat = CPXdelfuncdest (env, ourchannel, ourlabel, ourmsgfunc); if ( chanstat ) { strcpy (errmsg, "CPXdelfuncdest failed.\n"); ourmsgfunc (ourmessage, errmsg); if (!status) status = chanstat; } if ( fpout != NULL ) { chanstat = CPXdelfpdest (env, ourchannel, fpout); if ( chanstat ) { strcpy (errmsg, "CPXdelfpdest failed.\n"); ourmsgfunc (ourmessage, errmsg); if (!status) status = chanstat; } CPXfclose (fpout); } chanstat = CPXdelchannel (env, &ourchannel); if ( chanstat ) { strcpy (errmsg, "CPXdelchannel failed.\n"); ourmsgfunc (ourmessage, errmsg); if (!status) status = chanstat; } } /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { strcpy (errmsg, "CPXfreeprob failed.\n"); ourmsgfunc (ourmessage, errmsg); } } /* Now delete our function destinations from the 3 CPLEX channels. */ if ( cpxresults != NULL ) { int chanstat; chanstat = CPXdelfuncdest (env, cpxresults, reslabel, ourmsgfunc); if ( chanstat && !status ) { status = chanstat; strcpy (errmsg, "Failed to delete cpxresults function.\n"); ourmsgfunc (ourmessage, errmsg); } } if ( cpxwarning != NULL ) { int chanstat; chanstat = CPXdelfuncdest (env, cpxwarning, warnlabel, ourmsgfunc); if ( chanstat && !status ) { status = chanstat; strcpy (errmsg, "Failed to delete cpxwarning function.\n"); ourmsgfunc (ourmessage, errmsg); } } if ( cpxerror != NULL ) { int chanstat; chanstat = CPXdelfuncdest (env, cpxerror, errorlabel, ourmsgfunc); if ( chanstat && !status ) { status = chanstat; strcpy (errmsg, "Failed to delete cpxerror function.\n"); ourmsgfunc (ourmessage, errmsg); } } /* 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 ) { strcpy (errmsg, "Could not close CPLEX environment.\n"); ourmsgfunc (ourmessage, errmsg); CPXgeterrorstring (env, status, errmsg); ourmsgfunc (ourmessage, errmsg); } } return (status); } /* END main */