int CPLEXPrintFromSolver() { int Status = 0; if (CPLEXenv == NULL) { FErrorFile() << "Cannot print problem to file because CPLEX environment is not open." << endl; FlushErrorFile(); return FAIL; } if (CPLEXModel == NULL) { FErrorFile() << "Cannot print problem to file because no CPLEX model exists." << endl; FlushErrorFile(); return FAIL; } string Filename = CheckFilename(FOutputFilepath()+GetParameter("LP filename")); Status = CPXwriteprob (CPLEXenv, CPLEXModel,Filename.data(), "LP"); if (Status) { FErrorFile() << "Cannot print problem to file for unknown reason." << endl; FlushErrorFile(); return FAIL; } return SUCCESS; }
long GenModelCplex::WriteProblemToLpFile(string filename) { if(!bcreated) throw string("WriteProblemToLpFile() not available : Problem not created yet;"); CplexData* d = static_cast<CplexData*>(solverdata); CPXwriteprob(d->env, d->lp, filename.c_str(), "LP"); return 0; }
void SSCplex::AddExtraConstr( int NXC , int *IBeg , int *Indx , double *Vals , double *XLr , double *XUr ) { #if DEBUG status = CPXwriteprob(env, lp, "SPIC.txt", "LP"); if ( status ) stop("Failed to write LP to disk.", status); #endif } // end( SSCplex::AddExtraConstr )
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; int *qmatbeg = NULL; int *qmatcnt = NULL; int *qmatind = NULL; double *qmatval = NULL; /* Declare pointers for the variables that will contain the data for the constraint that cuts off certain local optima. */ int numrows_extra; int numnnz_extra; double *rhs_extra = NULL; char *sense_extra = NULL; int *rmatbeg = NULL; int *rmatind = NULL; double *rmatval = NULL; int rowind[1]; /* 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; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; /* 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, &qmatbeg, &qmatcnt, &qmatind, &qmatval, &numrows_extra, &numnnz_extra, &rhs_extra, &sense_extra, &rmatbeg, &rmatind, &rmatval); 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 problem.\n"); goto TERMINATE; } /* Now copy the LP part of 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; } status = CPXcopyquad (env, lp, qmatbeg, qmatcnt, qmatind, qmatval); if ( status ) { fprintf (stderr, "Failed to copy quadratic matrix.\n"); goto TERMINATE; } /* When a non-convex objective function is present, CPLEX will return error CPXERR_Q_NOT_POS_DEF unless the parameter CPXPARAM_OptimalityTarget is set to accept first-order optimal solutions. */ status = CPXsetintparam (env, CPXPARAM_OptimalityTarget, CPX_OPTIMALITYTARGET_FIRSTORDER); if ( status ) goto TERMINATE; /* Optimize the problem and obtain solution. */ status = optimize_and_report(env, lp, &solstat, &objval); if ( status ) goto TERMINATE; /* Add a constraint to cut off the solution at (-1, 1) */ status = CPXaddrows (env, lp, 0, numrows_extra, numnnz_extra, rhs_extra, sense_extra, rmatbeg, rmatind, rmatval, NULL, NULL); if ( status ) goto TERMINATE; status = optimize_and_report(env, lp, &solstat, &objval); if ( status ) goto TERMINATE; /* Reverse the sense of the new constraint to cut off the solution at (1, 1) */ rowind[0] = CPXgetnumrows (env, lp) - 1; status = CPXchgsense (env, lp, 1, rowind, "L"); if ( status ) goto TERMINATE; status = optimize_and_report(env, lp, &solstat, &objval); if ( status ) goto TERMINATE; /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "indefqpex1.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 **) &qmatbeg); free_and_null ((char **) &qmatcnt); free_and_null ((char **) &qmatind); free_and_null ((char **) &qmatval); free_and_null ((char **) &rhs_extra); free_and_null ((char **) &sense_extra); free_and_null ((char **) &rmatbeg); free_and_null ((char **) &rmatind); free_and_null ((char **) &rmatval); 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, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double *x = NULL; double *pi = NULL; double *slack = NULL; double *dj = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int i, j; int cur_numrows, cur_numcols; /* Check the command line arguments */ if (( argc != 2 ) || ( argv[1][0] != '-' ) || ( strchr ("rcn", argv[1][1]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn on data checking */ status = CPXsetintparam (env, CPXPARAM_Read_DataCheck, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on data checking, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ lp = CPXcreateprob (env, &status, "lpex1"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. For building large problems, consider setting the row, column and nonzero growth parameters before performing this task. */ switch (argv[1][1]) { case 'r': status = populatebyrow (env, lp); break; case 'c': status = populatebycolumn (env, lp); break; case 'n': status = populatebynonzero (env, lp); break; } if ( status ) { fprintf (stderr, "Failed to populate problem.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof(double)); slack = (double *) malloc (cur_numrows * sizeof(double)); dj = (double *) malloc (cur_numcols * sizeof(double)); pi = (double *) malloc (cur_numrows * sizeof(double)); if ( x == NULL || slack == NULL || dj == NULL || pi == NULL ) { status = CPXERR_NO_MEMORY; fprintf (stderr, "Could not allocate memory for solution.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the solution */ free_and_null ((char **) &x); free_and_null ((char **) &slack); free_and_null ((char **) &dj); free_and_null ((char **) &pi); /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int 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) { int status = 0; int nfoods; int nnutr; double *cost = NULL; double *lb = NULL; double *ub = NULL; double *nutrmin = NULL; double *nutrmax = NULL; double **nutrper = NULL; double *x = NULL; double objval; int solstat; /* 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. */ CPXENVptr env = NULL; CPXLPptr lp = NULL; int i, j; /* Check the command line arguments */ if (( argc != 3 ) || ( argv[1][0] != '-' ) || ( strchr ("rc", argv[1][1]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } status = readdata(argv[2], &nfoods, &cost, &lb, &ub, &nnutr, &nutrmin, &nutrmax, &nutrper); if ( status ) goto TERMINATE; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn on data checking */ status = CPXsetintparam (env, CPXPARAM_Read_DataCheck, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on data checking, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ lp = CPXcreateprob (env, &status, "diet"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. For building large problems, consider setting the row, column and nonzero growth parameters before performing this task. */ switch (argv[1][1]) { case 'r': status = populatebyrow (env, lp, nfoods, cost, lb, ub, nnutr, nutrmin, nutrmax, nutrper); break; case 'c': status = populatebycolumn (env, lp, nfoods, cost, lb, ub, nnutr, nutrmin, nutrmax, nutrper); break; } if ( status ) { fprintf (stderr, "Failed to populate problem.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } x = (double *) malloc (nfoods * sizeof(double)); if ( x == NULL ) { status = CPXERR_NO_MEMORY; fprintf (stderr, "Could not allocate memory for solution.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, NULL, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); for (j = 0; j < nfoods; j++) { printf ("Food %d: Buy = %10f\n", j, x[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "diet.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 > 0 ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } if ( nutrper != NULL ) { for (i = 0; i < nnutr; ++i) { free_and_null ((char **) &(nutrper[i])); } } free_and_null ((char **) &nutrper); free_and_null ((char **) &cost); free_and_null ((char **) &cost); free_and_null ((char **) &lb); free_and_null ((char **) &ub); free_and_null ((char **) &nutrmin); free_and_null ((char **) &nutrmax); free_and_null ((char **) &x); return (status); } /* END main */
//========================================================================== // This function solves the expected value problem int DDSIP_ExpValProb (void) { int status, j, mipstatus, nodes_1st = -1; int wall_hrs, wall_mins,cpu_hrs, cpu_mins; double objval, bobjval, time_start, time_end, wall_secs, cpu_secs, gap; char fname[DDSIP_ln_fname]; double *mipx = (double *) DDSIP_Alloc (sizeof (double), (DDSIP_bb->firstvar + DDSIP_bb->secvar), "mipx(ExpValProb)"); printf ("Solving expected value problem\n"); if (DDSIP_param->outlev) fprintf (DDSIP_bb->moreoutfile, "Solving expected value problem...\n"); status = DDSIP_ChgProb (-1, 0); if (status) { fprintf (stderr, "ERROR: Failed to change problem \n"); goto TERMINATE; } if (DDSIP_param->files > 1) { sprintf (fname, "%s/ev%s", DDSIP_outdir, DDSIP_param->coretype); status = CPXwriteprob (DDSIP_env, DDSIP_lp, fname, NULL); if (status) { fprintf (stderr, "ERROR: Failed to write problem\n"); goto TERMINATE; } } // New cplex parameters if (DDSIP_param->cpxnoeev) { status = DDSIP_SetCpxPara (DDSIP_param->cpxnoeev, DDSIP_param->cpxeevisdbl, DDSIP_param->cpxeevwhich, DDSIP_param->cpxeevwhat); if (status) { fprintf (stderr, "ERROR: Failed to set CPLEX parameters (ExpValProb) \n"); goto TERMINATE; } } time_start = DDSIP_GetCpuTime (); mipstatus = CPXmipopt (DDSIP_env, DDSIP_lp); // Reset cplex parameters if (DDSIP_param->cpxnoeev) { status = DDSIP_SetCpxPara (DDSIP_param->cpxno, DDSIP_param->cpxisdbl, DDSIP_param->cpxwhich, DDSIP_param->cpxwhat); if (status) { fprintf (stderr, "ERROR: Failed to reset CPLEX parameters (ExpValProb) \n"); goto TERMINATE; } } if (DDSIP_Error (mipstatus)) { fprintf (stderr, "ERROR: Failed to optimize EXP\n"); status = mipstatus; goto TERMINATE; } // Error ? (blatant infeasible, scenario problem limit) if (DDSIP_Infeasible (mipstatus)) { status = 1; goto TERMINATE; } // No solution found ? (integer infeasible, some limit (node, time)) mipstatus = CPXgetstat (DDSIP_env, DDSIP_lp); if (DDSIP_NoSolution (mipstatus)) { status = 1; goto TERMINATE; } status = CPXgetx (DDSIP_env, DDSIP_lp, mipx, 0, DDSIP_bb->firstvar + DDSIP_bb->secvar - 1); if (status) { fprintf (stderr, "ERROR: Failed to get solution \n"); goto TERMINATE; } // output of result if (DDSIP_param->outlev) { status = CPXgetobjval (DDSIP_env, DDSIP_lp, &objval); if (status) { fprintf (stderr, "ERROR*: Failed to get best objective value \n"); fprintf (DDSIP_outfile, "ERROR*: Failed to get best objective value \n"); if (DDSIP_param->outlev) fprintf (DDSIP_bb->moreoutfile, "ERROR*: Failed to get best objective value \n"); goto TERMINATE; } if (mipstatus == CPXMIP_OPTIMAL) { bobjval = objval; } else { status = CPXgetbestobjval (DDSIP_env, DDSIP_lp, &bobjval); if (status) { fprintf (stderr, "ERROR: Failed to get value of best remaining node\n"); fprintf (DDSIP_outfile, "ERROR: Failed to get value of best remaining node\n"); if (DDSIP_param->outlev) fprintf (DDSIP_bb->moreoutfile, "ERROR: Failed to get value of best remaining node\n"); goto TERMINATE; } } gap = 100.0*(objval-bobjval)/(fabs(objval)+1e-4); nodes_1st = CPXgetnodecnt (DDSIP_env,DDSIP_lp); time_end = DDSIP_GetCpuTime (); time_start = time_end-time_start; time (&DDSIP_bb->cur_time); DDSIP_translate_time (difftime(DDSIP_bb->cur_time,DDSIP_bb->start_time),&wall_hrs,&wall_mins,&wall_secs); DDSIP_translate_time (time_end,&cpu_hrs,&cpu_mins,&cpu_secs); if (mipstatus == CPXMIP_OPTIMAL) fprintf (DDSIP_bb->moreoutfile, " exp. val. prob: Best=%-20.14g\tBound=%-20.14g (%9.4g%%) \t %3dh %02d:%02.0f / %3dh %02d:%05.2f (%6.2fs n: %4d)", objval, bobjval, gap, wall_hrs,wall_mins,wall_secs,cpu_hrs,cpu_mins,cpu_secs, time_start, nodes_1st); else if (mipstatus == CPXMIP_OPTIMAL_TOL) fprintf (DDSIP_bb->moreoutfile, " exp. val. prob: Best=%-20.14g\tBound=%-20.14g (%9.4g%%) tol.\t %3dh %02d:%02.0f / %3dh %02d:%05.2f (%6.2fs n: %4d)", objval, bobjval, gap, wall_hrs,wall_mins,wall_secs,cpu_hrs,cpu_mins,cpu_secs, time_start, nodes_1st); else if (mipstatus == CPXMIP_TIME_LIM_FEAS) fprintf (DDSIP_bb->moreoutfile, " exp. val. prob: Best=%-20.14g\tBound=%-20.14g (%9.4g%%) TIME\t %3dh %02d:%02.0f / %3dh %02d:%05.2f (%6.2fs n: %4d)", objval, bobjval, gap, wall_hrs,wall_mins,wall_secs,cpu_hrs,cpu_mins,cpu_secs, time_start, nodes_1st); else fprintf (DDSIP_bb->moreoutfile, " exp. val. prob: Best=%-20.14g\tBound=%-20.14g (%9.4g%%) %-4d\t %3dh %02d:%02.0f / %3dh %02d:%05.2f (%6.2fs n: %4d)", objval, bobjval, gap, mipstatus, wall_hrs,wall_mins,wall_secs,cpu_hrs,cpu_mins,cpu_secs, time_start, nodes_1st); } // Returns sometimes rubbish, don't know why.. if (!DDSIP_bb->adv_sol) DDSIP_bb->adv_sol = (double *) DDSIP_Alloc (sizeof (double), DDSIP_bb->firstvar, "DDSIP_bb->adv_sol(sipread)"); for (j = 0; j < DDSIP_bb->firstvar; j++) { // Numerical errors ? if (DDSIP_Equal (mipx[DDSIP_bb->firstindex[j]], 0.0)) mipx[DDSIP_bb->firstindex[j]] = 0.0; DDSIP_bb->adv_sol[j] = mipx[DDSIP_bb->firstindex[j]]; } TERMINATE: DDSIP_Free ((void **) &(mipx)); return status; }
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 */
void DDSIP_DetEqu () { CPXLPptr det_equ; int status, scen, i, j, k; char probname[] = "sipout/det_equ.lp.gz"; double *obj_coef; double *scaled_obj_coef; char *sense; char **scen_spec_rowname; char **scen_spec_colname; char **rowname, *rownamestore; char **colname, *colnamestore; int rowstorespace, rowsurplus_p; int colstorespace, colsurplus_p; char *string1, *string2; double coef; double *lb, *lb_sorted; double *ub, *ub_sorted; char *vartype, *vartype_sorted; int *colindex_sorted, *colindex_revers, *matcol_sorted; double *value; double *det_equ_rhs = NULL; double *non_stoc_rhs = NULL; if (DDSIP_param->seccon) det_equ_rhs = (double *) DDSIP_Alloc(sizeof(double),DDSIP_param->seccon,"det_equ_rhs(DetEqu)"); else { fprintf (stderr,"XXX ERROR: no second stage contraints, got DDSIP_param->seccon=%d.\n",DDSIP_param->seccon); exit (1); } if (DDSIP_param->seccon - DDSIP_param->stocrhs>0) non_stoc_rhs = (double *) DDSIP_Alloc(sizeof(double),DDSIP_param->seccon - DDSIP_param->stocrhs,"non_stoc_rhs(DetEqu)"); fprintf (stderr, "\nBuilding deterministic equivalent. This may take some time.\nWorks only for expectation-based model so far.\n"); if (!(sense = (char *) calloc (DDSIP_param->seccon, sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } if (!(obj_coef = (double *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (double))) || !(scaled_obj_coef = (double *) calloc (DDSIP_bb->secvar, sizeof (double)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } det_equ = CPXcloneprob (DDSIP_env, DDSIP_lp, &status); CPXchgprobname (DDSIP_env, det_equ, probname); if (!(rowname = (char **) calloc (DDSIP_param->seccon, sizeof (char *))) || !(scen_spec_rowname = (char **) calloc (DDSIP_param->seccon, sizeof (char *))) || !(rownamestore = (char *) calloc (DDSIP_param->seccon * 255, sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } rowstorespace = DDSIP_param->seccon * 255; status = CPXgetrowname (DDSIP_env, DDSIP_lp, rowname, rownamestore, rowstorespace, &rowsurplus_p, DDSIP_param->firstcon, DDSIP_param->firstcon + DDSIP_param->seccon - 1); if (!(colname = (char **) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (char *))) || !(scen_spec_colname = (char **) calloc (DDSIP_param->secvar, sizeof (char *))) || !(colnamestore = (char *) calloc (DDSIP_param->secvar * 255, sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } colstorespace = (DDSIP_param->firstvar + DDSIP_param->secvar) * 255; status = CPXgetcolname (DDSIP_env, DDSIP_lp, colname, colnamestore, colstorespace, &colsurplus_p, 0, DDSIP_param->firstvar + DDSIP_param->secvar - 1); /*____________________________________________________________________________________*/ status = CPXgetsense (DDSIP_env, DDSIP_lp, sense, DDSIP_param->firstcon, DDSIP_param->firstcon + DDSIP_param->seccon - 1); /*____________________________________________________________________________________*/ status = CPXgetrhs (DDSIP_env, DDSIP_lp, non_stoc_rhs, DDSIP_param->firstcon + DDSIP_param->stocrhs, DDSIP_param->firstcon + DDSIP_param->seccon - 1); /*____________________________________________________________________________________*/ status = CPXgetobj (DDSIP_env, DDSIP_lp, obj_coef, 0, DDSIP_param->firstvar + DDSIP_param->secvar - 1); /*____________________________________________________________________________________*/ //copy rownames scenario many times, append scenario index //and enter sense and rhs for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->seccon; j++) { if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } string1 = rowname[j]; sprintf (string2, "%sSC%.3d", string1, scen); scen_spec_rowname[j] = string2; if (j < DDSIP_param->stocrhs) det_equ_rhs[j] = DDSIP_data->rhs[DDSIP_param->stocrhs * scen + j]; else det_equ_rhs[j] = non_stoc_rhs[j - DDSIP_param->stocrhs]; } status = CPXnewrows (DDSIP_env, det_equ, DDSIP_param->seccon, det_equ_rhs, sense, NULL, scen_spec_rowname); for (j = 0; j < DDSIP_param->seccon; j++) DDSIP_Free ((void **) &(scen_spec_rowname[j])); } //copy colnames scenario many times, append scenario index //and enter into constraint matrix if (!(lb = (double *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (double))) || !(lb_sorted = (double *) calloc (DDSIP_param->secvar, sizeof (double))) || !(ub = (double *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (double))) || !(ub_sorted = (double *) calloc (DDSIP_param->secvar, sizeof (double))) || !(vartype = (char *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (char))) || !(vartype_sorted = (char *) calloc (DDSIP_param->secvar, sizeof (double))) || !(colindex_revers = (int *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (int))) || !(colindex_sorted = (int *) calloc (DDSIP_param->firstvar + DDSIP_param->secvar, sizeof (int)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } status = CPXgetlb (DDSIP_env, det_equ, lb, 0, DDSIP_param->firstvar + DDSIP_param->secvar - 1); status = CPXgetub (DDSIP_env, det_equ, ub, 0, DDSIP_param->firstvar + DDSIP_param->secvar - 1); status = CPXgetctype (DDSIP_env, det_equ, vartype, 0, DDSIP_param->firstvar + DDSIP_param->secvar - 1); for (j = 0; j < DDSIP_param->secvar; j++) { vartype_sorted[j] = vartype[DDSIP_bb->secondindex[j]]; lb_sorted[j] = lb[DDSIP_bb->secondindex[j]]; ub_sorted[j] = ub[DDSIP_bb->secondindex[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->secvar; j++) { if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } string1 = colname[DDSIP_bb->secondindex[j]]; sprintf (string2, "%sSC%.3d", string1, scen); scen_spec_colname[j] = string2; scaled_obj_coef[j] = DDSIP_data->prob[scen] * obj_coef[DDSIP_bb->secondindex[j]]; } status = CPXnewcols (DDSIP_env, det_equ, DDSIP_param->secvar, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname); for (j = 0; j < DDSIP_param->secvar; j++) DDSIP_Free ((void **) &(scen_spec_colname[j])); } ///////////////////////////////////////////////// for (j = 0; j < DDSIP_param->firstvar; j++) { colindex_sorted[j] = DDSIP_bb->firstindex[j]; } for (j = 0; j < DDSIP_param->secvar; j++) { colindex_sorted[DDSIP_param->firstvar + j] = DDSIP_bb->secondindex[j]; } for (j = 0; j < DDSIP_param->firstvar + DDSIP_param->secvar; j++) { colindex_revers[colindex_sorted[j]] = j; } k = DDSIP_param->seccon / 60; printf ("\n0%% 100%%\n"); for (i = 0; i < DDSIP_param->seccon; i++) { for (j = 0; j < DDSIP_param->firstvar; j++) { if ((status = CPXgetcoef (DDSIP_env, det_equ, DDSIP_param->firstcon + i, colindex_sorted[j], &coef))) { fprintf (stderr, " Build det. equivalent: Error retrieving coefficient of first-stage Variable %d.\n", j); exit (1); } if (coef) { for (scen = 0; scen < DDSIP_param->scenarios; scen++) { status = CPXchgcoef (DDSIP_env, det_equ, DDSIP_param->firstcon + DDSIP_bb->seccon + scen * DDSIP_param->seccon + i, colindex_sorted[j], coef); if (status) { fprintf (stderr, " Build det. equivalent: Error setting coefficient of first-stage Variable %d.\n", j); exit (1); } } } } for (j = DDSIP_param->firstvar; j < DDSIP_param->firstvar + DDSIP_param->secvar; j++) { if ((status = CPXgetcoef (DDSIP_env, det_equ, DDSIP_param->firstcon + i, colindex_sorted[j], &coef))) { fprintf (stderr, " Build det. equivalent: Error retrieving coefficient of second-stage Variable %d.\n", j - DDSIP_param->firstvar); exit (1); } if (coef) { for (scen = 0; scen < DDSIP_param->scenarios; scen++) { status = CPXchgcoef (DDSIP_env, det_equ, DDSIP_param->firstcon + DDSIP_bb->seccon + scen * DDSIP_param->seccon + i, (scen + 1) * DDSIP_param->secvar + j, coef); } if (status) { fprintf (stderr, " Build det. equivalent: Error setting coefficient of second-stage Variable %d.\n", j - DDSIP_param->firstvar); exit (1); } } } if (!k) { for (j = 0; j <= 60 / DDSIP_param->seccon; j++) printf ("#"); } else if (i % k == k - 1) printf ("#"); } printf ("\n\n"); ///////delete original second stage rows & cols //////////////////////////////////////////// status = CPXdelrows (DDSIP_env, det_equ, DDSIP_param->firstcon, DDSIP_param->firstcon + DDSIP_bb->seccon - 1); j = 0; for (i = 0; i < DDSIP_param->secvar; i++) { status = CPXdelcols (DDSIP_env, det_equ, DDSIP_bb->secondindex[i] - j, DDSIP_bb->secondindex[i] - j); j++; } ///////enter stochastic matrix entries////////////////////////////////////////////////////// if (DDSIP_param->stocmat) { if (!(value = (double *) calloc (DDSIP_param->stocmat, sizeof (double))) || !(matcol_sorted = (int *) calloc (DDSIP_param->stocmat, sizeof (int)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } for (j = 0; j < DDSIP_param->stocmat; j++) { matcol_sorted[j] = colindex_revers[DDSIP_data->matcol[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->stocmat; j++) { value[j] = DDSIP_data->matval[scen * DDSIP_param->stocmat + j]; } status = CPXchgcoeflist (DDSIP_env, det_equ, DDSIP_param->stocmat, DDSIP_data->matrow, matcol_sorted, value); if (status) { char errmsg[1024]; CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "in DetEqu: %s\n", errmsg); } for (j = 0; j < DDSIP_param->stocmat; j++) { DDSIP_data->matrow[j] += DDSIP_param->seccon; if (matcol_sorted[j] >= DDSIP_param->firstvar) matcol_sorted[j] += DDSIP_param->secvar; } } DDSIP_Free ((void **) &(value)); DDSIP_Free ((void **) &(matcol_sorted)); //set matrow to the old values for (j = 0; j < DDSIP_param->stocmat; j++) { DDSIP_data->matrow[j] -= DDSIP_param->scenarios * DDSIP_param->seccon; } } ///////enter stochastic cost coefficients ////////////////////////////////////////////////// if (DDSIP_param->stoccost) { if (!(value = (double *) calloc (DDSIP_param->stoccost, sizeof (double))) || !(matcol_sorted = (int *) calloc (DDSIP_param->stoccost, sizeof (int)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); return; } for (j = 0; j < DDSIP_param->stoccost; j++) { value[j] = 0.0; matcol_sorted[j] = colindex_revers[DDSIP_data->costind[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->stoccost; j++) { if (matcol_sorted[j] >= DDSIP_param->firstvar) value[j] = DDSIP_data->prob[scen] * DDSIP_data->cost[scen * DDSIP_param->stoccost + j]; else value[j] += DDSIP_data->prob[scen] * DDSIP_data->cost[scen * DDSIP_param->stoccost + j]; } status = CPXchgobj (DDSIP_env, det_equ, DDSIP_param->stoccost, matcol_sorted, value); if (status) { char errmsg[1024]; CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "in DetEqu: %s\n", errmsg); } for (j = 0; j < DDSIP_param->stoccost; j++) { if (matcol_sorted[j] >= DDSIP_param->firstvar) matcol_sorted[j] += DDSIP_param->secvar; } } DDSIP_Free ((void **) &(value)); DDSIP_Free ((void **) &(matcol_sorted)); } //////////////////////////////////////////////////////////////////////////////////////////// status = CPXwriteprob (DDSIP_env, det_equ, probname, NULL); if (status) fprintf (DDSIP_outfile, " *** Deterministic equivalent not written successfully, status = %d\n", status); else fprintf (DDSIP_outfile, " *** Deterministic equivalent written successfully\n"); status = CPXfreeprob (DDSIP_env, &det_equ); DDSIP_Free ((void **) &(sense)); DDSIP_Free ((void **) &(vartype)); DDSIP_Free ((void **) &(rowname)); DDSIP_Free ((void **) &(rownamestore)); DDSIP_Free ((void **) &(colname)); DDSIP_Free ((void **) &(colnamestore)); DDSIP_Free ((void **) &(det_equ_rhs)); DDSIP_Free ((void **) &(non_stoc_rhs)); DDSIP_Free ((void **) &(lb)); DDSIP_Free ((void **) &(ub)); DDSIP_Free ((void **) &(vartype_sorted)); DDSIP_Free ((void **) &(lb_sorted)); DDSIP_Free ((void **) &(ub_sorted)); DDSIP_Free ((void **) &(obj_coef)); DDSIP_Free ((void **) &(scaled_obj_coef)); DDSIP_Free ((void **) &(colindex_sorted)); DDSIP_Free ((void **) &(colindex_revers)); DDSIP_Free ((void **) &(scen_spec_rowname)); DDSIP_Free ((void **) &(scen_spec_colname)); return; }
long GenModelCplex::ExportModel(string aFilename) { CplexData* d = (CplexData*)solverdata; return CPXwriteprob(d->env, d->lp, aFilename.c_str(), NULL); }
/*********************************************************************************** IPOutInFile - Write the model in a LP file ***********************************************************************************/ void IPOutInFile() { CPXwriteprob(env,lp,"IP.lp","LP"); }
/* 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); }
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 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); }
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 */
void DDSIP_DetEqu () { CPXLPptr det_equ; int status, scen, i, j, k, nzcnt_row, ranged = 0; char probname[] = "sipout/det_equ.lp.gz"; double *scaled_obj_coef = NULL; char *sense = NULL, *sense_sorted = NULL; char **scen_spec_rowname = NULL; char **scen_spec_colname = NULL; char **rowname = NULL, *rownamestore = NULL; char **colname = NULL, *colnamestore = NULL; int rowstorespace, rowsurplus; int colstorespace, colsurplus; char *string1 = NULL, *string2 = NULL; double *lb = NULL, *lb_sorted = NULL; double *ub = NULL, *ub_sorted = NULL; double *rng = NULL, *rng_sorted = NULL; char *vartype = NULL, *vartype_sorted = NULL; int *colindex_sorted = NULL, *colindex_revers = NULL; double *value = NULL; double *det_equ_rhs = NULL; double *base_rhs = NULL; int nzcnt=0, *rmatbeg=NULL, *rmatind=NULL, *rmatbeg_stage=NULL, *rmatind_stage=NULL, *rowindex=NULL; double *rmatval=NULL, *rmatval_stage=NULL; double time_start, time_end; time_start = DDSIP_GetCpuTime (); k = abs(DDSIP_param->riskmod); if (k > 2 && k != 4) { fprintf (stderr, "\nNot building deterministic equivalent, not available for risk model %d\n",DDSIP_param->riskmod); fprintf (DDSIP_outfile, "\nNot building deterministic equivalent, not available for risk model %d\n",DDSIP_param->riskmod); return; } if (DDSIP_data->seccon) det_equ_rhs = (double *) DDSIP_Alloc(sizeof(double),DDSIP_Imax(DDSIP_Imax(DDSIP_data->seccon, DDSIP_param->scenarios), DDSIP_data->firstcon),"det_equ_rhs(DetEqu)"); else { fprintf (stderr,"XXX ERROR: no second stage contraints, got DDSIP_data->seccon=%d.\n",DDSIP_data->seccon); return; } fprintf (stderr, "\nBuilding deterministic equivalent.\nWorks only for expectation-based models.\n"); colstorespace = DDSIP_data->novar * 255; rowstorespace = DDSIP_data->nocon * 255; if (!(sense = (char *) DDSIP_Alloc (sizeof (char), DDSIP_data->nocon, "sense(DetEqu)")) || !(sense_sorted = (char *) DDSIP_Alloc (sizeof (char), DDSIP_Imax(DDSIP_param->scenarios, DDSIP_Imax(DDSIP_data->firstcon,DDSIP_data->seccon)), "sense_sorted(DetEqu)")) || !(base_rhs = (double *) DDSIP_Alloc(sizeof(double),DDSIP_data->nocon,"base_rhs(DetEqu)")) || !(scaled_obj_coef = (double *) DDSIP_Alloc (sizeof (double), DDSIP_Imax(DDSIP_data->firstvar, DDSIP_data->secvar), "base_rhs(DetEqu)")) || !(colname = (char **) DDSIP_Alloc (sizeof (char *), DDSIP_data->novar,"base_rhs(DetEqu)")) || !(scen_spec_colname = (char **) DDSIP_Alloc (sizeof (char *), DDSIP_Imax(DDSIP_data->firstvar,DDSIP_data->secvar), "scen_spec_colname(DetEqu)")) || !(colnamestore = (char *) DDSIP_Alloc (sizeof (char), colstorespace, "colnamestore(DetEqu)")) || !(rowname = (char **) DDSIP_Alloc (sizeof (char *), DDSIP_data->nocon, "rowname(DetrEqu)")) || !(scen_spec_rowname = (char **) DDSIP_Alloc (sizeof (char *), DDSIP_Imax(DDSIP_param->scenarios, DDSIP_Imax(DDSIP_data->firstcon,DDSIP_data->seccon)), "scen_spec_rowname(DetEqu)")) || !(rownamestore = (char *) DDSIP_Alloc (sizeof (char), rowstorespace, "rownamestore(DetEqu)")) || !(lb = (double *) DDSIP_Alloc (sizeof (double), DDSIP_data->novar, "lb(DetEqu)")) || !(lb_sorted = (double *) DDSIP_Alloc (sizeof (double), DDSIP_Imax(DDSIP_data->firstvar,DDSIP_data->secvar), "lb_sorted(DetEqu)")) || !(ub = (double *) DDSIP_Alloc (sizeof (double), DDSIP_data->novar, "ub(DetEqu)")) || !(ub_sorted = (double *) DDSIP_Alloc (sizeof (double), DDSIP_Imax(DDSIP_data->firstvar,DDSIP_data->secvar), "ub_sorted(DetEqu)")) || !(vartype = (char *) DDSIP_Alloc (sizeof (char), DDSIP_data->novar, "vartype(DetEqu)")) || !(vartype_sorted = (char *) DDSIP_Alloc (sizeof (double), DDSIP_Imax(DDSIP_data->firstvar,DDSIP_data->secvar), "vartype_sorted(DetEqu)")) || !(colindex_sorted = (int *) DDSIP_Alloc (sizeof (int), DDSIP_data->novar, "colindex_sorted(DetEqu)")) || !(rowindex = (int *) DDSIP_Alloc (sizeof (int), DDSIP_Imax(DDSIP_data->firstcon, DDSIP_data->seccon), "rowindex(DetEqu)"))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } // get problem data /*____________________________________________________________________________________*/ if((status = CPXgetcolname (DDSIP_env, DDSIP_lp, colname, colnamestore, colstorespace, &colsurplus, 0, DDSIP_data->novar - 1)) || (status = CPXgetrowname (DDSIP_env, DDSIP_lp, rowname, rownamestore, rowstorespace, &rowsurplus, 0, DDSIP_data->nocon - 1)) || (status = CPXgetsense (DDSIP_env, DDSIP_lp, sense, 0, DDSIP_data->nocon - 1)) || (status = CPXgetrhs (DDSIP_env, DDSIP_lp, base_rhs, 0, DDSIP_data->nocon - 1)) || (status = CPXgetlb (DDSIP_env, DDSIP_lp, lb, 0, DDSIP_data->novar - 1)) || (status = CPXgetub (DDSIP_env, DDSIP_lp, ub, 0, DDSIP_data->novar - 1)) || (status = CPXgetctype (DDSIP_env, DDSIP_lp, vartype, 0, DDSIP_data->novar - 1))) { fprintf (stderr, "Coud not get problem data, returned %d\n", status); goto FREE; } // check whether there are ranged rows for (j=0; j<DDSIP_data->nocon; j++) { if (sense[j] == 'R') { ranged = 1; break; } } if (ranged) { if (!(rng = (double *) DDSIP_Alloc (sizeof (double), DDSIP_data->nocon, "rng(DetEqu)")) || !(rng_sorted = (double *) DDSIP_Alloc (sizeof (double), DDSIP_Imax(DDSIP_data->firstcon,DDSIP_data->seccon), "rng_sorted(DetEqu)"))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } if ((status = CPXgetrngval (DDSIP_env, DDSIP_lp, rng, 0, DDSIP_data->nocon-1))) { fprintf (stderr, "Coud not get problem ranges, returned %d\n", status); goto FREE; } } /*____________________________________________________________________________________*/ // create empty problem det_equ = CPXcreateprob (DDSIP_env, &status, probname); if (status) { fprintf (stderr, "CPXcreateprob returned %d\n", status); goto FREE; } // add (original) first-stage variables for (j = 0; j < DDSIP_data->firstvar; j++) { vartype_sorted[j] = vartype[DDSIP_bb->firstindex[j]]; lb_sorted[j] = lb[DDSIP_bb->firstindex[j]]; ub_sorted[j] = ub[DDSIP_bb->firstindex[j]]; if (DDSIP_param->deteqType && DDSIP_param->riskmod >= 0) scaled_obj_coef[j] = DDSIP_data->obj_coef[DDSIP_bb->firstindex[j]]; scen_spec_colname[j]= colname[DDSIP_bb->firstindex[j]]; } if ((status = CPXnewcols (DDSIP_env, det_equ, DDSIP_data->firstvar, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for first-stage variables\n", status); goto FREE; } // add (original) second-stage variables for all scenarios for (j = 0; j < DDSIP_data->secvar; j++) { vartype_sorted[j] = vartype[DDSIP_bb->secondindex[j]]; lb_sorted[j] = lb[DDSIP_bb->secondindex[j]]; ub_sorted[j] = ub[DDSIP_bb->secondindex[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_data->secvar; j++) { if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } // append scenario index to colname string1 = colname[DDSIP_bb->secondindex[j]]; sprintf (string2, "%sSC%.3d", string1, scen+1); scen_spec_colname[j] = string2; if (DDSIP_param->deteqType && DDSIP_param->riskmod >= 0) scaled_obj_coef[j] = DDSIP_data->prob[scen] * DDSIP_data->obj_coef[DDSIP_bb->secondindex[j]]; } if ((status = CPXnewcols (DDSIP_env, det_equ, DDSIP_data->secvar, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for second-stage variables of scenario %d\n", status, scen+1); goto FREE; } for (j = 0; j < DDSIP_data->secvar; j++) DDSIP_Free ((void **) &(scen_spec_colname[j])); } // add second-stage variable for objective value of the scenarios if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } scen_spec_colname[0] = string2; for (scen = 0; scen < DDSIP_param->scenarios; scen++) { vartype_sorted[0] = 'C'; lb_sorted[0] = -DDSIP_infty; ub_sorted[0] = DDSIP_infty; sprintf (string2, "DDSIPobj_SC%.3d", scen+1); if (!DDSIP_param->deteqType && DDSIP_param->riskmod >= 0) scaled_obj_coef[0] = DDSIP_data->prob[scen]; else scaled_obj_coef[0] = 0.; if ((status = CPXnewcols (DDSIP_env, det_equ, 1, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for second-stage variable DDSIPobj_SC%.3d\n", status, scen+1); goto FREE; } } // add the additional variables needed for risk models /////////////////////////////////////// if (DDSIP_param->riskmod) { switch (abs(DDSIP_param->riskmod)) { case 1: // Expected excess // one continuous second-stage variable for each scenario for (scen = 0; scen < DDSIP_param->scenarios; scen++) { vartype_sorted[0] = 'C'; lb_sorted[0] = 0.; ub_sorted[0] = DDSIP_infty; sprintf (string2, "DDSIP_expexc_SC%.3d", scen+1); if (DDSIP_param->riskmod > 0) scaled_obj_coef[0] = DDSIP_param->riskweight*DDSIP_data->prob[scen]; else if (DDSIP_param->riskmod < 0) scaled_obj_coef[0] = DDSIP_data->prob[scen]; else scaled_obj_coef[0] = 0.; if ((status = CPXnewcols (DDSIP_env, det_equ, 1, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for second-stage variable %s\n", status, string2); goto FREE; } } break; case 2: // Excess Probability // one binary second-stage variable for each scenario for (scen = 0; scen < DDSIP_param->scenarios; scen++) { vartype_sorted[0] = 'B'; lb_sorted[0] = 0.; ub_sorted[0] = 1.; sprintf (string2, "DDSIP_excprob_SC%.3d", scen+1); if (DDSIP_param->riskmod > 0) scaled_obj_coef[0] = DDSIP_param->riskweight*DDSIP_data->prob[scen]; else if (DDSIP_param->riskmod < 0) scaled_obj_coef[0] = DDSIP_data->prob[scen]; else scaled_obj_coef[0] = 0.; if ((status = CPXnewcols (DDSIP_env, det_equ, 1, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for second-stage variable %s\n", status, string2); goto FREE; } } break; case 4: // Worst Case Costs // one continuous first-stage variable vartype_sorted[0] = 'C'; lb_sorted[0] = -DDSIP_infty; ub_sorted[0] = DDSIP_infty; if (DDSIP_param->prefix) { if (!(strlen(DDSIP_param->prefix))) { fprintf (stderr," *** ERROR: The prefix for the first stage variables has to have a positive length.\n"); exit (1); } sprintf (string2, "%sDDSIP_n_aux01",DDSIP_param->prefix); } else { if (!(strlen(DDSIP_param->postfix))) { fprintf (stderr," *** ERROR: The postfix for the first stage variables has to have a positive length.\n"); exit (1); } sprintf (string2, "DDSIP_worstc_%s",DDSIP_param->postfix); } if (DDSIP_param->riskmod > 0) scaled_obj_coef[0] = DDSIP_param->riskweight; else if (DDSIP_param->riskmod < 0) scaled_obj_coef[0] = 1.; else scaled_obj_coef[0] = 0.; if ((status = CPXnewcols (DDSIP_env, det_equ, 1, scaled_obj_coef, lb_sorted, ub_sorted, vartype_sorted, scen_spec_colname))) { fprintf (stderr, "CPXnewcols returned %d for second-stage variable %s\n", status, string2); goto FREE; } } } DDSIP_Free ((void **) &(scen_spec_colname[0])); ///////enter stochastic cost coefficients in case of deteqType 1 ////////////////////////////// if (DDSIP_param->stoccost && DDSIP_param->deteqType && DDSIP_param->riskmod >= 0) { for (j = 0; j < DDSIP_param->stoccost; j++) { scaled_obj_coef[j] = 0.0; if ((colindex_sorted[j] = DDSIP_bb->firstindex_reverse[DDSIP_data->costind[j]])) colindex_sorted[j] = DDSIP_data->firstvar + DDSIP_bb->secondindex_reverse[DDSIP_data->costind[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->stoccost; j++) { if (colindex_sorted[j] >= DDSIP_data->firstvar) scaled_obj_coef[j] = DDSIP_data->prob[scen] * DDSIP_data->cost[scen * DDSIP_param->stoccost + j]; else scaled_obj_coef[j] += DDSIP_data->prob[scen] * DDSIP_data->cost[scen * DDSIP_param->stoccost + j]; } status = CPXchgobj (DDSIP_env, det_equ, DDSIP_param->stoccost, colindex_sorted, scaled_obj_coef); if (status) { char errmsg[1024]; CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "in DetEqu: %s\n", errmsg); } for (j = 0; j < DDSIP_param->stoccost; j++) { if (colindex_sorted[j] >= DDSIP_data->firstvar) colindex_sorted[j] += DDSIP_data->secvar; } } } // // free arrays needeed only for columns DDSIP_Free ((void **) &(vartype)); DDSIP_Free ((void **) &(colname)); DDSIP_Free ((void **) &(colnamestore)); DDSIP_Free ((void **) &(lb)); DDSIP_Free ((void **) &(ub)); DDSIP_Free ((void **) &(vartype_sorted)); DDSIP_Free ((void **) &(lb_sorted)); DDSIP_Free ((void **) &(ub_sorted)); DDSIP_Free ((void **) &(scaled_obj_coef)); // // get problem matrix coefficients // query the length needed for storage of coefficients CPXgetrows(DDSIP_env, DDSIP_lp, &nzcnt, rmatbeg, rmatind, rmatval, 0, &rowsurplus, 0, DDSIP_data->nocon-1); nzcnt = -rowsurplus; if (!(rmatbeg = (int *) DDSIP_Alloc (sizeof (int), DDSIP_data->nocon, "rmatbeg(DetEqu)")) || !(rmatind = (int *) DDSIP_Alloc (sizeof (int), DDSIP_Imax(nzcnt, DDSIP_param->stocmat), "rmatind(DetEqu)")) || !(rmatval = (double *) DDSIP_Alloc (sizeof (double), nzcnt, "rmatval(DetEqu)"))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } CPXgetrows(DDSIP_env, DDSIP_lp, &nzcnt, rmatbeg, rmatind, rmatval, nzcnt, &rowsurplus, 0, DDSIP_data->nocon-1); printf(" got %d elements of the matrix\n", nzcnt); k = DDSIP_Imax(nzcnt + DDSIP_param->stocmat, DDSIP_param->scenarios*(DDSIP_data->novar+1)); if (!(rmatbeg_stage = (int *) DDSIP_Alloc (sizeof (int), DDSIP_Imax(DDSIP_param->scenarios, DDSIP_Imax(DDSIP_data->firstcon, DDSIP_data->seccon)), "rmatbeg_stage(DetEqu)")) || !(rmatind_stage = (int *) DDSIP_Alloc (sizeof (int), k, "rmatind_stage(DetEqu)")) || !(rmatval_stage = (double *) DDSIP_Alloc (sizeof (double), k, "rmatval_stage(DetEqu)"))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } // add first-stage constraints k = 0; for (j = 0; j < DDSIP_data->firstcon; j++) { sense_sorted[j] = sense[DDSIP_bb->firstrowind[j]]; det_equ_rhs[j] = base_rhs[DDSIP_bb->firstrowind[j]]; scen_spec_rowname[j] = rowname[DDSIP_bb->firstrowind[j]]; rmatbeg_stage[j] = k; if (DDSIP_bb->firstrowind[j] == DDSIP_data->nocon -1) nzcnt_row = nzcnt - rmatbeg[DDSIP_data->nocon -1]; else nzcnt_row = rmatbeg[DDSIP_bb->firstrowind[j]+1] - rmatbeg[DDSIP_bb->firstrowind[j]]; for (i = 0; i < nzcnt_row; i++) { rmatind_stage[k + i] = DDSIP_bb->firstindex_reverse[rmatind[rmatbeg[DDSIP_bb->firstrowind[j]] + i]]; rmatval_stage[k + i] = rmatval[rmatbeg[DDSIP_bb->firstrowind[j]] + i]; } k += nzcnt_row; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_data->firstcon, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for first-stage constraints\n", status); goto FREE; } if (ranged) { for (j = 0; j < DDSIP_data->firstcon; j++) { rng_sorted[j] = rng[DDSIP_bb->firstrowind[j]]; rowindex[j] = j; } if((status = CPXchgrngval(DDSIP_env, det_equ, DDSIP_data->firstcon, rowindex, rng_sorted))) { fprintf (stderr, "CPXchgrngval returned %d for first-stage constraints\n", status); goto FREE; } } // add second-stage constraints for (scen = 0; scen < DDSIP_param->scenarios; scen++) { k = 0; for (j = 0; j < DDSIP_data->seccon; j++) { sense_sorted[j] = sense[DDSIP_bb->secondrowind[j]]; det_equ_rhs[j] = base_rhs[DDSIP_bb->secondrowind[j]]; if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } // append scenario index to colname string1 = rowname[DDSIP_bb->secondrowind[j]]; sprintf (string2, "%sSC%.3d", string1, scen+1); scen_spec_rowname[j] = string2; rmatbeg_stage[j] = k; if (DDSIP_bb->secondrowind[j] == DDSIP_data->nocon -1) nzcnt_row = nzcnt - rmatbeg[DDSIP_data->nocon -1]; else { nzcnt_row = rmatbeg[DDSIP_bb->secondrowind[j]+1] - rmatbeg[DDSIP_bb->secondrowind[j]]; } for (i = 0; i < nzcnt_row; i++) { if (DDSIP_bb->firstindex_reverse[rmatind[rmatbeg[DDSIP_bb->secondrowind[j]] + i]] < 0) rmatind_stage[k + i] = DDSIP_data->firstvar + scen*DDSIP_data->secvar + DDSIP_bb->secondindex_reverse[rmatind[rmatbeg[DDSIP_bb->secondrowind[j]] + i]]; else rmatind_stage[k + i] = DDSIP_bb->firstindex_reverse[rmatind[rmatbeg[DDSIP_bb->secondrowind[j]] + i]]; rmatval_stage[k + i] = rmatval[rmatbeg[DDSIP_bb->secondrowind[j]] + i]; } k += nzcnt_row; } ///////enter stochastic rhs entries////////////////////////////////////////////////////// for (j=0; j< DDSIP_param->stocrhs; j++) { det_equ_rhs[DDSIP_bb->secondrowind_reverse[DDSIP_data->rhsind[j]]] = DDSIP_data->rhs[scen * DDSIP_param->stocrhs + j]; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_data->seccon, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for second-stage constraints scenario %d\n", status, scen+1); goto FREE; } for (j = 0; j < DDSIP_data->seccon; j++) DDSIP_Free ((void **) &(scen_spec_rowname[j])); if (ranged) { for (j = 0; j < DDSIP_data->seccon; j++) { rng_sorted[j] = rng[DDSIP_bb->secondrowind[j]]; rowindex[j] = DDSIP_data->firstcon + scen * DDSIP_data->seccon + j; } if ((status = CPXchgrngval(DDSIP_env, det_equ, DDSIP_data->seccon, rowindex, rng_sorted))) { fprintf (stderr, "CPXchgrngval returned %d for first-stage constraints\n", status); goto FREE; } } } ///////enter stochastic matrix entries////////////////////////////////////////////////////// if (DDSIP_param->stocmat) { if (!(value = (double *) calloc (DDSIP_param->stocmat, sizeof (double)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } for (j = 0; j < DDSIP_param->stocmat; j++) { if ((colindex_sorted[j] = DDSIP_bb->firstindex_reverse[DDSIP_data->matcol[j]])) colindex_sorted[j] = DDSIP_data->firstvar + DDSIP_bb->secondindex_reverse[DDSIP_data->matcol[j]]; rmatind[j] = DDSIP_data->firstcon + DDSIP_bb->secondrowind_reverse[DDSIP_data->matrow[j]]; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->stocmat; j++) { value[j] = DDSIP_data->matval[scen * DDSIP_param->stocmat + j]; } status = CPXchgcoeflist (DDSIP_env, det_equ, DDSIP_param->stocmat, rmatind, colindex_sorted, value); if (status) { char errmsg[1024]; CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "in DetEqu chgcoeflist returned %d: %s\n", status, errmsg); } for (j = 0; j < DDSIP_param->stocmat; j++) { rmatind[j] += DDSIP_data->seccon; if (colindex_sorted[j] >= DDSIP_data->firstvar) colindex_sorted[j] += DDSIP_data->secvar; } } DDSIP_Free ((void **) &(value)); } // add second-stage equations for the objective values of the scenarios k = 0; for (scen = 0; scen < DDSIP_param->scenarios; scen++) { sense_sorted[scen] = 'E'; det_equ_rhs[scen] = 0.; if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } sprintf (string2, "DDSIP_o_SC%.3d", scen+1); scen_spec_rowname[scen] = string2; rmatbeg_stage[scen] = k; nzcnt_row = DDSIP_data->novar + 1; for (i = 0; i < DDSIP_data->novar; i++) { if (DDSIP_bb->firstindex_reverse[i] < 0) { rmatind_stage[k + i] = DDSIP_data->firstvar + scen*DDSIP_data->secvar + DDSIP_bb->secondindex_reverse[i]; } else { rmatind_stage[k + i] = DDSIP_bb->firstindex_reverse[i]; } rmatval_stage[k + i] = DDSIP_data->obj_coef[i]; } rmatind_stage[k + DDSIP_data->novar] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + scen; rmatval_stage[k + DDSIP_data->novar] = -1.; k += nzcnt_row; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_param->scenarios, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for second-stage objective constraints\n", status); goto FREE; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { DDSIP_Free ((void **) &(scen_spec_rowname[scen])); } ///////enter stochastic cost coefficients in the objective equations ////////////////////////////// if (DDSIP_param->stoccost) { if (!(value = (double *) calloc (DDSIP_param->stoccost, sizeof (double)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } for (scen = 0; scen < DDSIP_param->scenarios; scen++) { for (j = 0; j < DDSIP_param->stoccost; j++) { if ((colindex_sorted[j] = DDSIP_bb->firstindex_reverse[DDSIP_data->costind[j]]) < 0) colindex_sorted[j] = DDSIP_data->firstvar + scen * DDSIP_data->secvar +DDSIP_bb->secondindex_reverse[DDSIP_data->costind[j]]; rmatind[j] = DDSIP_data->firstcon + DDSIP_param->scenarios*DDSIP_data->seccon + scen; value[j] = DDSIP_data->cost[scen * DDSIP_param->stoccost + j]; } status = CPXchgcoeflist (DDSIP_env, det_equ, DDSIP_param->stoccost, rmatind, colindex_sorted, value); if (status) { char errmsg[1024]; CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "in DetEqu chgcoeflist returned %d: %s\n", status, errmsg); } for (j = 0; j < DDSIP_param->stocmat; j++) { rmatind[j] += DDSIP_data->seccon; if (colindex_sorted[j] >= DDSIP_data->firstvar) colindex_sorted[j] += DDSIP_data->secvar; } } DDSIP_Free ((void **) &(value)); } // add second-stage equations for the risk models ////////////////////////////////// switch (abs(DDSIP_param->riskmod)) { case 1: // Expected excess k = 0; for (scen = 0; scen < DDSIP_param->scenarios; scen++) { sense_sorted[scen] = 'L'; det_equ_rhs[scen] = DDSIP_param->risktarget; if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } sprintf (string2, "DDSIP_exp_excess_SC%.3d", scen+1); scen_spec_rowname[scen] = string2; rmatbeg_stage[scen] = k; nzcnt_row = 2; rmatind_stage[k] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + scen; rmatval_stage[k] = 1.; rmatind_stage[k + 1] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + DDSIP_param->scenarios + scen; rmatval_stage[k + 1] = -1.; k += nzcnt_row; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_param->scenarios, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for second-stage risk constraints\n", status); goto FREE; } break; case 2: // Excess probability k = 0; for (scen = 0; scen < DDSIP_param->scenarios; scen++) { sense_sorted[scen] = 'L'; det_equ_rhs[scen] = DDSIP_param->risktarget; if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } sprintf (string2, "DDSIP_excess_prob_SC%.3d", scen+1); scen_spec_rowname[scen] = string2; rmatbeg_stage[scen] = k; nzcnt_row = 2; rmatind_stage[k] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + scen; rmatval_stage[k] = 1.; rmatind_stage[k + 1] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + DDSIP_param->scenarios + scen; rmatval_stage[k + 1] = -DDSIP_param->riskM; k += nzcnt_row; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_param->scenarios, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for second-stage risk constraints\n", status); goto FREE; } break; case 4: // Worst case cost k = 0; for (scen = 0; scen < DDSIP_param->scenarios; scen++) { sense_sorted[scen] = 'L'; det_equ_rhs[scen] = 0.; if (!(string2 = (char *) calloc (1, 255 * sizeof (char)))) { fprintf (stderr, "Not enough memory for building deterministic equivalent\n"); goto FREE; } sprintf (string2, "DDSIP_worst_case_SC%.3d", scen+1); scen_spec_rowname[scen] = string2; rmatbeg_stage[scen] = k; nzcnt_row = 2; rmatind_stage[k] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + scen; rmatval_stage[k] = 1.; rmatind_stage[k + 1] = DDSIP_data->firstvar + DDSIP_param->scenarios*DDSIP_data->secvar + DDSIP_param->scenarios; rmatval_stage[k + 1] = -1.; k += nzcnt_row; } if ((status = CPXaddrows(DDSIP_env, det_equ, 0, DDSIP_param->scenarios, k, det_equ_rhs, sense_sorted, rmatbeg_stage, rmatind_stage, rmatval_stage, NULL, scen_spec_rowname))) { fprintf (stderr, "CPXaddrows returned %d for second-stage risk constraints\n", status); goto FREE; } break; } for (j = 0; j < DDSIP_param->scenarios; j++) DDSIP_Free ((void **) &(scen_spec_rowname[j])); time_end = DDSIP_GetCpuTime (); fprintf (DDSIP_outfile, " %6.2f sec for building deterministic equivalent\n",time_end-time_start); status = CPXwriteprob (DDSIP_env, det_equ, probname, NULL); if (status) { fprintf (DDSIP_outfile, " *** Deterministic equivalent not written successfully, status = %d\n", status); printf (" *** Deterministic equivalent not written successfully, status = %d\n", status); } else { fprintf (DDSIP_outfile, " *** Deterministic equivalent %s written successfully\n", probname); printf (" *** Deterministic equivalent %s written successfully\n", probname); } status = CPXfreeprob (DDSIP_env, &det_equ); time_start = DDSIP_GetCpuTime (); fprintf (DDSIP_outfile, " %6.2f sec for writing deterministic equivalent\n",time_start-time_end); FREE: DDSIP_Free ((void **) &(sense)); DDSIP_Free ((void **) &(sense_sorted)); DDSIP_Free ((void **) &(vartype)); DDSIP_Free ((void **) &(rowname)); DDSIP_Free ((void **) &(rownamestore)); DDSIP_Free ((void **) &(colname)); DDSIP_Free ((void **) &(colnamestore)); DDSIP_Free ((void **) &(det_equ_rhs)); DDSIP_Free ((void **) &(base_rhs)); DDSIP_Free ((void **) &(lb)); DDSIP_Free ((void **) &(ub)); DDSIP_Free ((void **) &(vartype_sorted)); DDSIP_Free ((void **) &(lb_sorted)); DDSIP_Free ((void **) &(ub_sorted)); DDSIP_Free ((void **) &(scaled_obj_coef)); DDSIP_Free ((void **) &(colindex_sorted)); DDSIP_Free ((void **) &(colindex_revers)); DDSIP_Free ((void **) &(scen_spec_rowname)); DDSIP_Free ((void **) &(scen_spec_colname)); DDSIP_Free ((void **) &(rmatbeg)); DDSIP_Free ((void **) &(rmatind)); DDSIP_Free ((void **) &(rmatval)); DDSIP_Free ((void **) &(rmatbeg_stage)); DDSIP_Free ((void **) &(rmatind_stage)); DDSIP_Free ((void **) &(rmatval_stage)); DDSIP_Free ((void **) &(rowindex)); if (ranged) { DDSIP_Free ((void **) &(rng)); DDSIP_Free ((void **) &(rng_sorted)); } return; }
// Just write the lp problem in a file int cplex_solver::writelp(char *filename) { return CPXwriteprob (env, lp, filename, NULL); }
void CplexSolver::write(std::string const & fileName) const { CPXchgobjsen(_env, _prob, _is_minimize ? CPX_MIN : CPX_MAX); CPXwriteprob(_env, _prob, fileName.c_str(), "LP"); }
SSCplex::SSCplex( string InstanceFile ) { num_vm = 0; // number of virtual machines num_vf = 0; // number of virtual function int offset; ifstream in; in.open(InstanceFile.c_str()); if( !in.is_open() ) { cout<<"Cannot open instance file.\n"; exit(1); } //leggo da file il numero di macchine e di funzioni virtuali in >> num_vm; in >> num_vf; cout << "Num VM " << num_vm << " Num VF " << num_vf << endl; lev_card = num_vm; // the number of nodes in each level h_len = num_vf; int lev_card_arcs = lev_card*lev_card; //number of nodes and arcs NNodes = lev_card * h_len + 2; NArcs = lev_card * lev_card * (h_len-1) + 2*lev_card; // array used to store the solution Y = array(NArcs); tempi_lat = new double *[num_vm]; for (int i=0; i<num_vm; i++) tempi_lat[i] = new double[num_vm]; cap = new int[ num_vm ]; // fill the distance matrix for (int i=0; i<num_vm; i++) for (int j=0; j<num_vm; j++) // if( j >= i ) in >> tempi_lat[i][j]; // else (in input is supposed to be symmetric) // tempi_lat[i][j] = tempi_lat[j][i]; // fill the capacity array for (int i=0; i<num_vm; i++) in >> cap[ i ]; incom = new int *[num_vf]; for (int i=0; i<num_vf; i++) incom[i] = new int[num_vm+1]; proc_time = new double *[num_vf]; for (int i=0; i<num_vf; i++) proc_time[i] = new double[num_vm]; for( int i = 0; i < num_vf; i++ ) { string dummy; int cnt; in >> dummy >> incom[i][0]; cnt = incom[i][0]; for( int j = 1; j <= cnt; j++ ) in >> incom[i][j]; for( int j = 0; j < num_vm; j++ ) in >> proc_time[i][j]; } source_dist = new double[ num_vm ]; dest_dist = new double[ num_vm ]; for( int j = 0; j < num_vm; j++ ) in >> source_dist[j]; for( int j = 0; j < num_vm; j++ ) in >> dest_dist[j]; in.close(); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); if ( env == NULL ) { stop("Could not open CPLEX environment.\n", status); } /* Create the problem */ lp = CPXcreateprob( env , &status , "HCP" ); if ( lp == NULL ) { stop("Failed to create LP.\n", status); } if( DEBUG ) { CPXout.open("DEBUG.txt", ios::out); } // Turn on debugging routines status = CPXsetintparam (env, CPX_PARAM_DATACHECK, CPX_ON); if ( status ) { stop("Failure to turn on debugging, error %d.\n", status); } // Turn on output to the screen status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); if ( status ) { stop("Failure to turn on screen indicator, error %d.\n", status); } double *obj = NULL; double *ub = NULL; double *lb = NULL; char *ctype = NULL; int nzcnt; double *rhs = NULL; char *sense = NULL; int *matbeg; int *matind; double *matval; // variable counters int y_var = NArcs; // flow variables // creating variables ub = array(y_var); lb = array(y_var); for( int k = 0; k < y_var; k++ ){ lb[k] = 0.0; ub[ k ] = 1.0; } #if( MIP ) ctype = arraychar(y_var); for( int h = 0; h < y_var; h++) ctype[h] = 'B'; #endif obj = array(NArcs); for(int i = 0; i < lev_card; i++ ) obj[i] = proc_time[0][i] + source_dist[i]; offset = lev_card * lev_card * (h_len-1) + lev_card; for(int i = 0; i < lev_card; i++ ) obj[offset+i] = dest_dist[i]; offset = lev_card; for( int h = 0; h < h_len - 1; h++ ) for( int i = 0; i < lev_card; i++ ) for( int j = 0; j < lev_card; j++ ) { int k = offset + h * (lev_card * lev_card) + i * lev_card + j; obj[k] = tempi_lat[i][j] + proc_time[h+1][j]; } status = CPXnewcols(env, lp, y_var, obj, lb, ub, ctype, NULL); if ( status ) stop("Failure to create y cols.", status); nzcnt = NArcs; matind = arrayint(nzcnt); matval = array(nzcnt); matbeg = arrayint(2); rhs = array(1); // at most one constraint is loaded sense = arraychar(1); // in one shot matbeg[0] = 0; // flow conservation constraint relative to source node rhs[0] = 1.0; sense[0] = 'E'; for( int h = 0; h < lev_card; h++ ) { matind[h] = h; matval[h] = 1.0; } matbeg[1] = lev_card; status = CPXaddrows(env, lp, 0, 1, lev_card, rhs, sense, matbeg, matind, matval, NULL, NULL); if ( status ) { stop("Failed to insert cons.\n", status); } offset = lev_card + (h_len - 1) * (lev_card * lev_card); // flow conservation constraint relative to destination node for( int h = 0; h < lev_card; h++ ) { matind[h] = offset + h; matval[h] = 1.0; } matbeg[1] = lev_card; status = CPXaddrows(env, lp, 0, 1, lev_card, rhs, sense, matbeg, matind, matval, NULL, NULL); if ( status ) { stop("Failed to insert cons.\n", status); } // flow conservation constraints relative to intermediate nodes rhs[0] = 0.0; for( int h = 0; h < h_len; h++ ) { for( int i = 0; i < lev_card; i++ ) { int k = 0; // insert a constraint for each intermediate node // incoming flow if( h == 0 ) { matind[k] = i; matval[k] = -1.0; k++; } else { offset = lev_card + lev_card*lev_card*(h-1); for( int j = 0; j < lev_card; j++ ) { matind[k] = offset + j * lev_card + i; matval[k] = -1.0; k++; } } // outcoming flow if( h == h_len - 1) { offset = lev_card + lev_card*lev_card*h; matind[k] = offset + i; matval[k] = 1.0; k++; } else { offset = lev_card + lev_card*lev_card*h; for( int j = 0; j < lev_card; j++ ) { matind[k] = offset + i*lev_card + j; matval[k] = 1.0; k++; } } matbeg[1] = k; assert( k <= nzcnt ); status = CPXaddrows(env, lp, 0, 1, k, rhs, sense, matbeg, matind, matval, NULL, NULL); if ( status ) { stop("Failed to insert cons.\n", status); } } } // VM capacity constraints sense[0] = 'L'; for( int i = 0; i < lev_card; i++ ) { int k = 0; // insert a constraint for each VM rhs[0] = cap[i]; for( int h = 0; h < h_len - 1; h++ ) { offset = lev_card + lev_card*lev_card*h; for( int j = 0; j < lev_card; j++ ) { matind[k] = offset + i*lev_card + j; matval[k] = 1.0; k++; } } offset = lev_card + lev_card*lev_card*(h_len-1); matind[k] = offset + i; matval[k] = 1.0; k++; matbeg[1] = k; assert( k <= nzcnt ); status = CPXaddrows(env, lp, 0, 1, k, rhs, sense, matbeg, matind, matval, NULL, NULL); if ( status ) { stop("Failed to insert cons.\n", status); } } // incompatibilities management // vf_0 int cnt = incom[0][0]; for( int j = 0; j < cnt; j++ ) { int arc_index = incom[0][j+1]; ChgBds(arc_index, 0.0); } // other vf_h for( int h = 1; h < num_vf; h++ ) { int cnt = incom[h][0]; int offset = lev_card + (h-1) * (lev_card*lev_card); for( int j = 0; j < cnt; j++ ) for( int i = 0; i < lev_card; i++ ) { int arc_index = offset + i * lev_card + incom[h][j+1]; ChgBds(arc_index, 0.0); } } #if DEBUG status = CPXwriteprob(env, lp, "SS.lp", "LP"); if ( status ) stop("Failed to write LP to disk.", status); #endif /* Set limit to emphasize feasibility */ status = CPXsetintparam (env, CPX_PARAM_MIPEMPHASIS, MIPEMPH); if ( status ) stop("Failure to set parameter emphasizing feasibility.\n", status); // Turn on output to the screen status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); if ( status ) { stop("Failure to turn on screen indicator, error %d.\n", status); } status = CPXsetdblparam (env, CPX_PARAM_TILIM, TIMELIMIT); free_arraychar(sense); free_array(rhs); free_arrayint(matbeg); free_array(matval); free_arrayint(matind); free_array(obj); #if( MIP ) free_arraychar(ctype); #endif free_array(lb); free_array(ub); } //END SSCplex
int main(int argc, char *argv[]) { if(argc < 3){ cerr << "Uso: input_file max_iteraciones" << endl; exit(1); } srand(time(NULL)); string archivo_entrada(argv[1]); int max_iteraciones = atoi(argv[2]); //----------------------- PARSEO DE ENTRADA pair <int, pair<vector<vector<bool> >*, vector<vector<bool> >* > > grafo = parsear_entrada(archivo_entrada); int cant_ejes = grafo.first; vector<vector<bool> > *adyacencias = grafo.second.first; // matriz de adyacencia vector<vector<bool> > *particion = grafo.second.second; // filas: subconjuntos de la particion. columnas: nodos. // Variables binarias: // * X_n_j = nodo n pintado con el color j? (son cant_nodos * cant_colores_disp variables) // * W_j = hay algun nodo pintado con el color j? (son cant_colores_disp variables) // => TOTAL: (cant_nodos * cant_colores_disp + cant_colores_disp) variables // // Orden de las variables: // X_0_0, X_0_1, ... , X_0_(cant_col_disp), X_1_0, ... , X_(cant_nodos)_(cant_col_disp), W_0, ... , W(cant_col_disp) int cant_nodos = adyacencias->size(); int cant_subconj_particion = particion->size(); //cant de subconjuntos de la particion int cant_colores_disp = particion->size(); // cant colores usados <= cant de subconjuntos de la particion int n = cant_nodos * cant_colores_disp + cant_colores_disp; // n = cant de variables //----------------------- CARGA DE LP // Genero el problema de cplex. int status; CPXENVptr env; // Puntero al entorno. CPXLPptr lp; // Puntero al LP // Creo el entorno. env = CPXopenCPLEX(&status); if (env == NULL) { cerr << "Error creando el entorno" << endl; exit(1); } // Creo el LP. lp = CPXcreateprob(env, &status, "Coloreo Particionado"); if (lp == NULL) { cerr << "Error creando el LP" << endl; exit(1); } //TUNNING //Para que haga Branch & Cut: CPXsetintparam(env, CPX_PARAM_MIPSEARCH, CPX_MIPSEARCH_TRADITIONAL); //Para que no se adicionen planos de corte: ( => Branch & Bound) CPXsetintparam(env,CPX_PARAM_EACHCUTLIM, 0); CPXsetintparam(env, CPX_PARAM_FRACCUTS, -1); //Para facilitar la comparación evitamos paralelismo: CPXsetintparam(env, CPX_PARAM_THREADS, 1); //Para desactivar preprocesamiento CPXsetintparam(env, CPX_PARAM_PRESLVND, -1); CPXsetintparam(env, CPX_PARAM_REPEATPRESOLVE, 0); CPXsetintparam(env, CPX_PARAM_RELAXPREIND, 0); CPXsetintparam(env, CPX_PARAM_REDUCE, 0); CPXsetintparam(env, CPX_PARAM_LANDPCUTS, -1); //Otros parámetros // Para desactivar la salida poner CPX_OFF. Para activar: CPX_ON. status = CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF); if (status) { cerr << "Problema seteando SCRIND" << endl; exit(1); } //Setea el tiempo limite de ejecucion. status = CPXsetdblparam(env, CPX_PARAM_TILIM, 3600); if (status) { cerr << "Problema seteando el tiempo limite" << endl; exit(1); } double *ub, *lb, *objfun; // Cota superior, cota inferior, coeficiente de la funcion objetivo. char *xctype, **colnames; // tipo de la variable (por ahora son siempre continuas), string con el nombre de la variable. ub = new double[n]; lb = new double[n]; objfun = new double[n]; xctype = new char[n]; colnames = new char*[n]; // Defino las variables X_n_j for (int i = 0; i < n - cant_colores_disp; i++) { ub[i] = 1; lb[i] = 0; objfun[i] = 0; // Estas var no figuran en la funcion objetivo xctype[i] = 'C'; colnames[i] = new char[10]; sprintf(colnames[i], "X_%d_%d", i / cant_colores_disp, i % cant_colores_disp); } // Defino las variables W_j for (int i = n - cant_colores_disp; i < n; i++) { ub[i] = 1; lb[i] = 0; objfun[i] = 1; xctype[i] = 'C'; colnames[i] = new char[10]; sprintf(colnames[i], "W_%d", i - (n - cant_colores_disp)); } // Agrego las columnas. status = CPXnewcols(env, lp, n, objfun, lb, ub, NULL, colnames); if (status) { cerr << "Problema agregando las variables CPXnewcols" << endl; exit(1); } // Libero las estructuras. for (int i = 0; i < n; i++) { delete[] colnames[i]; } delete[] ub; delete[] lb; delete[] objfun; delete[] xctype; delete[] colnames; // Restricciones: // (1) Nodos adyacentes tienen distinto color (cant_ejes * cant_colores_disp restricciones por <=) // (2) Cada nodo tiene a lo sumo un color (cant_nodos restricciones por <=) // (3) Solo un nodo de cada subconj. de la particion tiene color (cant. de subconj. de la particion restricciones por =) // (4) W_j = 1 sii "X_i_j = 1 para algún i" (cant_colores_disp restricciones por >=) // (5) W_j >= W_(j+1) (cant_colores_disp - 1 restricciones por >=) // => TOTAL: (cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion + cant_colores_disp + cant_colores_disp - 1) restricciones int ccnt = 0; //numero nuevo de columnas en las restricciones. int rcnt = cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion + cant_colores_disp + cant_colores_disp - 1; //cuantas restricciones se estan agregando. int nzcnt = 0; //# de coeficientes != 0 a ser agregados a la matriz. Solo se pasan los valores que no son cero. char sense[rcnt]; // Sentido de la desigualdad. 'G' es mayor o igual y 'E' para igualdad. for(unsigned int i = 0; i < cant_ejes * cant_colores_disp; i++) sense[i] = 'L'; for(unsigned int i = cant_ejes * cant_colores_disp; i < cant_ejes * cant_colores_disp + cant_nodos; i++) sense[i] = 'L'; for(unsigned int i = cant_ejes * cant_colores_disp + cant_nodos; i < cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion; i++) sense[i] = 'E'; for(unsigned int i = cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion; i < rcnt; i++) sense[i] = 'G'; 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*n]; // Array con los indices de las variables con coeficientes != 0 en la desigualdad. double *matval = new double[rcnt*n]; // Array que en la posicion i tiene coeficiente ( != 0) de la variable cutind[i] en la restriccion. //El termino indep. de restr (1), (2) y (3) es 1 for(unsigned int i = 0; i < cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion; i++) rhs[i] = 1; //El termino indep. de restr (4) y (5) es 0 for(unsigned int i = cant_ejes * cant_colores_disp + cant_nodos + cant_subconj_particion; i < rcnt; i++) rhs[i] = 0; unsigned int indice = 0; //numero de restriccion actual //Restricciones (1) for(unsigned int i = 0; i < cant_nodos; i++) //itero nodo 1 for(unsigned int j = i+1; j < cant_nodos; j++) //itero nodo 2 if((*adyacencias)[i][j]) for(unsigned int p = 0; p < cant_colores_disp; p++){ //itero color matbeg[indice] = nzcnt; indice++; //cargo una de las variables participantes de la restr. matind[nzcnt] = cant_colores_disp*i + p; //var1: X_nodo1_color matval[nzcnt] = 1; nzcnt++; //idem con la otra variable matind[nzcnt] = cant_colores_disp*j + p; //var2: X_nodo2_color matval[nzcnt] = 1; nzcnt++; } //Restricciones (2) for(unsigned int i = 0; i < cant_nodos; i++){ //itero nodo matbeg[indice] = nzcnt; indice++; for(unsigned int p = 0; p < cant_colores_disp; p++){ //itero color matind[nzcnt] = cant_colores_disp*i + p; //var: X_nodo_color matval[nzcnt] = 1; nzcnt++; } } //Restricciones (3) for(unsigned int v = 0; v < cant_subconj_particion; v++){ //itero subconjunto de la particion matbeg[indice] = nzcnt; indice++; for(unsigned int i = 0; i < cant_nodos; i++) //itero nodo if((*particion)[v][i]) for(unsigned int p = 0; p < cant_colores_disp; p++){ //itero color matind[nzcnt] = cant_colores_disp*i + p; //var: X_nodo_color matval[nzcnt] = 1; nzcnt++; } } //Restricciones (4) for(unsigned int p = 0; p < cant_colores_disp; p++){ //itero color matbeg[indice] = nzcnt; indice++; matind[nzcnt] = cant_nodos * cant_colores_disp + p; //var: W_color matval[nzcnt] = cant_nodos; nzcnt++; for(unsigned int i = 0; i < cant_nodos; i++){ //itero nodo matind[nzcnt] = cant_colores_disp*i + p; //var: X_nodo_color matval[nzcnt] = -1; nzcnt++; } } //Restricciones (5) for(unsigned int p = 0; p < cant_colores_disp - 1; p++){ //itero color matbeg[indice] = nzcnt; indice++; matind[nzcnt] = cant_nodos * cant_colores_disp + p; //var: W_color matval[nzcnt] = 1; nzcnt++; matind[nzcnt] = cant_nodos * cant_colores_disp + p + 1; //var: W_(color+1) matval[nzcnt] = -1; nzcnt++; } // Esta rutina agrega la restriccion 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; // Escribimos el problema a un archivo .lp status = CPXwriteprob(env, lp, "output.lp", NULL); if (status) { cerr << "Problema escribiendo modelo" << endl; exit(1); } //----------------------- PRIMER ITERACION DE RESOLUCIÓN DEL LP // Tomamos el tiempo de resolucion utilizando CPXgettime. double inittime, endtime, fractpart, intpart, opt_anterior, opt_actual; int cant_iteraciones = 0; status = CPXgettime(env, &inittime); bool criterio_de_corte, todas_enteras, hubo_plano = true; status = CPXlpopt(env, lp); if (status) { cerr << "Problema optimizando CPLEX" << endl; exit(1); } status = CPXgetobjval(env, lp, &opt_actual); if (status) { cerr << "Problema obteniendo valor de mejor solucion." << endl; exit(1); } cout << "Optimo Inicial: " << opt_actual << endl << endl; double *sol = new double[n]; status = CPXgetx(env, lp, sol, 0, n - 1); if (status) { cerr << "Problema obteniendo la solucion del LP." << endl; exit(1); } // Chequeo si la solución es entera for (int i = 0; i < n; i++){ fractpart = modf(sol[i] , &intpart); if (fractpart > TOL){ todas_enteras = false; break; } } criterio_de_corte = todas_enteras || max_iteraciones==0; //----------------------- INICIO CICLO DE RESOLUCIÓN DEL LP while(!criterio_de_corte){ opt_anterior = opt_actual; hubo_plano = agregar_restricciones_clique(adyacencias, sol, env, lp, cant_colores_disp, n); hubo_plano = agregar_restricciones_ciclos(adyacencias, sol, env, lp, cant_colores_disp, n) || hubo_plano; if(hubo_plano){ status = CPXlpopt(env, lp); if (status) { cerr << "Problema optimizando CPLEX" << endl; exit(1); } status = CPXgetx(env, lp, sol, 0, n - 1); if (status) { cerr << "Problema obteniendo la solucion del LP." << endl; exit(1); } for (int i = 0; i < n; i++){ fractpart = modf(sol[i] , &intpart); if (fractpart > TOL){ todas_enteras = false; break; } } } status = CPXgetobjval(env, lp, &opt_actual); if (status) { cerr << "Problema obteniendo valor de mejor solucion." << endl; exit(1); } cant_iteraciones++; criterio_de_corte = todas_enteras || (cant_iteraciones >= max_iteraciones) || !hubo_plano;// || abs(opt_actual - opt_anterior) < TOL; } status = CPXgettime(env, &endtime); //----------------------- FIN CICLO DE RESOLUCIÓN DEL LP 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!=CPX_STAT_OPTIMAL) exit(1); double objval; status = CPXgetobjval(env, lp, &objval); if (status) { cerr << "Problema obteniendo valor de mejor solucion." << endl; exit(1); } cout << "Optimo: " << objval << "\t(Time: " << (endtime - inittime) << " sec)" << endl; // Tomamos los valores de la solucion y los escribimos a un archivo. std::string outputfile = "output.sol"; ofstream solfile(outputfile.c_str()); // Tomamos los valores de todas las variables. Estan numeradas de 0 a n-1. status = CPXgetx(env, lp, sol, 0, n - 1); if (status) { cerr << "Problema obteniendo la solucion del LP." << endl; exit(1); } // Solo escribimos las variables distintas de cero (tolerancia, 1E-05). solfile << "Status de la solucion: " << statstr << endl; // Imprimo var X_n_j for (int i = 0; i < n - cant_colores_disp; i++) { if (sol[i] > TOL) { solfile << "X_" << i / cant_colores_disp << "_" << i % cant_colores_disp << " = " << sol[i] << endl; } } // Imprimo var W_j for (int i = n - cant_colores_disp; i < n; i++) { if (sol[i] > TOL) { solfile << "W_" << i - (n - cant_colores_disp) << " = " << sol[i] << endl; } } solfile.close(); delete [] sol; delete adyacencias; delete particion; return 0; }
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 */
int main (void) { /* Declare pointers for the variables and arrays that will contain the data which define the LP problem. The setproblemdata() routine allocates space for the problem data. */ char *probname = NULL; int numcols; int numrows; int objsen; double *obj = NULL; double *rhs = NULL; char *sense = NULL; int *matbeg = NULL; int *matcnt = NULL; int *matind = NULL; double *matval = NULL; double *lb = NULL; double *ub = NULL; /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Allocate memory and fill in the data for the problem. */ status = setproblemdata (&probname, &numcols, &numrows, &objsen, &obj, &rhs, &sense, &matbeg, &matcnt, &matind, &matval, &lb, &ub); if ( status ) { fprintf (stderr, "Failed to build problem data arrays.\n"); goto TERMINATE; } /* Create the problem. */ lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now copy the problem data into the lp */ status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, rhs, sense, matbeg, matcnt, matind, matval, lb, ub, NULL); if ( status ) { fprintf (stderr, "Failed to copy problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using what was passed to CPXcopylp. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } /* Free up the problem data arrays, if necessary. */ free_and_null ((char **) &probname); free_and_null ((char **) &obj); free_and_null ((char **) &rhs); free_and_null ((char **) &sense); free_and_null ((char **) &matbeg); free_and_null ((char **) &matcnt); free_and_null ((char **) &matind); free_and_null ((char **) &matval); free_and_null ((char **) &lb); free_and_null ((char **) &ub); return (status); } /* END main */
int 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 */