long CplexData::Delete() { if(lp != NULL) { CPXfreeprob(env, &lp); } if(env != NULL) { CPXcloseCPLEX(&env); } if(cpxfileptr != NULL) { CPXfclose(cpxfileptr); } ClearStructure(); return 0; }
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 (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 */
int main (int argc, char *argv[]) { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int numcols; double totinv; int solstat; double objval; double *x = NULL; double rrhs[1]; char rsense[1]; int rmatbeg[1]; int *indices = NULL; double *values = NULL; char *namestore = NULL; char **nameptr = NULL; int surplus, storespace; const char * datadir = argc <= 1 ? "../../../examples/data" : argv[1]; char *prod = NULL; prod = (char *) malloc (strlen (datadir) + 1 + strlen("prod.lp") + 1); sprintf (prod, "%s/prod.lp", datadir); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, "prod.lp"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, prod, NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Tell presolve to do only primal reductions, turn off simplex logging */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Reduce, 1); if ( status ) { fprintf (stderr, "Failed to set CPXPARAM_Preprocessing_Reduce: %d\n", status); goto TERMINATE; } status = CPXsetintparam (env, CPXPARAM_Simplex_Display, 0); if ( status ) { fprintf (stderr, "Failed to set CPXPARAM_Simplex_Display: %d\n", status); goto TERMINATE; } if ( status ) { fprintf (stderr, "Failure to set parameters\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize profit LP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status || solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "Solution failed. Status %d, solstat %d.\n", status, solstat); goto TERMINATE; } printf ("Profit objective value is %g\n", objval); /* Allocate space for column names */ numcols = CPXgetnumcols (env, lp); if ( !numcols ) { fprintf (stderr, "No columns in problem\n"); goto TERMINATE; } CPXgetcolname (env, lp, NULL, NULL, 0, &surplus, 0, numcols-1); storespace = - surplus; namestore = (char *) malloc (storespace * sizeof(char)); nameptr = (char **) malloc (numcols * sizeof(char *)); if ( namestore == NULL || nameptr == NULL ) { fprintf (stderr, "No memory for column names\n"); goto TERMINATE; } status = CPXgetcolname (env, lp, nameptr, namestore, storespace, &surplus, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to get column names\n"); goto TERMINATE; } /* Allocate space for solution */ x = (double *) malloc (numcols * sizeof(double)); if ( x == NULL ) { fprintf (stderr,"No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } totinv = 0; for (j = 0; j < numcols; j++) { if ( !strncmp (nameptr[j], "inv", 3) ) totinv += x[j]; } printf ("Inventory level under profit objective is %g\n", totinv); /* Allocate space for a constraint */ indices = (int *) malloc (numcols * sizeof (int)); values = (double *) malloc (numcols * sizeof (double)); if ( indices == NULL || values == NULL ) { fprintf (stderr, "No memory for constraint\n"); goto TERMINATE; } /* Get profit objective and add it as a constraint */ status = CPXgetobj (env, lp, values, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to get profit objective. Status %d\n", status); goto TERMINATE; } for (j = 0; j < numcols; j++) { indices[j] = j; } rrhs[0] = objval - fabs (objval) * 1e-6; rsense[0] = 'G'; rmatbeg[0] = 0; status = CPXpreaddrows (env, lp, 1, numcols, rrhs, rsense, rmatbeg, indices, values, NULL); if ( status ) { fprintf (stderr, "Failed to add objective as constraint. Status %d\n", status); goto TERMINATE; } /* Set up objective to maximize negative of sum of inventory */ totinv = 0; for (j = 0; j < numcols; j++) { if ( strncmp (nameptr[j], "inv", 3) ) { values[j] = 0.0; } else { values[j] = - 1.0; } } status = CPXprechgobj (env, lp, numcols, indices, values); if ( status ) { fprintf (stderr, "Failed to change to inventory objective. Status %d\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Optimization on inventory level failed. Status %d.\n", status); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status || solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "Solution failed. Status %d, solstat %d.\n", status, solstat); goto TERMINATE; } printf("Solution status %d.\n", solstat); printf ("Inventory level after optimization is %g\n", -objval); status = CPXgetx (env, lp, x, 0, numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } printf("Found solution"); /* Write out the solution */ printf ("\n"); for (j = 0; j < numcols; j++) { printf ( "%s: Value = %17.10g\n", nameptr[j], x[j]); } TERMINATE: /* Free the filename */ free_and_null ((char **) &prod); /* Free up the basis and solution */ free_and_null ((char **) &indices); free_and_null ((char **) &values); free_and_null ((char **) &nameptr); free_and_null ((char **) &namestore); free_and_null ((char **) &x); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int j; int cur_numcols; int wantorig = 1; int nameind = 1; /* Check the command line arguments */ if ( argc != 2 ) { if ( argc != 3 || argv[1][0] != '-' || argv[1][1] != 'r' ) { usage (argv[0]); goto TERMINATE; } wantorig = 0; nameind = 2; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[nameind]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[nameind], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( CPXgetnumcols (env, lp) != CPXgetnumbin (env, lp) ) { fprintf (stderr, "Problem contains non-binary variables, exiting\n"); goto TERMINATE; } /* Set parameters */ if ( wantorig ) { /* Assure linear mappings between the presolved and original models */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Linear, 0); if ( status ) goto TERMINATE; /* Let MIP callbacks work on the original model */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_CallbackReducedLP, CPX_OFF); if ( status ) goto TERMINATE; } status = CPXsetdblparam (env, CPXPARAM_MIP_Tolerances_MIPGap, (double) 1e-6); if ( status ) goto TERMINATE; /* Turn on traditional search for use with control callbacks */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_Search, CPX_MIPSEARCH_TRADITIONAL); if ( status ) goto TERMINATE; /* Set up to use MIP callback */ status = CPXsetheuristiccallbackfunc (env, rounddownheur, NULL); if ( status ) goto TERMINATE; /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, maximum bound violation, variable values, and basis. */ int solnstat, solnmethod, solntype; double objval, maxviol; double *x = NULL; int *cstat = NULL; int *rstat = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int cur_numrows, cur_numcols; char **cur_colname = NULL; char *cur_colnamestore = NULL; int cur_colnamespace; int surplus; int method; char *basismsg; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("podhbnsc", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ switch (argv[2][0]) { case 'o': method = CPX_ALG_AUTOMATIC; break; case 'p': method = CPX_ALG_PRIMAL; break; case 'd': method = CPX_ALG_DUAL; break; case 'n': method = CPX_ALG_NET; break; case 'h': method = CPX_ALG_BARRIER; break; case 'b': method = CPX_ALG_BARRIER; status = CPXsetintparam (env, CPXPARAM_Barrier_Crossover, CPX_ALG_NONE); if ( status ) { fprintf (stderr, "Failed to set the crossover method, error %d.\n", status); goto TERMINATE; } break; case 's': method = CPX_ALG_SIFTING; break; case 'c': method = CPX_ALG_CONCURRENT; break; default: method = CPX_ALG_NONE; break; } status = CPXsetintparam (env, CPXPARAM_LPMethod, method); if ( status ) { fprintf (stderr, "Failed to set the optimization method, error %d.\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } solnstat = CPXgetstat (env, lp); if ( solnstat == CPX_STAT_UNBOUNDED ) { printf ("Model is unbounded\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INFEASIBLE ) { printf ("Model is infeasible\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INForUNBD ) { printf ("Model is infeasible or unbounded\n"); goto TERMINATE; } status = CPXsolninfo (env, lp, &solnmethod, &solntype, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to obtain solution info.\n"); goto TERMINATE; } printf ("Solution status %d, solution method %d\n", solnstat, solnmethod); if ( solntype == CPX_NO_SOLN ) { fprintf (stderr, "Solution not available.\n"); goto TERMINATE; } status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g.\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numcols = CPXgetnumcols (env, lp); cur_numrows = CPXgetnumrows (env, lp); /* Retrieve basis, if one is available */ if ( solntype == CPX_BASIC_SOLN ) { cstat = (int *) malloc (cur_numcols*sizeof(int)); rstat = (int *) malloc (cur_numrows*sizeof(int)); if ( cstat == NULL || rstat == NULL ) { fprintf (stderr, "No memory for basis statuses.\n"); goto TERMINATE; } status = CPXgetbase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to get basis; error %d.\n", status); goto TERMINATE; } } else { printf ("No basis available\n"); } /* Retrieve solution vector */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } /* Now get the column names for the problem. First we determine how much space is used to hold the names, and then do the allocation. Then we call CPXgetcolname() to get the actual names. */ status = CPXgetcolname (env, lp, NULL, NULL, 0, &surplus, 0, cur_numcols-1); if (( status != CPXERR_NEGATIVE_SURPLUS ) && ( status != 0 ) ) { fprintf (stderr, "Could not determine amount of space for column names.\n"); goto TERMINATE; } cur_colnamespace = - surplus; if ( cur_colnamespace > 0 ) { cur_colname = (char **) malloc (sizeof(char *)*cur_numcols); cur_colnamestore = (char *) malloc (cur_colnamespace); if ( cur_colname == NULL || cur_colnamestore == NULL ) { fprintf (stderr, "Failed to get memory for column names.\n"); status = -1; goto TERMINATE; } status = CPXgetcolname (env, lp, cur_colname, cur_colnamestore, cur_colnamespace, &surplus, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "CPXgetcolname failed.\n"); goto TERMINATE; } } else { printf ("No names associated with problem. Using Fake names.\n"); } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( cur_colnamespace > 0 ) { printf ("%-16s: ", cur_colname[j]); } else { printf ("Fake%-6.6d : ", j);; } printf ("%17.10g", x[j]); if ( cstat != NULL ) { switch (cstat[j]) { case CPX_AT_LOWER: basismsg = "Nonbasic at lower bound"; break; case CPX_BASIC: basismsg = "Basic"; break; case CPX_AT_UPPER: basismsg = "Nonbasic at upper bound"; break; case CPX_FREE_SUPER: basismsg = "Superbasic, or free variable at zero"; break; default: basismsg = "Bad basis status"; break; } printf (" %s",basismsg); } printf ("\n"); } /* Display the maximum bound violation. */ status = CPXgetdblquality (env, lp, &maxviol, CPX_MAX_PRIMAL_INFEAS); if ( status ) { fprintf (stderr, "Failed to obtain bound violation.\n"); goto TERMINATE; } printf ("Maximum bound violation = %17.10g\n", maxviol); TERMINATE: /* Free up the basis and solution */ free_and_null ((char **) &cstat); free_and_null ((char **) &rstat); free_and_null ((char **) &x); free_and_null ((char **) &cur_colname); free_and_null ((char **) &cur_colnamestore); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, and variable values. */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int j; int cur_numcols; /* Check the command line arguments */ if ( argc != 2 ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numcols stores the current number of columns. */ cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } TERMINATE: /* Free up the solution */ free_and_null ((char **) &x); /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (void) { char probname[16]; /* Problem name is max 16 characters */ int cstat[NUMCOLS]; int rstat[NUMROWS]; /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ strcpy (probname, "example"); lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. */ status = populatebycolumn (env, lp); if ( status ) { fprintf (stderr, "Failed to populate problem data.\n"); goto TERMINATE; } /* We assume we know the optimal basis. Variables 1 and 2 are basic, while variable 0 is at its upper bound */ cstat[0] = CPX_AT_UPPER; cstat[1] = CPX_BASIC; cstat[2] = CPX_BASIC; /* The row statuses are all nonbasic for this problem */ rstat[0] = CPX_AT_LOWER; rstat[1] = CPX_AT_LOWER; /* Now copy the basis */ status = CPXcopybase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to copy the basis.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n", objval); printf ("Iteration count = %d\n\n", CPXgetitcnt (env, lp)); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex6.sav", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int TSPSolver::resolve(string dataFile, string problemFile, string resultFile) { int result = -1; std::chrono::time_point<std::chrono::system_clock> start; std::chrono::time_point<std::chrono::system_clock> end; if(resultFile != "") { try { //Read the problem datas from a .dat files this->readProblemDatas(dataFile); //Environment initialization DECL_ENV(env); DECL_PROB(env, lp); //Setup the objective function this->setObjectiveFunction(env, lp); //Setup the problem constraints this->setConstraint_1(env, lp); this->setConstraint_2(env, lp); this->setConstraint_3(env, lp); this->setConstraint_4(env, lp); this->setConstraint_5(env, lp); if(problemFile != "") { //Print the file with the problem CHECKED_CPX_CALL(CPXwriteprob, env, lp, problemFile.c_str(), NULL); } //Save the time before the problem is resolved start = std::chrono::system_clock::now(); //Resolve the problem CHECKED_CPX_CALL(CPXmipopt, env, lp); //Save the time after the problem is solved end = std::chrono::system_clock::now(); if(resultFile != "") { //Print the file with the result of the problem CHECKED_CPX_CALL(CPXsolwrite, env, lp, resultFile.c_str()); } //Environment finalization CPXfreeprob(env, &lp); CPXcloseCPLEX(&env); //Print the time spent in search of the solution this->printTime(start, end); result = 0; } catch(exception &ex) { cout << "EXCEPTION -> " << ex.what() << endl; result = -1; } } return result; }
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; }
int main (void) { CPXENVptr env; CPXLPptr lp = NULL; int *cone = NULL; int status; CPXCHANNELptr resc, warnc, errc, logc; int retval = -1; /* Initialize CPLEX and get a reference to the output channels. * If any of this fails immediately terminate the program. */ env = CPXopenCPLEX (&status); if ( env == NULL || status != 0 ) abort (); status = CPXgetchannels (env, &resc, &warnc, &errc, &logc); if ( status != 0 ) abort (); /* CPLEX is fully setup. Enable output. */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) goto TERMINATE; /* Create model. */ lp = CPXcreateprob (env, &status, "xsocpex1"); if ( lp == NULL || status != 0 ) goto TERMINATE; if ( !createmodel (env, lp, &cone) ) goto TERMINATE; /* Solve the problem to optimality. */ CPXmsg (logc, "Optimizing ...\n"); status = CPXsetdblparam (env, CPXPARAM_Barrier_QCPConvergeTol, CONVTOL); if ( status != 0 ) goto TERMINATE; if ( (status = CPXhybbaropt (env, lp, CPX_ALG_NONE)) != 0 ) goto TERMINATE; if ( CPXgetstat (env, lp) != CPX_STAT_OPTIMAL ) { CPXmsg (errc, "Cannot test KKT conditions on non-optimal solution.\n"); goto TERMINATE; } /* Now test KKT conditions on the result. */ if ( !checkkkt (env, lp, cone, TESTTOL) ) { CPXmsg (logc, "Testing of KKT conditions failed.\n"); CPXmsg (errc, "Testing of KKT conditions failed.\n"); goto TERMINATE; } CPXmsg (resc, "KKT conditions are satisfied.\n"); retval = 0; TERMINATE: free (cone); if ( lp != NULL ) CPXfreeprob (env, &lp); CPXcloseCPLEX (&env); return retval; }
reducemex(double M[], double costs[], double stats[], double ikeep[], double m[], int matbeg[], int matcnt[], int matind[], double matval[], char sense[], int objsen, double lb[], double ub[], int numrows, int numcols, double tol) { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; char probname[16]; double *pi; double *slack; double *dj; double *obj; int solstat; double objval; double *x; double newval; int *indices; int kc, i; obj = mxCalloc(numcols,sizeof(double)); x = mxCalloc(numcols,sizeof(double)); indices = mxCalloc(numcols,sizeof(int)); pi = mxCalloc(numrows,sizeof(double)); slack = mxCalloc(numrows,sizeof(double)); dj = mxCalloc(numcols,sizeof(double)); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[1024]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn off output to the screen */ status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn off pre-processor status = CPXsetintparam (env, CPX_PARAM_PREIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn off pre-processor, error %d.\n", status); goto TERMINATE; } /* Turn off aggregator status = CPXsetintparam (env, CPX_PARAM_AGGIND, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn of aggregator, error %d.\n", status); goto TERMINATE; }*/ /* Create the problem. */ strcpy(probname,"LPnoname"); lp = CPXcreateprob (env, &status, probname); if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Initialize data */ for (kc = 0; kc <= numcols-1; kc++) { indices[kc] = kc; } /* Now copy the problem data into the lp */ status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, m, sense, matbeg, matcnt, matind, matval, lb, ub, NULL); if ( status ) { fprintf (stderr, "Failed to copy problem data.\n"); goto TERMINATE; } /**********MAIN LOOP************/ for(i = 0; i <= numrows-1; i++) { for (kc = 0; kc <= numcols-1; kc++) { obj[kc] = M[i+kc*numrows]; } CPXchgobj(env, lp, numcols, indices, obj); newval = m[i] + 10; CPXchgrhs(env, lp, 1, &i, &newval); /* Optimize the problem and obtain solution. */ status = CPXlpopt (env, lp); /*status = CPX[prim/dual]opt (env, lp);*/ if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } ikeep[i] = 0; if (objval > m[i] + tol) /* keep row */ { ikeep[i] = 1; newval = m[i]; CPXchgrhs(env, lp, 1, &i, &newval); } /* Write the output to the screen. */ /* printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); */ costs[i] = objval; stats[i] = solstat; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); if ( status ) { char errmsg[1024]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } }
/* 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); }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int i, j; double *c=NULL, *b=NULL, *A=NULL, *H=NULL, *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ; int *nzA=NULL, *nzH=NULL ; int *iA=NULL, *kA=NULL ; int *iH=NULL, *kH=NULL ; #ifndef MX_COMPAT_32 long *iA_=NULL, *kA_=NULL ; long *iH_=NULL, *kH_=NULL ; #endif int neq=0, m=0, n=0, display=0; long *cpenv=NULL, *p_qp=NULL; char *Sense=NULL ; CPXENVptr env = NULL; CPXLPptr qp = NULL; int status, qpstat; double objval; double * p_qpstat ; char opt_method[128]="auto" ; if (nrhs > 10 || nrhs < 1) { mexErrMsgTxt("Usage: [x,lambda,how,p_qp] " "= qp_solve(cpenv,Q,c,A,b,l,u,neq,disp,method)"); return; } switch (nrhs) { case 10: if (mxGetM(prhs[9]) != 0 || mxGetN(prhs[9]) != 0) { if (mxIsNumeric(prhs[9]) || mxIsComplex(prhs[9]) || !mxIsChar(prhs[9]) || mxIsSparse(prhs[9]) || !(mxGetM(prhs[9])==1 && mxGetN(prhs[9])>=1)) { mexErrMsgTxt("10th argument (method) must be " "a string."); return; } mxGetString(prhs[9], opt_method, 128) ; } case 9: if (mxGetM(prhs[8]) != 0 || mxGetN(prhs[8]) != 0) { if (!mxIsNumeric(prhs[8]) || mxIsComplex(prhs[8]) || mxIsSparse(prhs[8]) || !(mxGetM(prhs[8])==1 && mxGetN(prhs[8])==1)) { mexErrMsgTxt("9th argument (display) must be " "an integer scalar."); return; } display = *mxGetPr(prhs[8]); } case 8: if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) { if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7]) || mxIsSparse(prhs[7]) || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) { mexErrMsgTxt("8th argument (neqcstr) must be " "an integer scalar."); return; } neq = *mxGetPr(prhs[7]); } case 7: if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) { if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6]) || mxIsSparse(prhs[6]) || !mxIsDouble(prhs[6]) || mxGetN(prhs[6])!=1 ) { mexErrMsgTxt("7th argument (u) must be " "a column vector."); return; } u = mxGetPr(prhs[6]); n = mxGetM(prhs[6]); } case 6: if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) { if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) || mxIsSparse(prhs[5]) || !mxIsDouble(prhs[5]) || mxGetN(prhs[5])!=1 ) { mexErrMsgTxt("6th argument (l) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[5])) { mexErrMsgTxt("Dimension error (arg 6 and later)."); return; } l = mxGetPr(prhs[5]); n = mxGetM(prhs[5]); } case 5: if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) { if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 ) { mexErrMsgTxt("5th argument (b) must be " "a column vector."); return; } if (m != 0 && m != mxGetM(prhs[4])) { mexErrMsgTxt("Dimension error (arg 5 and later)."); return; } b = mxGetPr(prhs[4]); m = mxGetM(prhs[4]); } case 4: if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || !mxIsSparse(prhs[3]) ) { mexErrMsgTxt("4th argument (A) must be " "a sparse matrix."); return; } if (m != 0 && m != mxGetM(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } if (n != 0 && n != mxGetN(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } m = mxGetM(prhs[3]); n = mxGetN(prhs[3]); A = mxGetPr(prhs[3]); #ifdef MX_COMPAT_32 iA = mxGetIr(prhs[3]); kA = mxGetJc(prhs[3]); #else iA_ = mxGetIr(prhs[3]); kA_ = mxGetJc(prhs[3]); iA = (int*)malloc(mxGetNzmax(prhs[3])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[3]); i++) iA[i]=iA_[i] ; kA = (int*)malloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kA[i]=kA_[i] ; #endif nzA=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzA[i]=kA[i+1]-kA[i] ; Sense=myMalloc((m+1)*sizeof(char)) ; for (i=0; i<m; i++) if (i<neq) Sense[i]='E' ; else Sense[i]='L' ; Sense[m]=0 ; } case 3: if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) { if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2]) || mxGetN(prhs[2])!=1 ) { mexErrMsgTxt("3rd argument (c) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } c = mxGetPr(prhs[2]); n = mxGetM(prhs[2]); } case 2: if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || !mxIsSparse(prhs[1]) ) { mexErrMsgTxt("2nd argument (H) must be " "a sparse matrix."); return; } if (n != 0 && n != mxGetM(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } if (n != 0 && n != mxGetN(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } n = mxGetN(prhs[1]); H = mxGetPr(prhs[1]); #ifdef MX_COMPAT_32 iH = mxGetIr(prhs[1]); kH = mxGetJc(prhs[1]); #else iH_ = mxGetIr(prhs[1]); kH_ = mxGetJc(prhs[1]); iH = (int*)malloc(mxGetNzmax(prhs[1])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[1]); i++) iH[i]=iH_[i] ; kH = (int*)malloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kH[i]=kH_[i] ; #endif nzH=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzH[i]=kH[i+1]-kH[i] ; } case 1: if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) { if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxGetN(prhs[0])!=1 ) { mexErrMsgTxt("1st argument (cpenv) must be " "a column vector."); return; } if (1 != mxGetM(prhs[0])) { mexErrMsgTxt("Dimension error (arg 1)."); return; } cpenv = (long*) mxGetPr(prhs[0]); } } /*if (display>3) */ fprintf(STD_OUT,"argument processing finished") ; /* Initialize the CPLEX environment */ env = (CPXENVptr) cpenv[0] ; /* Turn on output to the screen */ if (display>0) status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); else status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF); if ( status ) { fprintf (STD_OUT, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, display); if ( status ) { fprintf (STD_OUT,"Failed to turn up simplex display level.\n"); goto TERMINATE; } if (nlhs > 4 || nlhs < 1) { mexErrMsgTxt("Usage: [x,lambda,how,p_qp] " "= qp_solve(cpenv,H,c,A,b,l,u,neqcstr)"); return; } if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ; switch (nlhs) { case 4: plhs[3] = mxCreateDoubleMatrix(1, 1, mxREAL); p_qp = (long*) mxGetPr(plhs[3]); case 3: /* plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL); p_qpstat = mxGetPr(plhs[2]);*/ case 2: plhs[1] = mxCreateDoubleMatrix(m, 1, mxREAL); lambda = mxGetPr(plhs[1]); case 1: plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL); x = mxGetPr(plhs[0]); break; } if (display>2) fprintf(STD_OUT, "argument processing finished\n") ; if (strcmp(opt_method, "primal") && strcmp(opt_method, "dual") && strcmp(opt_method, "net") && strcmp(opt_method, "bar") && strcmp(opt_method, "sift") && strcmp(opt_method, "con") && strcmp(opt_method, "auto")) mexErrMsgTxt("method \\in " "{'auto','primal','dual','bar','net','sift','con'}\n") ; if (strcmp(opt_method, "primal")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 1); else if (strcmp(opt_method, "dual")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 2); else if (strcmp(opt_method, "net")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 3); else if (strcmp(opt_method, "bar")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 4); else if (strcmp(opt_method, "sift")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 5); else if (strcmp(opt_method, "con")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 6); else if (strcmp(opt_method, "auto")==0) status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 0); else status = 1 ; if ( status ) { fprintf (STD_OUT,"Failed to set QP method.\n"); goto TERMINATE; } /* Create the problem */ if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ; qp = CPXcreateprob (env, &status, "xxx"); if ( qp == NULL ) { fprintf (STD_OUT,"Failed to create subproblem\n"); status = 1; goto TERMINATE; } if (p_qp) *p_qp=(long) qp ; /* Copy network part of problem. */ /*if (display>2) */ fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ; status = CPXcopylp(env, qp, n, m, CPX_MIN, c, b, Sense, kA, nzA, iA, A, l, u, NULL); if ( status ) { fprintf (STD_OUT, "CPXcopylp failed.\n"); goto TERMINATE; } /*if (display>2) */ fprintf(STD_OUT, "calling CPXcopyquad \n") ; status = CPXcopyquad (env, qp, kH, nzH, iH, H); if ( status ) { fprintf (STD_OUT, "CPXcopyquad failed.\n"); goto TERMINATE; } /*if (display>2) */ fprintf(STD_OUT, "calling optimizer 'bar'\n") ; status = CPXqpopt (env, qp); if (display>3) fprintf(STD_OUT, "CPXbaropt=%i\n", status) ; if ( status ) { fprintf (STD_OUT,"CPXbaropt failed.\n"); goto TERMINATE; } if (display>2) fprintf(STD_OUT, "calling CPXsolution\n") ; status = CPXsolution (env, qp, &qpstat, &objval, x, lambda, NULL, NULL); if ( status ) { fprintf (STD_OUT,"CPXsolution failed.\n"); goto TERMINATE; } if (display>1) fprintf (STD_OUT, "Solution status: %i,%s\n", qpstat, err_str[qpstat]); if (display>2) fprintf (STD_OUT, "Objective value %g\n", objval); if (nlhs >= 3) if (qpstat==1) plhs[2] = mxCreateString(err_str[0]) ; else plhs[2] = mxCreateString(err_str[qpstat]) ; /* if (nlhs >= 3) if (qpstat==1) *p_qpstat = 0 ; else *p_qpstat = qpstat ;*/ TERMINATE: if (status) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (STD_OUT, "%s", errmsg); if (nlhs >= 3) plhs[2] = mxCreateString(errmsg) ; } ; if (nzA) myFree(nzA) ; if (nzH) myFree(nzH) ; if (Sense) myFree(Sense) ; #ifndef MX_COMPAT_32 if (iA) myFree(iA) ; if (kA) myFree(kA) ; if (iH) myFree(iH) ; if (kH) myFree(kH) ; #endif if (!p_qp) { if ( qp != NULL ) { if (display>2) fprintf(STD_OUT, "calling CPXfreeprob\n") ; status = CPXfreeprob (env, &qp); if ( status ) { fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status); } } } return ; }
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; }
extern int solve_allocation(int nodeSize, int windowSize, int timeout, sched_nodeinfo_t *node_array, solver_job_list_t *job_array) { solver_job_list_t *sjob_ptr; struct job_details *job_det_ptr; int solstat; int n = windowSize, m = nodeSize; 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, k; int cur_numrows, cur_numcols; char envstr[256]; sprintf(envstr,"ILOG_LICENSE_FILE=%s",get_cplex_license_address()); if ( envstr != NULL ) { CPXputenv (envstr); } env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[1024]; fatal ("Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); if (status) { fatal("Failure to turn on screen indicator, error %d.",status); goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_DATACHECK, CPX_ON); if (status) { fatal("Failure to turn on data checking, error %d.", status); goto TERMINATE; } lp = CPXcreateprob (env, &status, "lpex1"); if (lp == NULL) { fatal("Failed to create LP."); goto TERMINATE; } status = CPXsetdblparam(env,CPX_PARAM_TILIM,timeout); status = populatebynonzero (env, lp, m, n, timeout, node_array, job_array); if ( status ) { fprintf (stderr, "Failed to populate problem."); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP."); goto TERMINATE; } cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof(double)); slack = (double *) malloc (cur_numrows * sizeof(double)); dj = (double *) malloc (cur_numcols * sizeof(double)); pi = (double *) malloc (cur_numrows * sizeof(double)); if ( x == NULL || slack == NULL || dj == NULL || pi == NULL ) { status = CPXERR_NO_MEMORY; fatal ("Could not allocate memory for solution."); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fatal ("Failed to obtain solution."); goto TERMINATE; } for (j = 0; j < windowSize; j++) { if (x[j] > 0) { sjob_ptr = &job_array[j]; job_det_ptr = sjob_ptr->job_ptr->details; sjob_ptr->node_bitmap = (bitstr_t *) bit_alloc (node_record_count); job_det_ptr->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); sjob_ptr->onnodes = (uint32_t *) xmalloc (sizeof(uint32_t) * node_record_count); job_det_ptr->req_node_layout = (uint16_t *) xmalloc (sizeof(uint16_t) * node_record_count); job_det_ptr->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); for (i = 0; i < nodeSize; i++) { k = (1 + i) * windowSize + j; if (x[k] > 0) { bit_set (sjob_ptr->node_bitmap, (bitoff_t) (i)); bit_set (job_det_ptr->req_node_bitmap, (bitoff_t) (i)); node_array[i].rem_cpus -= x[k]; node_array[i].rem_gpus -= sjob_ptr->gpu; sjob_ptr->onnodes[i] = x[k]; job_det_ptr->req_node_layout[i] = sjob_ptr->onnodes[i]; sjob_ptr->alloc_total += x[k]; } } } else job_array[j].alloc_total = 0; } TERMINATE: free_and_null ((char **) &x); free_and_null ((char **) &slack); free_and_null ((char **) &dj); free_and_null ((char **) &pi); if (lp != NULL) { status = CPXfreeprob (env, &lp); if (status) { fatal("CPXfreeprob failed, error code %d.", status); } } if (env != NULL) { status = CPXcloseCPLEX (&env); if (status) { char errmsg[1024]; fatal("Could not close CPLEX environment."); CPXgeterrorstring (env, status, errmsg); fatal("%s", errmsg); } } return (status); }
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval, relobj; double *x = NULL; MYCB info; CPXENVptr env = NULL; CPXLPptr lp = NULL; CPXLPptr lpclone = NULL; int j; int cur_numcols; /* Check the command line arguments */ if ( argc != 2 ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Turn on traditional search for use with control callbacks */ status = CPXsetintparam (env, CPXPARAM_MIP_Strategy_Search, CPX_MIPSEARCH_TRADITIONAL); if ( status ) goto TERMINATE; /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* We transfer a problem with semi-continuous or semi-integer variables to a MIP problem by adding variables and constraints. So in MIP callbacks, the size of the problem is changed and this example won't work for such problems */ if ( CPXgetnumsemicont (env, lp) + CPXgetnumsemiint (env, lp) ) { fprintf (stderr, "Not for problems with semi-continuous or semi-integer variables.\n"); goto TERMINATE; } /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numcols store the current number of columns */ cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "Memory allocation failed.\n"); goto TERMINATE; } /* Solve relaxation of MIP */ /* Clone original model */ lpclone = CPXcloneprob (env, lp, &status); if ( status ) { fprintf (stderr, "Failed to clone problem.\n"); goto TERMINATE; } /* Relax */ status = CPXchgprobtype (env, lpclone, CPXPROB_LP); if ( status ) { fprintf (stderr, "Failed to relax problem.\n"); goto TERMINATE; } /* Solve LP relaxation of original model using "default" LP solver */ status = CPXlpopt (env, lpclone); if ( status ) { fprintf (stderr, "Failed to solve relaxation.\n"); goto TERMINATE; } status = CPXsolution (env, lpclone, NULL, &relobj, x, NULL, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to extract solution.\n"); goto TERMINATE; } printf ("Solution status = %d", CPXgetstat(env,lpclone)); printf ("\nLP relaxation objective: %.4e\n\n", relobj); /* Set up solve callback */ info.count = 0; info.mip = lp; info.relx = x; status = CPXsetsolvecallbackfunc (env, &solvecallback, (void *) &info); if ( status ) { fprintf (stderr, "Failed to set solve callback.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Solution status %d.\n", solstat); printf ("Objective value %.10g\n", objval); status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ( "Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the cloned lp as allocated by CPXcloneprob, if necessary */ if ( lpclone != NULL ) { status = CPXfreeprob (env, &lpclone); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int 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 (int argc, char * argv[]) { // Temporary variables struct stat filestat; char astring[DDSIP_ln_fname]; int status = 0, cont, boundstat, comb, i; // guarantee minimal stacksize limit const rlim_t kStackSize = 128 * 1024 * 1024; // min stack size = 128 MB struct rlimit rl; int result; unsigned long cur_limit; result = getrlimit(RLIMIT_STACK, &rl); if (result == 0) { cur_limit = rl.rlim_cur; printf ("original stacksize limit %lu\n", cur_limit); if (rl.rlim_cur < kStackSize) { rl.rlim_cur = kStackSize; result = setrlimit(RLIMIT_STACK, &rl); if (result != 0) { fprintf(stderr, "setrlimit returned result = %d\n", result); } result = getrlimit(RLIMIT_STACK, &rl); if (result == 0) { cur_limit = rl.rlim_cur; printf ("changed stacksize limit %lu\n", cur_limit); } } } i = argc; // // Welcome printf ("#######################################################################################\n"); printf ("######### D D S I P -- Dual Decomposition In Stochastic Integer Programming #########\n"); printf ("######### %-66s #########\n", DDSIP_version); printf ("For copyright, license agreements, help, comments, requests, ... "); printf ("see\n\thttp://www.uni-duisburg-essen.de/~hn215go/ddsip.shtml\n"); printf ("\thttp://www.www.github.com/RalfGollmer/ddsip\n"); /* printf (" Copyright (C) to University of Duisburg-Essen \n\n"); */ /* printf(" This program is free software; you can redistribute it and/or\n"); */ /* printf (" modify it under the terms of the GNU General Public License\n"); */ /* printf(" as published by the Free Software Foundation; either version 2\n"); */ /* printf (" of the License, or (at your option) any later version.\n\n"); */ /* printf (" This program is distributed in the hope that it will be useful,\n"); */ /* printf(" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); */ /* printf (" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); */ /* printf (" GNU General Public License for more details.\n\n"); */ /* printf (" You should have received a copy of the GNU General Public License\n"); */ /* printf(" along with this program; if not, write to the Free Software\n"); */ /* printf (" Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n"); */ /* printf ("==============================================================================\n\n"); */ // These four structures shall carry the whole problem data DDSIP_param = NULL; DDSIP_bb = NULL; DDSIP_data = NULL; DDSIP_node = NULL; // In DDSIP some signals are handled seperatly DDSIP_RegisterSignalHandlers (); // Create output directory if it doesn't already exist if (stat (DDSIP_outdir, &filestat) == -1) { sprintf (astring, "mkdir %s\n", DDSIP_outdir); i = system (astring); printf ("Creating subdirectory %s ...\n", DDSIP_outdir); } // remove possibly existing output file sprintf (astring, "rm -f %s\n", DDSIP_outfname); i = system (astring); // Open output file if ((DDSIP_outfile = fopen (DDSIP_outfname, "a")) == NULL) { fprintf (stderr, "ERROR: Cannot open '%s'. \n", DDSIP_outfname); status = 107; goto TERMINATE; } setbuf (DDSIP_outfile, 0); fprintf (DDSIP_outfile, "%s\n", argv[0]); fprintf (DDSIP_outfile, "-----------------------------------------------------------\n"); fprintf (DDSIP_outfile, "current system time: "); fflush (DDSIP_outfile); #ifndef _WIN32 i = system ("date"); // Print time to output file sprintf (astring, "date >> %s\n", DDSIP_outfname); i = system (astring); fprintf (DDSIP_outfile, "host : "); sprintf (astring, "hostname >> %s; cat /proc/cpuinfo | sed '/processor.*: 0/,/^$/!d' |grep -E 'vendor|cpu |model|stepping|MHz|cache |cores' >> %s\n", DDSIP_outfname, DDSIP_outfname); for (i = 0; i < 100; i++) exp(1.11*(-i-2)); i = system (astring); #else sprintf (astring, "date /T >> %s & time /T >> %s\n", DDSIP_outfname,DDSIP_outfname); i = system (astring); #endif fprintf (DDSIP_outfile, "\nDDSIP %s\n", DDSIP_version); fprintf (DDSIP_outfile, "-----------------------------------------------------------\n"); // Open cplex environment DDSIP_env = CPXopenCPLEX (&status); if (DDSIP_env == NULL) { fprintf (stderr, "ERROR: Failed to open cplex environment, CPLEX error code %d.\n",status); fprintf (DDSIP_outfile, "ERROR: Failed to open cplex environment, CPLEX error code %d.\n",status); return status; } sprintf (astring, "%s", CPXversion (DDSIP_env)); printf ("CPLEX version is %s\n", astring); fprintf (DDSIP_outfile, "CPLEX version is %s\n\n", astring); // Allocate the structures to hold the information on the problem DDSIP_param = (para_t *) DDSIP_Alloc (sizeof (para_t), 1, "param(Main)"); DDSIP_bb = (bb_t *) DDSIP_Alloc (sizeof (bb_t), 1, "bb(Main)"); DDSIP_data = (data_t *) DDSIP_Alloc (sizeof (data_t), 1, "data(Main)"); // Read model (lp) file if ((status = DDSIP_ReadModel ())) goto TERMINATE; // Read specification file if ((status = DDSIP_ReadSpec ())) goto TERMINATE; // Set specified CPLEX parameters if ((status = DDSIP_InitCpxPara ())) goto TERMINATE; // if a Benders annotation file is given, read it if (DDSIP_param->annotationFile) { status = CPXreadcopyannotations (DDSIP_env, DDSIP_lp, DDSIP_param->annotationFile); if ( status ) { fprintf (stderr, "ERROR: Failed to read and copy the annotation data from file %s.\n", DDSIP_param->annotationFile); fprintf (DDSIP_outfile, "ERROR: Failed to read and copy the annotation data from file %s.\n", DDSIP_param->annotationFile); goto TERMINATE; } } // data->cost contains: stoch. costs for all scenarios, followed by the original costs DDSIP_data->cost = (double *) DDSIP_Alloc (sizeof (double), DDSIP_param->scenarios * DDSIP_param->stoccost + DDSIP_data->novar, "cost (ReadData)"); // Store original objective coefficients status = CPXgetobj (DDSIP_env, DDSIP_lp, DDSIP_data->cost + DDSIP_param->scenarios * DDSIP_param->stoccost, 0, DDSIP_data->novar - 1); if (status) { fprintf (stderr, "ERROR: Failed to get objective coefficients\n"); fprintf (DDSIP_outfile, "ERROR: Failed to get objective coefficients\n"); goto TERMINATE; } DDSIP_bb->moreoutfile = NULL; if (DDSIP_param->outlev) { // Open debug output file if ((DDSIP_bb->moreoutfile = fopen (DDSIP_moreoutfname, "a")) == NULL) { fprintf (stderr, "ERROR: Cannot open '%s'. \n", DDSIP_moreoutfname); fprintf (DDSIP_outfile, "ERROR: Cannot open '%s'. \n", DDSIP_moreoutfname); status = 109; goto TERMINATE; } if (DDSIP_param->outlev > 10) { // Buffer size = 0 setbuf (stdout, 0); if (DDSIP_param->outlev > 20) setbuf (DDSIP_bb->moreoutfile, 0); } #ifndef _WIN32 // Print time to output file sprintf (astring, "date > %s\n", DDSIP_moreoutfname); i = system (astring); #else sprintf (astring, "date /T > %s & time /T >> %s\n", DDSIP_moreoutfname,DDSIP_moreoutfname); i = system (astring); #endif fprintf (DDSIP_bb->moreoutfile, "--------------------------------------------------------------"); fprintf (DDSIP_bb->moreoutfile, "---------\nThis is an additional output file of DDSIP. The "); fprintf (DDSIP_bb->moreoutfile, "actual amount of output\nis controlled by the parameter "); fprintf (DDSIP_bb->moreoutfile, "OUTLEV in the specification file.\n---------"); fprintf (DDSIP_bb->moreoutfile, "--------------------------------------------------------------\n\n"); } DDSIP_node = (node_t **) DDSIP_Alloc (sizeof (node_t *), DDSIP_param->nodelim + 3, "node(Main)"); DDSIP_node[0] = (node_t *) DDSIP_Alloc (sizeof (node_t), 1, "node[0](Main)"); DDSIP_node[0]->first_sol = (double **) DDSIP_Alloc (sizeof (double *), DDSIP_param->scenarios, "node[0]->first_sol(Main)"); DDSIP_node[0]->cursubsol = (double *) DDSIP_Alloc (sizeof (double), DDSIP_param->scenarios, "node[0]->cursubsol(Main)"); DDSIP_node[0]->subbound = (double *) DDSIP_Alloc (sizeof (double), DDSIP_param->scenarios, "node[0]->subbound(Main)"); if (DDSIP_param->cb) { DDSIP_node[0]->scenBoundsNoLag = (double *) DDSIP_Alloc (sizeof (double), DDSIP_param->scenarios, "node[0]->scenBoundsNoLag(Main)"); DDSIP_node[0]->BoundNoLag = -DDSIP_infty; } DDSIP_node[0]->mipstatus = (int *) DDSIP_Alloc (sizeof (int), DDSIP_param->scenarios, "node[0]->mipstatus(Main)"); DDSIP_node[0]->ref_scenobj = (double *) DDSIP_Alloc (sizeof (double), DDSIP_param->scenarios, "node[0]->ref_scenobj(Main)"); // Prepare first and second stage variables if ((status = DDSIP_InitStages ())) { fprintf (stderr, "ERROR: Failed to initialize stages\n"); fprintf (DDSIP_outfile, "ERROR: Failed to initialize stages\n"); goto TERMINATE; } // Read data file(s) if ((status = DDSIP_ReadData ())) goto TERMINATE; // Read order file if specified if (DDSIP_param->cpxorder) { status = CPXsetintparam (DDSIP_env, CPX_PARAM_MIPORDIND, 1); if (status) { fprintf (stderr, "ERROR: Failed to set cplex parameter CPX_PARAM_MIPORDIND.\n"); return status; } if (DDSIP_ReadCPLEXOrder ()) goto TERMINATE; } // Detect first and second stage constraints if ((status = DDSIP_DetectStageRows ())) { fprintf (stderr, "ERROR: Failed detection of row stages (BbInit)\n"); fprintf (DDSIP_outfile, "ERROR: Failed detection of row stages (BbInit)\n"); goto TERMINATE; } DDSIP_bb->DDSIP_step = solve; #ifdef CONIC_BUNDLE if (DDSIP_param->cb) { status = DDSIP_NonAnt (); if (status) goto TERMINATE; } #endif if (DDSIP_param->outlev) { printf ("\t Total initialization time: %4.2f seconds.\n", DDSIP_GetCpuTime ()); fprintf (DDSIP_bb->moreoutfile, " Total initialization time: %4.2f seconds.\n", DDSIP_GetCpuTime ()); } #ifndef _WIN32 sprintf (astring, "grep 'MHz' /proc/cpuinfo|sort -r|head -1 >> %s\n", DDSIP_outfname); i = system (astring); #endif // at the start there is no solution status = CPXsetintparam (DDSIP_env, CPX_PARAM_ADVIND, 0); if (status) { fprintf (stderr, "ERROR: Failed to set cplex parameter CPX_PARAM_ADVIND.\n"); fprintf (DDSIP_outfile, "ERROR: Failed to set cplex parameter CPX_PARAM_ADVIND.\n"); return status; } #ifndef NEOS // Write deterministic equivalent (only expectation-based cases) if (DDSIP_param->write_detequ) DDSIP_DetEqu (); #endif if (DDSIP_param->riskmod < 0) { fprintf (stderr, " pure risk models are disabled for now, exiting.\n"); fprintf (DDSIP_outfile, " pure risk models are disabled for now, exiting.\n"); goto TERMINATE; } if (DDSIP_param->stoccost && DDSIP_param->riskmod) { fprintf (DDSIP_outfile, "XXX Error: Risk optimization not implemented for stochastic cost coefficients.\n"); fprintf (stderr, "XXX Error: Risk optimization not implemented for stochastic cost coefficients.\n"); goto TERMINATE; } // Read advanced starting info if (DDSIP_param->advstart) { DDSIP_node[DDSIP_bb->curnode]->step = DDSIP_bb->DDSIP_step = adv; if ((status = DDSIP_AdvStart ())) goto TERMINATE; // Solution provided? if (DDSIP_param->advstart == 2) { DDSIP_bb->curnode = 0; DDSIP_bb->sug[DDSIP_param->nodelim + 2] = (struct sug_l *)DDSIP_Alloc (sizeof (sug_t), 1, "sug[0](Advanced start solution)"); (DDSIP_bb->sug[DDSIP_param->nodelim + 2])->firstval = (double *) DDSIP_Alloc (sizeof (double), DDSIP_bb->firstvar, "sug[0]->firstval(adv start)"); for (i = 0; i < (DDSIP_bb->firstvar); i++) (DDSIP_bb->sug[DDSIP_param->nodelim + 2]->firstval)[i] = DDSIP_bb->adv_sol[i]; (DDSIP_bb->sug[DDSIP_param->nodelim + 2])->next = NULL; if ((status = DDSIP_UpperBound (DDSIP_param->scenarios, 0)) && status < 100000) goto TERMINATE; } // Only weak consistency check: if ((DDSIP_node[0]->bound) > DDSIP_bb->bestvalue) { status = 121; goto TERMINATE; } fprintf (DDSIP_outfile, "-----------------------------------------------------------\n\n"); } // Solve EV and EEV if specified if (DDSIP_param->expected) { DDSIP_node[DDSIP_bb->curnode]->step = DDSIP_bb->DDSIP_step = eev; // status = 1 -> ExpValProb infeasible if ((status = DDSIP_ExpValProb ()) == 1) { if (DDSIP_param->outlev) fprintf (DDSIP_bb->moreoutfile, " exp. val. prob: INFEASIBLE\n"); fprintf (DDSIP_outfile, " exp. val. prob: INFEASIBLE\n"); } if (!status) { DDSIP_bb->curnode = 0; DDSIP_bb->sug[DDSIP_param->nodelim + 2] = (struct sug_l *)DDSIP_Alloc (sizeof (sug_t), 1, "sug[0](Advanced start solution)"); DDSIP_bb->sug[DDSIP_param->nodelim + 2]->firstval = (double *) DDSIP_Alloc (sizeof (double), DDSIP_bb->firstvar, "sug[i]->firstval(Heuristic)"); for (i = 0; i < DDSIP_bb->firstvar; i++) (DDSIP_bb->sug[DDSIP_param->nodelim + 2]->firstval)[i] = DDSIP_bb->adv_sol[i]; DDSIP_bb->sug[DDSIP_param->nodelim + 2]->next = NULL; if ((status = DDSIP_UpperBound (DDSIP_param->scenarios, 0)) && status < 100000) goto TERMINATE; } if (fabs (DDSIP_bb->expbest) < DDSIP_infty) { if (DDSIP_param->outlev) printf ("\t\t EEV: %13.7f\n", DDSIP_bb->expbest); fprintf (DDSIP_outfile, "-EEV: %13.7f\n", DDSIP_bb->expbest); } else { if (DDSIP_param->outlev) printf ("\t\t EEV: No solution found.\n"); fprintf (DDSIP_outfile, "-EEV: No solution found.\n"); } } // END if (EV) // stop here if NODELIM is zero if (!(DDSIP_param->nodelim)) goto TERMINATE; // Print cplex log to debugfile if (DDSIP_param->outlev > 51) { #ifdef CPLEX_12_8 if ((status = CPXsetlogfilename (DDSIP_env, DDSIP_moreoutfname, "a"))) goto TERMINATE; #else if ((status = CPXsetlogfile (DDSIP_env, DDSIP_bb->moreoutfile))) goto TERMINATE; #endif } // No of DDSIP iterations DDSIP_bb->noiter = 0; // cont = 1 if no stop criteria is fullfilled cont = 1; // comb tells in case of a combined heuristic, which one to apply (3 = RoundNear) comb = 3; if (DDSIP_param->outlev) printf ("Starting branch-and-bound algorithm.\n"); fprintf (DDSIP_outfile, "----------------------------------------------------------------------------------------\n"); while (cont) { // the cuts from the root node are contained in every following node model, there is no need to check their violation // for the scenario solutions. But the rounding heuristics could violate a cut, so keep them. #ifdef CONIC_BUNDLE #ifdef DEBUG //////////////////////////////////////////// if (DDSIP_bb->curnode && DDSIP_param->outlev) { if((DDSIP_node[DDSIP_bb->curnode-1])->step == dual) fprintf(DDSIP_bb->moreoutfile, "######## last node %d step=dual, leaf= %d, dualdescitcnt = %d, DDSIP_bb->cutoff= %d\n",DDSIP_bb->curnode-1,(DDSIP_node[DDSIP_bb->curnode-1])->leaf,DDSIP_bb->dualdescitcnt,DDSIP_bb->cutoff); } //////////////////////////////////////////// #endif if (DDSIP_param->outlev > 20 && DDSIP_bb->curnode && DDSIP_node[DDSIP_node[DDSIP_bb->curnode]->father]->cbReturn32) fprintf (DDSIP_bb->moreoutfile, "########## DDSIP_node[%d >father]->cbReturn32 = 1\n", DDSIP_bb->curnode); // Dual method if ((!DDSIP_bb->curnode || !DDSIP_node[DDSIP_node[DDSIP_bb->curnode]->father]->cbReturn32) && ((DDSIP_param->cb > 0 && (!(DDSIP_bb->noiter % abs(DDSIP_param->cb))) && (abs(DDSIP_param->riskmod) != 4 || DDSIP_bb->noiter)) || (DDSIP_param->cb < 0 && (((DDSIP_node[DDSIP_bb->curnode]->depth <= DDSIP_param->cb_depth) && abs(DDSIP_param->riskmod) != 4) || (abs(DDSIP_param->riskmod) == 5 && DDSIP_node[DDSIP_bb->curnode]->depth == 8) || (DDSIP_bb->noiter > DDSIP_param->cbBreakIters && ((!(DDSIP_bb->noiter % abs(DDSIP_param->cb))) || (!((DDSIP_bb->noiter+1) % -DDSIP_param->cb)) || (DDSIP_bb->noiter%200 > 199 - DDSIP_param->cbContinuous) || (DDSIP_bb->noiter < DDSIP_param->cbContinuous + DDSIP_param->cbBreakIters) || ((DDSIP_bb->noiter >= 2*DDSIP_param->cbBreakIters) && (DDSIP_bb->noiter < DDSIP_param->cbContinuous + 2*DDSIP_param->cbBreakIters)) || ((DDSIP_bb->cutoff > 6) && (((DDSIP_bb->no_reduced_front < 51) && (DDSIP_bb->noiter % -DDSIP_param->cb) < DDSIP_param->cbContinuous) || (((DDSIP_node[DDSIP_bb->curnode-1])->step == dual) && (DDSIP_node[DDSIP_bb->curnode-1])->leaf /*&& (DDSIP_bb->dualdescitcnt < 11)*/) ) ) ) ) || (abs(DDSIP_param->riskmod) != 5 && DDSIP_bb->noiter <= DDSIP_param->cbBreakIters && DDSIP_bb->noiter > DDSIP_param->cbBreakIters*.5 && (CBFORALL || (DDSIP_node[DDSIP_bb->curnode]->numInheritedSols > (DDSIP_Imin(DDSIP_param->scenarios/20,2)+(DDSIP_param->scenarios+1)/2)))) ) ) ) ) { DDSIP_bb->DDSIP_step = DDSIP_node[DDSIP_bb->curnode]->step = dual; if ((status = DDSIP_DualOpt ())) { if (!DDSIP_bb->curnode) goto TERMINATE; else { DDSIP_bb->skip = 1; DDSIP_node[DDSIP_bb->curnode]->bound = DDSIP_infty; } } } else { DDSIP_node[DDSIP_bb->curnode]->step = DDSIP_bb->DDSIP_step = solve; // status=1 means there was no solution found to a scenario problem if ((status = DDSIP_LowerBound ())) goto TERMINATE; } #else DDSIP_node[DDSIP_bb->curnode]->step = DDSIP_bb->DDSIP_step = solve; // status=1 means there was no solution found to a subproblem if ((status = LowerBound ())) goto TERMINATE; #endif if (!DDSIP_bb->skip || DDSIP_bb->skip == -1) { double old_bound; int cntr, maxCntr; DDSIP_bb->cutAdded = 0; DDSIP_EvaluateScenarioSolutions (&comb); cntr = 0; if (DDSIP_node[DDSIP_bb->curnode]->step != dual) maxCntr = DDSIP_param->numberReinits; else maxCntr = 0; old_bound = DDSIP_node[DDSIP_bb->curnode]->bound; boundstat = DDSIP_Bound (); if (!DDSIP_bb->curnode) { int cnt, j; double lhs; cutpool_t *currentCut; DDSIP_PrintState (DDSIP_bb->noiter); if (DDSIP_bb->cutAdded && DDSIP_param->outlev) { fprintf (DDSIP_outfile, " %6d%101d cuts\n", DDSIP_bb->curnode, DDSIP_bb->cutAdded); } while ((DDSIP_bb->cutAdded || DDSIP_node[0]->step == dual) && cntr < maxCntr) { old_bound = DDSIP_node[0]->bound; // Free the solutions from former LowerBound for (i = 0; i < DDSIP_param->scenarios; i++) { if (((DDSIP_node[0])->first_sol)[i]) { if (DDSIP_node[0]->step == solve) { currentCut = DDSIP_bb->cutpool; while (currentCut) { lhs = 0.; for (j = 0; j < DDSIP_bb->firstvar; j++) { lhs += (DDSIP_node[0])->first_sol[i][j] * currentCut->matval[j]; } if (lhs < currentCut->rhs - 1.e-7) { #ifdef DEBUG if (DDSIP_param->outlev > 50) fprintf (DDSIP_bb->moreoutfile, "scen %d solution violates cut %d.\n", i+1, currentCut->number); #endif if ((cnt = (int) ((((DDSIP_node[0])->first_sol)[i])[DDSIP_bb->firstvar] - 0.9))) for (j = i + 1; cnt && j < DDSIP_param->scenarios; j++) { { if (((DDSIP_node[0])->first_sol)[j] && ((DDSIP_node[0])->first_sol)[i] == ((DDSIP_node[0])->first_sol)[j]) { ((DDSIP_node[0])->first_sol)[j] = NULL; cnt--; } } } DDSIP_Free ((void **) &(((DDSIP_node[0])->first_sol)[i])); break; } currentCut = currentCut->prev; } } else { if ((cnt = (int) ((((DDSIP_node[0])->first_sol)[i])[DDSIP_bb->firstvar] - 0.9))) for (j = i + 1; cnt && j < DDSIP_param->scenarios; j++) { { if (((DDSIP_node[0])->first_sol)[j] && ((DDSIP_node[0])->first_sol)[i] == ((DDSIP_node[0])->first_sol)[j]) { ((DDSIP_node[0])->first_sol)[j] = NULL; cnt--; } } } DDSIP_Free ((void **) &(((DDSIP_node[0])->first_sol)[i])); } } } DDSIP_node[0]->step = DDSIP_bb->DDSIP_step = solve; // status=1 means there was no solution found to a scenario problem if ((status = DDSIP_LowerBound ())) goto TERMINATE; DDSIP_bb->cutAdded = 0; DDSIP_EvaluateScenarioSolutions (&comb); cntr++; DDSIP_bb->bestbound = DDSIP_node[0]->bound; DDSIP_bb->noiter++; DDSIP_PrintState (1); if (DDSIP_bb->cutAdded && DDSIP_param->outlev) { fprintf (DDSIP_outfile, " %6d %82d. reinit: %8d cuts\n", 0, cntr, DDSIP_bb->cutAdded); } if ((DDSIP_node[0]->bound - old_bound)/(fabs(old_bound) + 1e-16) < 1.e-7 || (DDSIP_bb->bestvalue - DDSIP_node[0]->bound)/(fabs(DDSIP_bb->bestvalue) + 1e-16) < 0.5*DDSIP_param->relgap) break; } if (DDSIP_param->deleteRedundantCuts) DDSIP_CheckRedundancy(1); } else { // Print a line of output at the first, the last and each `ith' node if (!DDSIP_bb->noiter || (!((DDSIP_bb->noiter + 1) % DDSIP_param->logfreq)) || (DDSIP_param->outlev && (DDSIP_node[DDSIP_bb->curnode])->step == dual)) DDSIP_PrintState (DDSIP_bb->noiter); if (DDSIP_bb->cutAdded && DDSIP_param->outlev > 1) { fprintf (DDSIP_outfile, " %6d%101d cuts\n", DDSIP_bb->curnode, DDSIP_bb->cutAdded); } } } else { boundstat = DDSIP_Bound (); // Print a line of output at the first, the last and each `ith' node if (!DDSIP_bb->noiter || (!((DDSIP_bb->noiter + 1) % DDSIP_param->logfreq)) || (DDSIP_param->outlev && (DDSIP_node[DDSIP_bb->curnode])->step == dual)) DDSIP_PrintState (DDSIP_bb->noiter); } if (!DDSIP_bb->curnode) DDSIP_bb->cutCntr0 = DDSIP_bb->cutNumber; else if (DDSIP_param->alwaysBendersCuts) { if (DDSIP_bb->curnode == 24) { if (DDSIP_bb->cutCntr0 == DDSIP_bb->cutNumber) { if (DDSIP_param->outlev > 20) fprintf (DDSIP_bb->moreoutfile, "### setting alwaysBendersCuts to 0\n"); DDSIP_param->alwaysBendersCuts = 0; } else DDSIP_bb->cutCntr0 = DDSIP_bb->cutNumber; } else if (DDSIP_bb->curnode == 49) { if (DDSIP_bb->cutCntr0 == DDSIP_bb->cutNumber) { if (DDSIP_param->outlev > 20) fprintf (DDSIP_bb->moreoutfile, "### setting alwaysBendersCuts to 0\n"); DDSIP_param->alwaysBendersCuts = 0; } else DDSIP_bb->cutCntr0 = DDSIP_bb->cutNumber; } else if (DDSIP_bb->curnode == 99) { if (DDSIP_bb->cutCntr0 == DDSIP_bb->cutNumber) { if (DDSIP_param->outlev > 20) fprintf (DDSIP_bb->moreoutfile, "### setting alwaysBendersCuts to 0\n"); DDSIP_param->alwaysBendersCuts = 0; } } } // DDSIP_bb->skip > 0 indicates that UpperBound calls have been skipped // DDSIP_bb->heurval contains the objective value of the heuristic solution // Reset to initial values DDSIP_bb->heurval = DDSIP_infty; DDSIP_bb->skip = 0; cont = DDSIP_Continue (&DDSIP_bb->noiter, &boundstat); if (!cont) { status = boundstat; goto TERMINATE; } if ((status = DDSIP_Branch ())) goto TERMINATE; if (DDSIP_param->deleteRedundantCuts && !(DDSIP_bb->curnode % 10)) DDSIP_CheckRedundancy(1); } // Termination TERMINATE: DDSIP_PrintErrorMsg (status); printf ("\nOutput files in directory `%s'.\n", DDSIP_outdir); // Free up problem as allocated above // if (DDSIP_node != NULL) { DDSIP_FreeFrontNodes (); for (i = 0; i < DDSIP_bb->nonode; i++) DDSIP_Free ((void **) &(DDSIP_node[i])); DDSIP_Free ((void **) &(DDSIP_node)); } if (DDSIP_data != NULL) { DDSIP_FreeData (); DDSIP_Free ((void **) &(DDSIP_data)); } // Free up the problem as allocated by CPXcreateprob, if necessary if (DDSIP_lp != NULL) { status = CPXfreeprob (DDSIP_env, &DDSIP_lp); if (status) fprintf (stderr, "ERROR: CPXfreeprob failed, error code %d\n", status); } // Free up the CPLEX environment if (DDSIP_env != NULL) { status = CPXcloseCPLEX (&DDSIP_env); if (status) { char errmsg[1024]; fprintf (stderr, "ERROR: Failed to close CPLEX environment.\n"); CPXgeterrorstring (DDSIP_env, status, errmsg); fprintf (stderr, "%s\n", errmsg); } } if (DDSIP_bb != NULL) { DDSIP_FreeBb (); DDSIP_Free ((void **) &(DDSIP_bb)); } if (DDSIP_param->outlev) printf ("Terminating DDSIP.\n"); if (DDSIP_param != NULL) { DDSIP_FreeParam (); DDSIP_Free ((void **) &(DDSIP_param)); } fprintf (DDSIP_outfile, "Current system time: "); #ifndef _WIN32 i = system ("date"); // Print time to output file sprintf (astring, "date >> %s\n", DDSIP_outfname); i = system (astring); #else sprintf (astring, "date /T >> %s & time /T >> %s\n", DDSIP_outfname,DDSIP_outfname); i = system (astring); #endif if (DDSIP_outfile != NULL) fclose (DDSIP_outfile); return 0; }
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 */
extern int solve_allocation(int nodeSize, int windowSize, int timeout, sched_nodeinfo_t *node_array, solver_job_list_t *job_array) { solver_job_list_t *solver_job_ptr; int solstat; int n = windowSize, m = nodeSize; double objval; double *x = NULL; double *pi = NULL; double *slack = NULL; double *dj = NULL; double *obj = NULL; int NUMCOLS = n * (2 * m + 2); CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int i, j, k; int cur_numrows, cur_numcols; char envstr[256] = "ILOG_LICENSE_FILE=/home/seren/ILOG/CPLEX_Studio_AcademicResearch122/licenses/access.ilm"; if ( envstr != NULL ) { CPXputenv (envstr); } env = CPXopenCPLEX (&status); if ( env == NULL ) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON); if ( status ) { goto TERMINATE; } status = CPXsetintparam (env, CPX_PARAM_DATACHECK, CPX_ON); if ( status ) { goto TERMINATE; } lp = CPXcreateprob (env, &status, "lpex1"); if ( lp == NULL ) { goto TERMINATE; } obj = (double*)malloc(NUMCOLS * sizeof(double)); status = CPXsetdblparam(env,CPX_PARAM_TILIM,5); status = populatebynonzero (env, lp, nodeSize, windowSize, timeout, node_array, job_array); if ( status ) { fprintf (stderr, "Failed to populate problem."); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP."); goto TERMINATE; } cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); x = (double *) malloc (cur_numcols * sizeof(double)); slack = (double *) malloc (cur_numrows * sizeof(double)); dj = (double *) malloc (cur_numcols * sizeof(double)); pi = (double *) malloc (cur_numrows * sizeof(double)); if ( x == NULL || slack == NULL || dj == NULL || pi == NULL ) { status = CPXERR_NO_MEMORY; goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { goto TERMINATE; } /*debug3("\nSolution status = %d\n", solstat);*/ printf("Solution value = %f\n\n", objval); /* for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } */ /*debug3("sending solution results to slurm");*/ /* for (j = 0; j < windowSize; j++) { if (x[j] > 0) { solver_job_ptr = &job_array[j]; solver_job_ptr->node_bitmap = (bitstr_t *) bit_alloc (node_record_count); solver_job_ptr->job_ptr->details->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); solver_job_ptr->onnodes = (int *) xmalloc (sizeof(int)*node_record_count); solver_job_ptr->job_ptr->details->req_node_layout = (int *)xmalloc(sizeof(int) * node_record_count); solver_job_ptr->job_ptr->details->req_node_bitmap = (bitstr_t *) bit_alloc (node_record_count); for (i = 0; i < nodeSize; i++) { k = (1 + i) * windowSize + j; if (x[k] > 0) { bit_set (solver_job_ptr->node_bitmap, (bitoff_t) (i)); bit_set (solver_job_ptr->job_ptr->details->req_node_bitmap, (bitoff_t) (i)); node_array[i].rem_cpus -= x[k]; node_array[i].rem_gpus -= solver_job_ptr->gpu; solver_job_ptr->onnodes[i] = x[k]; solver_job_ptr->job_ptr->details->req_node_layout[i] = solver_job_ptr->onnodes[i]; solver_job_ptr->alloc_total += x[k]; } } } else job_array[j].alloc_total = 0; } */ /* status = CPXwriteprob (env, lp, "lpex1.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk."); goto TERMINATE; } */ TERMINATE: free_and_null ((char **) &x); free_and_null ((char **) &slack); free_and_null ((char **) &dj); free_and_null ((char **) &pi); if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.", status); } } if ( env != NULL ) { status = CPXcloseCPLEX (&env); if ( status ) { char errmsg[1024]; fprintf (stderr, "Could not close CPLEX environment."); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int i, j; double *c=NULL, *b=NULL, *A=NULL, *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ; int *iA=NULL, *kA=NULL, *nzA=NULL, neq=0, m=0, n=0, display=0; long *lpenv=NULL, *p_lp=NULL; char *Sense=NULL ; #ifndef MX_COMPAT_32 long *iA_=NULL, *kA_=NULL ; #endif if (nrhs > 8 || nrhs < 1) { mexErrMsgTxt("Usage: [p_lp,how] " "= lp_gen(lpenv,c,A,b,l,u,neq,disp)"); return; } switch (nrhs) { case 8: if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) { if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7]) || mxIsSparse(prhs[7]) || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) { mexErrMsgTxt("8th argument (display) must be " "an integer scalar."); return; } display = *mxGetPr(prhs[7]); } case 7: if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) { if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6]) || mxIsSparse(prhs[6]) || !(mxGetM(prhs[6])==1 && mxGetN(prhs[6])==1)) { mexErrMsgTxt("7th argument (neq) must be " "an integer scalar."); return; } neq = *mxGetPr(prhs[6]); } case 6: if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) { if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) || mxIsSparse(prhs[5]) || !mxIsDouble(prhs[5]) || mxGetN(prhs[5])!=1 ) { mexErrMsgTxt("6th argument (u) must be " "a column vector."); return; } u = mxGetPr(prhs[5]); n = mxGetM(prhs[5]); } case 5: if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) { if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 ) { mexErrMsgTxt("5th argument (l) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[4])) { mexErrMsgTxt("Dimension error (arg 5 and later)."); return; } l = mxGetPr(prhs[4]); n = mxGetM(prhs[4]); } case 4: if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3]) || mxGetN(prhs[3])!=1 ) { mexErrMsgTxt("4rd argument (b) must be " "a column vector."); return; } if (m != 0 && m != mxGetM(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } b = mxGetPr(prhs[3]); m = mxGetM(prhs[3]); } case 3: if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) { if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || !mxIsSparse(prhs[2]) ) { mexErrMsgTxt("3n argument (A) must be " "a sparse matrix."); return; } if (m != 0 && m != mxGetM(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } if (n != 0 && n != mxGetN(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } m = mxGetM(prhs[2]); n = mxGetN(prhs[2]); A = mxGetPr(prhs[2]); #ifdef MX_COMPAT_32 iA = mxGetIr(prhs[2]); kA = mxGetJc(prhs[2]); #else iA_ = mxGetIr(prhs[2]); kA_ = mxGetJc(prhs[2]); iA = myMalloc(mxGetNzmax(prhs[2])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[2]); i++) iA[i]=iA_[i] ; kA = myMalloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kA[i]=kA_[i] ; #endif nzA=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzA[i]=kA[i+1]-kA[i] ; Sense=myMalloc((m+1)*sizeof(char)) ; for (i=0; i<m; i++) if (i<neq) Sense[i]='E' ; else Sense[i]='L' ; Sense[m]=0 ; } case 2: if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || mxGetN(prhs[1])!=1 ) { mexErrMsgTxt("2st argument (c) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } c = mxGetPr(prhs[1]); n = mxGetM(prhs[1]); } case 1: if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) { if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxGetN(prhs[0])!=1 ) { mexErrMsgTxt("1st argument (lpenv) must be " "a column vector."); return; } if (1 != mxGetM(prhs[0])) { mexErrMsgTxt("Dimension error (arg 1)."); return; } lpenv = (long*) mxGetPr(prhs[0]); } } if (nlhs > 2 || nlhs < 1) { mexErrMsgTxt("Usage: [p_lp,how] " "= lp_gen(lpenv,c,A,b,l,u,neq,disp)"); return; } if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ; switch (nlhs) { case 2: case 1: plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); p_lp = (long*) mxGetPr(plhs[0]); } if (display>2) fprintf(STD_OUT, "argument processing finished\n") ; { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status, lpstat; double objval; /* Initialize the CPLEX environment */ env = (CPXENVptr) lpenv[0] ; /* Create the problem */ if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ; lp = CPXcreateprob (env, &status, "xxx"); if ( lp == NULL ) { fprintf (STD_OUT,"Failed to create subproblem\n"); status = 1; goto TERMINATE; } if (p_lp) *p_lp=(long) lp ; if (display>2) fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ; status = CPXcopylp(env, lp, n, m, CPX_MIN, c, b, Sense, kA, nzA, iA, A, l, u, NULL); if ( status ) { fprintf (STD_OUT, "CPXcopylp failed.\n"); goto TERMINATE; } TERMINATE: if (status) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (STD_OUT, "%s", errmsg); if (nlhs >= 2) plhs[1] = mxCreateString(errmsg) ; } else if (nlhs >= 2) plhs[1] = mxCreateString("OK") ; ; if (nzA) myFree(nzA) ; #ifndef MX_COMPAT_32 if (iA) myFree(iA) ; if (kA) myFree(kA) ; #endif /*if (Sense) myFree(Sense) ;*/ if (!p_lp) { if ( lp != NULL ) { if (display>2) fprintf(STD_OUT, "calling CPXfreeprob\n") ; status = CPXfreeprob (env, &lp); if ( status ) { fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status); } } } return ; } }
int main (int argc, char *argv[]) { int uselogcallback = 0; LOGINFO myloginfo; int usetimelimcallback = 0; TIMELIMINFO mytimeliminfo; int useterminate = 0; volatile int terminator; CPXENVptr env = NULL; CPXLPptr lp = NULL; int solstat; int status = 0; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("lta", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } switch (argv[2][0]) { case 'l': uselogcallback = 1; break; case 't': usetimelimcallback = 1; break; case 'a': useterminate = 1; break; default: break; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( usetimelimcallback ) { double t; status = CPXgettime (env, &t); if ( status ) { fprintf (stderr, "Failed to initialize timer.\n"); goto TERMINATE; } mytimeliminfo.acceptablegap = 10.0; mytimeliminfo.aborted = 0; mytimeliminfo.timestart = t; mytimeliminfo.timelim = 1.0; status = CPXsetinfocallbackfunc (env, timelimcallback, &mytimeliminfo); if ( status ) { fprintf (stderr, "Failed to set time limit callback function.\n"); goto TERMINATE; } } else if ( uselogcallback ) { /* Set overall node limit in case callback conditions are not met */ status = CPXsetintparam (env, CPXPARAM_MIP_Limits_Nodes, 5000); if ( status ) goto TERMINATE; status = CPXgettime (env, &myloginfo.timestart); if ( status ) { fprintf (stderr, "Failed to query time.\n"); goto TERMINATE; } status = CPXgetdettime (env, &myloginfo.dettimestart); if ( status ) { fprintf (stderr, "Failed to query deterministic time.\n"); goto TERMINATE; } myloginfo.numcols = CPXgetnumcols (env, lp); myloginfo.lastincumbent = CPXgetobjsen (env, lp) * 1e+35; myloginfo.lastlog = -10000; status = CPXsetinfocallbackfunc (env, logcallback, &myloginfo); if ( status ) { fprintf (stderr, "Failed to set logging callback function.\n"); goto TERMINATE; } /* Turn off CPLEX logging */ status = CPXsetintparam (env, CPXPARAM_MIP_Display, 0); if ( status ) goto TERMINATE; } else if ( useterminate) { status = CPXsetterminate (env, &terminator); if ( status ) { fprintf (stderr, "Failed to set terminator.\n"); goto TERMINATE; } /* Typically, you would pass the terminator variable to another thread or pass it to an interrupt handler, and monitor for some event to occur. When it does, set terminator to a non-zero value. To illustrate its use without creating a thread or an interrupt handler, terminate immediately by setting terminator before the solve. */ terminator = 1; } /* Optimize the problem and obtain solution. */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { int xstatus = CPXfreeprob (env, &lp); if ( xstatus ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", xstatus); status = xstatus; } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { int xstatus = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); status = xstatus; } } return (status); } /* END main */
int main (int argc, char *argv[]) { int status = 0; /* Declare and allocate space for the variables and arrays where we will store the optimization results, including the status, objective value, and variable values */ int solstat; double objval; double *x = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int j; int cur_numcols; const char * datadir = argc <= 1 ? "../../../examples/data" : argv[1]; char *noswot = NULL; noswot = (char *) malloc (strlen (datadir) + 1 + strlen("noswot.mps") + 1); sprintf (noswot, "%s/noswot.mps", datadir); /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } CPXsetintparam (env, CPXPARAM_MIP_Interval, 1000); /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, "noswot"); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, noswot, NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } /* Set parameters */ /* Assure linear mappings between the presolved and original models */ status = CPXsetintparam (env, CPXPARAM_Preprocessing_Linear, 0); if ( status ) goto TERMINATE; /* Create user cuts for noswot problem */ status = addusercuts (env, lp); if ( status ) goto TERMINATE; /* Optimize the problem and obtain solution */ status = CPXmipopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize MIP.\n"); goto TERMINATE; } solstat = CPXgetstat (env, lp); printf ("Solution status %d.\n", solstat); status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr,"Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g\n", objval); cur_numcols = CPXgetnumcols (env, lp); /* Allocate space for solution */ x = (double *) malloc (cur_numcols * sizeof (double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution values.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { if ( fabs (x[j]) > 1e-10 ) { printf ("Column %d: Value = %17.10g\n", j, x[j]); } } TERMINATE: /* Free the filename */ free_and_null ((char **) &noswot); /* Free the solution vector */ free_and_null ((char **) &x); /* Free the problem as allocated by CPXcreateprob and CPXreadcopyprob, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput parameter is set to CPX_ON */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
int main (int argc, char *argv[]) { /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, maximum bound violation, variable values, and basis. */ int solnstat, solnmethod, solntype; double objval, maxviol; double *x = NULL; int *cstat = NULL; int *rstat = NULL; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status = 0; int j; int cur_numrows, cur_numcols; char *basismsg; /* Check the command line arguments */ if (( argc != 3 ) || ( strchr ("cfg", argv[2][0]) == NULL ) ) { usage (argv[0]); goto TERMINATE; } /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. A call to CPXgeterrorstring will produce the text of the error message. Note that CPXopenCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( env == NULL ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not open CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); goto TERMINATE; } /* Turn on output to the screen */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status ) { fprintf (stderr, "Failure to turn on screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem, using the filename as the problem name */ lp = CPXcreateprob (env, &status, argv[1]); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, the setting of the parameter CPXPARAM_ScreenOutput causes the error message to appear on stdout. Note that most CPLEX routines return an error code to indicate the reason for failure. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now read the file, and copy the data into the created lp */ status = CPXreadcopyprob (env, lp, argv[1], NULL); if ( status ) { fprintf (stderr, "Failed to read and copy the problem data.\n"); goto TERMINATE; } if ( CPXgetprobtype (env, lp) != CPXPROB_QP ) { fprintf (stderr, "Input file is not a QP. Exiting.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ switch (argv[2][0]) { case 'c': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_OPTIMALCONVEX); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { if ( status == CPXERR_Q_NOT_POS_DEF ) printf ("Problem is not convex. Use argument f to get local optimum " "or g to get global optimum.\n"); else fprintf (stderr, "Failed to optimize QP.\n"); goto TERMINATE; } break; case 'f': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_FIRSTORDER); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize QP.\n"); goto TERMINATE; } break; case 'g': status = CPXsetintparam (env, CPXPARAM_SolutionTarget, CPX_SOLUTIONTARGET_OPTIMALGLOBAL); if ( status ) goto TERMINATE; status = CPXqpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize noncvonex QP.\n"); goto TERMINATE; } break; default: break; } solnstat = CPXgetstat (env, lp); if ( solnstat == CPXMIP_UNBOUNDED || solnstat == CPX_STAT_UNBOUNDED ) { printf ("Model is unbounded\n"); goto TERMINATE; } else if ( solnstat == CPXMIP_INFEASIBLE || solnstat == CPX_STAT_INFEASIBLE ) { printf ("Model is infeasible\n"); goto TERMINATE; } else if ( solnstat == CPX_STAT_INForUNBD ) { printf ("Model is infeasible or unbounded\n"); goto TERMINATE; } status = CPXsolninfo (env, lp, &solnmethod, &solntype, NULL, NULL); if ( status ) { fprintf (stderr, "Failed to obtain solution info.\n"); goto TERMINATE; } printf ("Solution status %d, solution method %d\n", solnstat, solnmethod); if ( solntype == CPX_NO_SOLN ) { fprintf (stderr, "Solution not available.\n"); goto TERMINATE; } status = CPXgetobjval (env, lp, &objval); if ( status ) { fprintf (stderr, "Failed to obtain objective value.\n"); goto TERMINATE; } printf ("Objective value %.10g.\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numcols = CPXgetnumcols (env, lp); cur_numrows = CPXgetnumrows (env, lp); /* Retrieve basis, if one is available */ if ( solntype == CPX_BASIC_SOLN ) { cstat = (int *) malloc (cur_numcols*sizeof(int)); rstat = (int *) malloc (cur_numrows*sizeof(int)); if ( cstat == NULL || rstat == NULL ) { fprintf (stderr, "No memory for basis statuses.\n"); goto TERMINATE; } status = CPXgetbase (env, lp, cstat, rstat); if ( status ) { fprintf (stderr, "Failed to get basis; error %d.\n", status); goto TERMINATE; } } else { printf ("No basis available\n"); } /* Retrieve solution vector */ x = (double *) malloc (cur_numcols*sizeof(double)); if ( x == NULL ) { fprintf (stderr, "No memory for solution.\n"); goto TERMINATE; } status = CPXgetx (env, lp, x, 0, cur_numcols-1); if ( status ) { fprintf (stderr, "Failed to obtain primal solution.\n"); goto TERMINATE; } /* Write out the solution */ for (j = 0; j < cur_numcols; j++) { printf ( "Column %d: Value = %17.10g", j, x[j]); if ( cstat != NULL ) { switch (cstat[j]) { case CPX_AT_LOWER: basismsg = "Nonbasic at lower bound"; break; case CPX_BASIC: basismsg = "Basic"; break; case CPX_AT_UPPER: basismsg = "Nonbasic at upper bound"; break; case CPX_FREE_SUPER: basismsg = "Superbasic, or free variable at zero"; break; default: basismsg = "Bad basis status"; break; } printf (" %s",basismsg); } printf ("\n"); } /* Display the maximum bound violation. */ status = CPXgetdblquality (env, lp, &maxviol, CPX_MAX_PRIMAL_INFEAS); if ( status ) { fprintf (stderr, "Failed to obtain bound violation.\n"); goto TERMINATE; } printf ("Maximum bound violation = %17.10g\n", maxviol); TERMINATE: /* Free up the basis and solution */ free_and_null ((char **) &cstat); free_and_null ((char **) &rstat); free_and_null ((char **) &x); /* Free up the problem, if necessary */ if ( lp != NULL ) { status = CPXfreeprob (env, &lp); if ( status ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status); } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { status = CPXcloseCPLEX (&env); /* Note that CPXcloseCPLEX produces no output, so the only way to see the cause of the error is to use CPXgeterrorstring. For other CPLEX routines, the errors will be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */ if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; fprintf (stderr, "Could not close CPLEX environment.\n"); CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } } return (status); } /* END main */
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 */
~IPimpl() { if (lp_) CPXfreeprob(env_, &lp_); if (env_) CPXcloseCPLEX(&env_); }
int main (void) { char probname[16]; /* Problem name is max 16 characters */ /* Declare and allocate space for the variables and arrays where we will store the optimization results including the status, objective value, variable values, dual values, row slacks and variable reduced costs. */ int solstat; double objval; double x[NUMCOLS]; double pi[NUMROWS]; double slack[NUMROWS]; double dj[NUMCOLS]; CPXENVptr env = NULL; CPXLPptr lp = NULL; int status; int i, j; int cur_numrows, cur_numcols; /* Initialize the CPLEX environment */ env = CPXopenCPLEX (&status); /* If an error occurs, the status value indicates the reason for failure. The error message will be printed at the end of the program. */ if ( env == NULL ) { fprintf (stderr, "Could not open CPLEX environment.\n"); goto TERMINATE; } /* Turn *off* output to the screen since we'll be producing it via the callback function. This also means we won't see any CPLEX generated errors, but we'll handle that at the end of the program. */ status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_OFF); if ( status ) { fprintf (stderr, "Failure to turn off screen indicator, error %d.\n", status); goto TERMINATE; } /* Create the problem. */ strcpy (probname, "example"); lp = CPXcreateprob (env, &status, probname); /* A returned pointer of NULL may mean that not enough memory was available or there was some other problem. In the case of failure, an error message will have been written to the error channel from inside CPLEX. In this example, we wouldn't see an error message from CPXcreateprob since we turned off the CPXPARAM_ScreenOutput parameter above. The only way to see this message would be to use the CPLEX message handler, but that clutters up the simplicity of this example, which has a point of illustrating the CPLEX callback functionality. */ if ( lp == NULL ) { fprintf (stderr, "Failed to create LP.\n"); goto TERMINATE; } /* Now populate the problem with the data. */ status = populatebycolumn (env, lp); if ( status ) { fprintf (stderr, "Failed to populate problem data.\n"); goto TERMINATE; } status = CPXsetlpcallbackfunc (env, mycallback, NULL); if ( status ) { fprintf (stderr, "Failed to set callback function.\n"); goto TERMINATE; } /* Optimize the problem and obtain solution. */ status = CPXsetintparam (env, CPXPARAM_LPMethod, CPX_ALG_PRIMAL); if ( status ) { fprintf (stderr, "Failed to set the optimization method, error %d.\n", status); goto TERMINATE; } status = CPXlpopt (env, lp); if ( status ) { fprintf (stderr, "Failed to optimize LP.\n"); goto TERMINATE; } /* Turn off the callback function. This isn't strictly necessary, but is good practice. Note that the cast in front of NULL is only necessary for some compilers. */ status = CPXsetlpcallbackfunc (env, (int (CPXPUBLIC *)(CPXCENVptr, void *, int, void *)) NULL, NULL); if ( status ) { fprintf (stderr, "Failed to turn off callback function.\n"); goto TERMINATE; } status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj); if ( status ) { fprintf (stderr, "Failed to obtain solution.\n"); goto TERMINATE; } /* Write the output to the screen. */ printf ("\nSolution status = %d\n", solstat); printf ("Solution value = %f\n\n", objval); /* The size of the problem should be obtained by asking CPLEX what the actual size is, rather than using sizes from when the problem was built. cur_numrows and cur_numcols store the current number of rows and columns, respectively. */ cur_numrows = CPXgetnumrows (env, lp); cur_numcols = CPXgetnumcols (env, lp); for (i = 0; i < cur_numrows; i++) { printf ("Row %d: Slack = %10f Pi = %10f\n", i, slack[i], pi[i]); } for (j = 0; j < cur_numcols; j++) { printf ("Column %d: Value = %10f Reduced cost = %10f\n", j, x[j], dj[j]); } /* Finally, write a copy of the problem to a file. */ status = CPXwriteprob (env, lp, "lpex4.lp", NULL); if ( status ) { fprintf (stderr, "Failed to write LP to disk.\n"); goto TERMINATE; } TERMINATE: /* Free up the problem as allocated by CPXcreateprob, if necessary */ if ( lp != NULL ) { int frstatus; frstatus = CPXfreeprob (env, &lp); if ( frstatus ) { fprintf (stderr, "CPXfreeprob failed, error code %d.\n", frstatus); if (( !status ) && frstatus ) status = frstatus; } } /* Free up the CPLEX environment, if necessary */ if ( env != NULL ) { int clstatus; clstatus = CPXcloseCPLEX (&env); if ( clstatus ) { fprintf (stderr, "CPXcloseCPLEX failed, error code %d.\n", clstatus); if (( !status ) && clstatus ) status = clstatus; } } if ( status ) { char errmsg[CPXMESSAGEBUFSIZE]; /* Note that since we have turned off the CPLEX screen indicator, we'll need to print the error message ourselves. */ CPXgeterrorstring (env, status, errmsg); fprintf (stderr, "%s", errmsg); } return (status); } /* END main */
int main (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) { int status, solstat; CPXENVptr env; CPXLPptr lp; int i; double x[NUMCOLS]; double cpi[NUMCOLS]; double rpi[NUMROWS]; double qpi[NUMQS]; double slack[NUMROWS], qslack[NUMQS]; double kktsum[NUMCOLS]; /* ********************************************************************** * * * * S E T U P P R O B L E M * * * * ********************************************************************** */ /* Create CPLEX environment and enable screen output. */ env = CPXopenCPLEX (&status); if ( status != 0 ) goto TERMINATE; status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON); if ( status != 0 ) goto TERMINATE; /* Create the problem object and populate it. */ lp = CPXcreateprob (env, &status, "qcpdual"); if ( status != 0 ) goto TERMINATE; status = CPXnewcols (env, lp, NUMCOLS, obj, lb, ub, NULL, cname); if ( status != 0 ) goto TERMINATE; status = CPXaddrows (env, lp, 0, NUMROWS, NUMNZS, rhs, sense, rmatbeg, rmatind, rmatval, NULL, rname); if ( status != 0 ) goto TERMINATE; for (i = 0; i < NUMQS; ++i) { int const linend = (i == NUMQS - 1) ? NUMLINNZ : linbeg[i + 1]; int const quadend = (i == NUMQS - 1) ? NUMQUADNZ : quadbeg[i + 1]; status = CPXaddqconstr (env, lp, linend - linbeg[i], quadend - quadbeg[i], qrhs[i], qsense[i], &linind[linbeg[i]], &linval[linbeg[i]], &quadrow[quadbeg[i]], &quadcol[quadbeg[i]], &quadval[quadbeg[i]], qname[i]); if ( status != 0 ) goto TERMINATE; } /* ********************************************************************** * * * * O P T I M I Z E P R O B L E M * * * * ********************************************************************** */ status = CPXsetdblparam (env, CPXPARAM_Barrier_QCPConvergeTol, 1e-10); if ( status != 0 ) goto TERMINATE; /* Solve the problem. */ status = CPXbaropt (env, lp); if ( status != 0 ) goto TERMINATE; solstat = CPXgetstat (env, lp); if ( solstat != CPX_STAT_OPTIMAL ) { fprintf (stderr, "No optimal solution found!\n"); goto TERMINATE; } /* ********************************************************************** * * * * Q U E R Y S O L U T I O N * * * * ********************************************************************** */ /* Optimal solution and slacks for linear and quadratic constraints. */ status = CPXgetx (env, lp, x, 0, NUMCOLS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetslack (env, lp, slack, 0, NUMROWS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetqconstrslack (env, lp, qslack, 0, NUMQS - 1); if ( status != 0 ) goto TERMINATE; /* Dual multipliers for linear constraints and bound constraints. */ status = CPXgetdj (env, lp, cpi, 0, NUMCOLS - 1); if ( status != 0 ) goto TERMINATE; status = CPXgetpi (env, lp, rpi, 0, NUMROWS - 1); if ( status != 0 ) goto TERMINATE; status = getqconstrmultipliers (env, lp, x, qpi, ZEROTOL); if ( status != 0 ) goto TERMINATE; /* ********************************************************************** * * * * C H E C K K K T C O N D I T I O N S * * * * Here we verify that the optimal solution computed by CPLEX (and * * the qpi[] values computed above) satisfy the KKT conditions. * * * * ********************************************************************** */ /* Primal feasibility: This example is about duals so we skip this test. */ /* Dual feasibility: We must verify * - for <= constraints (linear or quadratic) the dual * multiplier is non-positive. * - for >= constraints (linear or quadratic) the dual * multiplier is non-negative. */ for (i = 0; i < NUMROWS; ++i) { switch (sense[i]) { case 'E': /* nothing */ break; case 'R': /* nothing */ break; case 'L': if ( rpi[i] > ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for <= row %d: %f\n", i, rpi[i]); status = -1; goto TERMINATE; } break; case 'G': if ( rpi[i] < -ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for >= row %d: %f\n", i, rpi[i]); status = -1; goto TERMINATE; } break; } } for (i = 0; i < NUMQS; ++i) { switch (qsense[i]) { case 'E': /* nothing */ break; case 'L': if ( qpi[i] > ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for <= quad %d: %f\n", i, qpi[i]); status = -1; goto TERMINATE; } break; case 'G': if ( qpi[i] < -ZEROTOL ) { fprintf (stderr, "Dual feasibility test failed for >= quad %d: %f\n", i, qpi[i]); status = -1; goto TERMINATE; } break; } } /* Complementary slackness. * For any constraint the product of primal slack and dual multiplier * must be 0. */ for (i = 0; i < NUMROWS; ++i) { if ( sense[i] != 'E' && fabs (slack[i] * rpi[i]) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for row %d: %f\n", i, fabs (slack[i] * rpi[i])); status = -1; goto TERMINATE; } } for (i = 0; i < NUMQS; ++i) { if ( qsense[i] != 'E' && fabs (qslack[i] * qpi[i]) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for quad %d: %f\n", i, fabs (qslack[i] * qpi[i])); status = -1; goto TERMINATE; } } for (i = 0; i < NUMCOLS; ++i) { if ( ub[i] < CPX_INFBOUND ) { double const slk = ub[i] - x[i]; double const dual = cpi[i] < -ZEROTOL ? cpi[i] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { fprintf (stderr, "Complementary slackness test failed for ub %d: %f\n", i, fabs (slk * dual)); status = -1; goto TERMINATE; } } if ( lb[i] > -CPX_INFBOUND ) { double const slk = x[i] - lb[i]; double const dual = cpi[i] > ZEROTOL ? cpi[i] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { printf ("lb=%f, x=%f, cpi=%f\n", lb[i], x[i], cpi[i]); fprintf (stderr, "Complementary slackness test failed for lb %d: %f\n", i, fabs (slk * dual)); status = -1; goto TERMINATE; } } } /* Stationarity. * The difference between objective function and gradient at optimal * solution multiplied by dual multipliers must be 0, i.e., for the * optimal solution x * 0 == c * - sum(r in rows) r'(x)*rpi[r] * - sum(q in quads) q'(x)*qpi[q] * - sum(c in cols) b'(x)*cpi[c] * where r' and q' are the derivatives of a row or quadratic constraint, * x is the optimal solution and rpi[r] and qpi[q] are the dual * multipliers for row r and quadratic constraint q. * b' is the derivative of a bound constraint and cpi[c] the dual bound * multiplier for column c. */ /* Objective function. */ for (i = 0; i < NUMCOLS; ++i) kktsum[i] = obj[i]; /* Linear constraints. * The derivative of a linear constraint ax - b (<)= 0 is just a. */ for (i = 0; i < NUMROWS; ++i) { int const end = (i == NUMROWS - 1) ? NUMNZS : rmatbeg[i + 1]; int k; for (k = rmatbeg[i]; k < end; ++k) kktsum[rmatind[k]] -= rpi[i] * rmatval[k]; } /* Quadratic constraints. * The derivative of a constraint xQx + ax - b <= 0 is * Qx + Q'x + a. */ for (i = 0; i < NUMQS; ++i) { int j; int k; for (j = linbeg[i]; j < linbeg[i] + linnzcnt[i]; ++j) kktsum[linind[j]] -= qpi[i] * linval[j]; for (k = quadbeg[i]; k < quadbeg[i] + quadnzcnt[i]; ++k) { kktsum[quadrow[k]] -= qpi[i] * x[quadcol[k]] * quadval[k]; kktsum[quadcol[k]] -= qpi[i] * x[quadrow[k]] * quadval[k]; } } /* Bounds. * The derivative for lower bounds is -1 and that for upper bounds * is 1. * CPLEX already returns dj with the appropriate sign so there is * no need to distinguish between different bound types here. */ for (i = 0; i < NUMCOLS; ++i) { kktsum[i] -= cpi[i]; } for (i = 0; i < NUMCOLS; ++i) { if ( fabs (kktsum[i]) > ZEROTOL ) { fprintf (stderr, "Stationarity test failed at index %d: %f\n", i, kktsum[i]); status = -1; goto TERMINATE; } } /* KKT conditions satisfied. Dump out the optimal solutions and * the dual values. */ printf ("Optimal solution satisfies KKT conditions.\n"); printf (" x[] ="); for (i = 0; i < NUMCOLS; ++i) printf (" %7.3f", x[i]); printf ("\n"); printf ("cpi[] ="); for (i = 0; i < NUMCOLS; ++i) printf (" %7.3f", cpi[i]); printf ("\n"); printf ("rpi[] ="); for (i = 0; i < NUMROWS; ++i) printf (" %7.3f", rpi[i]); printf ("\n"); printf ("qpi[] ="); for (i = 0; i < NUMQS; ++i) printf (" %7.3f", qpi[i]); printf ("\n"); TERMINATE: /* ********************************************************************** * * * * C L E A N U P * * * * ********************************************************************** */ status = CPXfreeprob (env, &lp); if ( status != 0 ) { fprintf (stderr, "WARNING: Failed to free problem: %d\n", status); } status = CPXcloseCPLEX (&env); if ( status != 0 ) { fprintf (stderr, "WARNING: Failed to close CPLEX: %d\n", status); } return status; }