int lpx_write_mps(LPX *lp, const char *fname) { /* write problem data in fixed MPS format */ return glp_write_mps(lp, GLP_MPS_DECK, NULL, fname); }
int lpx_write_freemps(LPX *lp, const char *fname) { /* write problem data in free MPS format */ return glp_write_mps(lp, GLP_MPS_FILE, NULL, fname); }
int main(int argc, char * argv[]) { int i,j; time(&initial); srand(SEED); /* Default values */ outFile = stdout; maxAlpha = 2; maxIter = 100; maxTime = 30; randomSeed = SEED; simpleOutput = 0; /* Read arguments */ if( argc > 7 ) argc = 7; switch(argc) { case 7: simpleOutput = atoi(argv[6]); case 6: if( !(randomSeed = atoi(argv[5])) ) leave(argv[0]); case 5: if( !(maxTime = atoi(argv[4])) ) leave(argv[0]); case 4: if( !(maxIter = atoi(argv[3])) ) leave(argv[0]); case 3: if( !(maxAlpha = atoi(argv[2])) ) leave(argv[0]); case 2: if( simpleOutput ) { if( !(outFile = fopen(argv[1],"a")) ) leave(argv[0]); break; } if( !(outFile = fopen(argv[1],"w")) ) leave(argv[0]); } readInput(stdin); /* Initiate positions */ for( i = 0 ; i < n ; ++i ) { pOrd[i].ideal = planes[i].ideal; pOrd[i].pos = i; } qsort (pOrd, n, sizeof(struct planeOrder), compIdealT); for( i = 0 ; i < n ; ++i ) { planes[pOrd[i].pos].pos = i; } /* Create lp instance */ glp_prob * Prob; Prob = glp_create_prob(); glp_set_prob_name(Prob, "Airplane Landing Problem"); glp_set_obj_name(Prob, "Cost"); /* Create basic constraints */ for( i = 0 ; i < n ; ++i ) { addBasicRestriction(Prob,i); } glp_create_index(Prob); /* Create separation constraints and order variables (&ij) if necessary */ for( i = 0 ; i < n ; ++i ) { for( j = i+1 ; j < n ; ++j ) { if( planes[i].latest >= planes[j].earliest && planes[j].latest >= planes[i].earliest ) { addOrderConstraint(Prob,i,j); } else if ( planes[i].latest < planes[j].earliest && planes[i].latest + planes[i].sep[j] >= planes[j].earliest ) { addSeparationConstraint(Prob, i, j); } else if ( planes[j].latest < planes[i].earliest && planes[j].latest + planes[j].sep[i] >= planes[i].earliest ) { addSeparationConstraint(Prob, j, i); } } } /* Write problem in MPS format so glpsol can (try to) solve it */ glp_write_mps(Prob, GLP_MPS_FILE, NULL,"mpsProblem.txt"); glp_delete_index(Prob); glp_create_index(Prob); /* GRASP */ /* Data to handle glp solving, time checking and solution generating */ glp_smcp * param = malloc(sizeof(glp_smcp)); glp_init_smcp(param); param->msg_lev = GLP_MSG_ERR; int solution[MAXSIZE], timeAux[MAXSIZE], t; double currResult = DBL_MAX, bestResult = DBL_MAX; alpha = 0; time_t start, curr; time(&start); for( t = 0 ; t < maxIter ; ++t ) { /* Greedy solution generation */ while(createSolution(solution,timeAux,0)) alpha = n; /* Building the right constraints */ mapSolution(Prob,solution); /* Solving with glpsol */ param->presolve = GLP_ON; glp_simplex(Prob,param); param->presolve = GLP_OFF; currResult = glp_get_obj_val(Prob); /* Local search using the first increase */ for( i = 0 ; i < n-1 ; ++i ) { /* Swap two adjacent planes */ swapConstraint(Prob,i,solution,0); glp_simplex(Prob,param); /* Check for improvements */ if( GLP_OPT == glp_get_status(Prob) && glp_get_obj_val(Prob) < currResult ) { currResult = glp_get_obj_val(Prob); /* Changing the solution */ int swp; swp = solution[i]; solution[i] = solution[i+1]; solution[i+1] = swp; /* Restarting */ i = -1; } else swapConstraint(Prob,i,solution,1); } /* Checking improvements */ if( bestResult > currResult ) { bestResult = currResult; for( i = 0 ; i < n ; ++i ) planes[solution[i]].pos = i; } /* Choosing alpha */ alpha = rand()%(maxAlpha+1); /* Is our time up? */ time(&curr); if( difftime(curr,start) > maxTime ) break; } /* Print Answer */ printResult(Prob, stdout); if( outFile ) { printResult(Prob, outFile); fclose(outFile); } return 0; }
static PyObject* LPX_write(LPXObject *self, PyObject *args, PyObject *keywds) { static char* kwlist[] = {"mps", "freemps", "prob", "sol", "sens_bnds", "ips", "mip", NULL}; char* fnames[] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL}; char* fname; const char* err_msg = "writer for '%s' failed to write to '%s'"; int rv; rv = PyArg_ParseTupleAndKeywords(args, keywds, "|sssssss", kwlist, fnames,fnames+1,fnames+2,fnames+3, fnames+4,fnames+5,fnames+6); if (!rv) return NULL; fname = fnames[0]; if (fname != NULL) { rv = glp_write_mps(LP, GLP_MPS_DECK, NULL, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[0], fname); return NULL; } } fname = fnames[1]; if (fname != NULL) { rv = glp_write_mps(LP, GLP_MPS_FILE, NULL, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[1], fname); return NULL; } } fname = fnames[2]; if (fname != NULL) { rv = glp_write_lp(LP, NULL, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[2], fname); return NULL; } } fname = fnames[3]; if (fname != NULL) { rv = glp_print_sol(LP, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[3], fname); return NULL; } } fname = fnames[4]; if (fname != NULL) { if (glp_get_status(LP) == GLP_OPT && !glp_bf_exists(LP)) glp_factorize(LP); rv = glp_print_ranges(LP, 0, NULL, 0, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[4], fname); return NULL; } } fname = fnames[5]; if (fname != NULL) { rv = glp_print_ipt(LP, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[5], fname); return NULL; } } fname = fnames[6]; if (fname != NULL) { glp_print_mip(LP, fname); if (rv != 0) { PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[6], fname); return NULL; } } Py_RETURN_NONE; }
int glpk (int sense, int n, int m, double *c, int nz, int *rn, int *cn, double *a, double *b, char *ctype, int *freeLB, double *lb, int *freeUB, double *ub, int *vartype, int isMIP, int lpsolver, int save_pb, char *save_filename, char *filetype, double *xmin, double *fmin, double *status, double *lambda, double *redcosts, double *time, double *mem) { int typx = 0; int method; clock_t t_start = clock(); //Redirect standard output if (glpIntParam[0] > 1) glp_term_hook (glpk_print_hook, NULL); else glp_term_hook (NULL, NULL); //-- Create an empty LP/MILP object LPX *lp = lpx_create_prob (); //-- Set the sense of optimization if (sense == 1) glp_set_obj_dir (lp, GLP_MIN); else glp_set_obj_dir (lp, GLP_MAX); //-- Define the number of unknowns and their domains. glp_add_cols (lp, n); for (int i = 0; i < n; i++) { //-- Define type of the structural variables if (! freeLB[i] && ! freeUB[i]) { if ( lb[i] == ub[i] ) glp_set_col_bnds (lp, i+1, GLP_FX, lb[i], ub[i]); else glp_set_col_bnds (lp, i+1, GLP_DB, lb[i], ub[i]); } else { if (! freeLB[i] && freeUB[i]) glp_set_col_bnds (lp, i+1, GLP_LO, lb[i], ub[i]); else { if (freeLB[i] && ! freeUB[i]) glp_set_col_bnds (lp, i+1, GLP_UP, lb[i], ub[i]); else glp_set_col_bnds (lp, i+1, GLP_FR, lb[i], ub[i]); } } // -- Set the objective coefficient of the corresponding // -- structural variable. No constant term is assumed. glp_set_obj_coef(lp,i+1,c[i]); if (isMIP) glp_set_col_kind (lp, i+1, vartype[i]); } glp_add_rows (lp, m); for (int i = 0; i < m; i++) { /* If the i-th row has no lower bound (types F,U), the corrispondent parameter will be ignored. If the i-th row has no upper bound (types F,L), the corrispondent parameter will be ignored. If the i-th row is of S type, the i-th LB is used, but the i-th UB is ignored. */ switch (ctype[i]) { case 'F': typx = GLP_FR; break; // upper bound case 'U': typx = GLP_UP; break; // lower bound case 'L': typx = GLP_LO; break; // fixed constraint case 'S': typx = GLP_FX; break; // double-bounded variable case 'D': typx = GLP_DB; break; } if ( typx == GLP_DB && -b[i] < b[i]) { glp_set_row_bnds (lp, i+1, typx, -b[i], b[i]); } else if(typx == GLP_DB && -b[i] == b[i]) { glp_set_row_bnds (lp, i+1, GLP_FX, b[i], b[i]); } else { // this should be glp_set_row_bnds (lp, i+1, typx, -b[i], b[i]); glp_set_row_bnds (lp, i+1, typx, b[i], b[i]); } } // Load constraint matrix A glp_load_matrix (lp, nz, rn, cn, a); // Save problem if (save_pb) { if (!strcmp(filetype,"cplex")){ if (glp_write_lp (lp, NULL, save_filename) != 0) { mexErrMsgTxt("glpk: unable to write the problem"); longjmp (mark, -1); } }else{ if (!strcmp(filetype,"fixedmps")){ if (glp_write_mps (lp, GLP_MPS_DECK, NULL, save_filename) != 0) { mexErrMsgTxt("glpk: unable to write the problem"); longjmp (mark, -1); } }else{ if (!strcmp(filetype,"freemps")){ if (glp_write_mps (lp, GLP_MPS_FILE, NULL, save_filename) != 0) { mexErrMsgTxt("glpk: unable to write the problem"); longjmp (mark, -1); } }else{// plain text if (lpx_print_prob (lp, save_filename) != 0) { mexErrMsgTxt("glpk: unable to write the problem"); longjmp (mark, -1); } } } } } //-- scale the problem data (if required) if (! glpIntParam[16] || lpsolver != 1) { switch ( glpIntParam[1] ) { case ( 0 ): glp_scale_prob( lp, GLP_SF_SKIP ); break; case ( 1 ): glp_scale_prob( lp, GLP_SF_GM ); break; case ( 2 ): glp_scale_prob( lp, GLP_SF_EQ ); break; case ( 3 ): glp_scale_prob( lp, GLP_SF_AUTO ); break; case ( 4 ): glp_scale_prob( lp, GLP_SF_2N ); break; default : mexErrMsgTxt("glpk: unrecognized scaling option"); longjmp (mark, -1); } } else { /* do nothing? or unscale? glp_unscale_prob( lp ); */ } //-- build advanced initial basis (if required) if (lpsolver == 1 && ! glpIntParam[16]) glp_adv_basis (lp, 0); glp_smcp sParam; glp_init_smcp(&sParam); //-- set control parameters for simplex/exact method if (lpsolver == 1 || lpsolver == 3){ //remap of control parameters for simplex method sParam.msg_lev=glpIntParam[0]; // message level // simplex method: primal/dual switch ( glpIntParam[2] ) { case 0: sParam.meth=GLP_PRIMAL; break; case 1: sParam.meth=GLP_DUAL; break; case 2: sParam.meth=GLP_DUALP; break; default: mexErrMsgTxt("glpk: unrecognized primal/dual method"); longjmp (mark, -1); } // pricing technique if (glpIntParam[3]==0) sParam.pricing=GLP_PT_STD; else sParam.pricing=GLP_PT_PSE; // ratio test if (glpIntParam[20]==0) sParam.r_test = GLP_RT_STD; else sParam.r_test=GLP_RT_HAR; //tollerances sParam.tol_bnd=glpRealParam[1]; // primal feasible tollerance sParam.tol_dj=glpRealParam[2]; // dual feasible tollerance sParam.tol_piv=glpRealParam[3]; // pivot tollerance sParam.obj_ll=glpRealParam[4]; // lower limit sParam.obj_ul=glpRealParam[5]; // upper limit // iteration limit if (glpIntParam[5]==-1) sParam.it_lim=INT_MAX; else sParam.it_lim=glpIntParam[5]; // time limit if (glpRealParam[6]==-1) sParam.tm_lim=INT_MAX; else sParam.tm_lim=(int) glpRealParam[6]; sParam.out_frq=glpIntParam[7]; // output frequency sParam.out_dly=(int) glpRealParam[7]; // output delay // presolver if (glpIntParam[16]) sParam.presolve=GLP_ON; else sParam.presolve=GLP_OFF; }else{ for(int i = 0; i < NIntP; i++) { // skip assinging ratio test or if ( i == 18 || i == 20) continue; lpx_set_int_parm (lp, IParam[i], glpIntParam[i]); } for (int i = 0; i < NRealP; i++) { lpx_set_real_parm (lp, RParam[i], glpRealParam[i]); } } //set MIP params if MIP.... glp_iocp iParam; glp_init_iocp(&iParam); if ( isMIP ){ method = 'I'; switch (glpIntParam[0]) { //message level case 0: iParam.msg_lev = GLP_MSG_OFF; break; case 1: iParam.msg_lev = GLP_MSG_ERR; break; case 2: iParam.msg_lev = GLP_MSG_ON; break; case 3: iParam.msg_lev = GLP_MSG_ALL; break; default: mexErrMsgTxt("glpk: msg_lev bad param"); } switch (glpIntParam[14]) { //branching param case 0: iParam.br_tech = GLP_BR_FFV; break; case 1: iParam.br_tech = GLP_BR_LFV; break; case 2: iParam.br_tech = GLP_BR_MFV; break; case 3: iParam.br_tech = GLP_BR_DTH; break; default: mexErrMsgTxt("glpk: branch bad param"); } switch (glpIntParam[15]) { //backtracking heuristic case 0: iParam.bt_tech = GLP_BT_DFS; break; case 1: iParam.bt_tech = GLP_BT_BFS; break; case 2: iParam.bt_tech = GLP_BT_BLB; break; case 3: iParam.bt_tech = GLP_BT_BPH; break; default: mexErrMsgTxt("glpk: backtrack bad param"); } if ( glpRealParam[8] > 0.0 && glpRealParam[8] < 1.0 ) iParam.tol_int = glpRealParam[8]; // absolute tolorence else mexErrMsgTxt("glpk: tolint must be between 0 and 1"); iParam.tol_obj = glpRealParam[9]; // relative tolarence iParam.mip_gap = glpRealParam[10]; // realative gap tolerance // set time limit for mip if ( glpRealParam[6] < 0.0 || glpRealParam[6] > 1e6 ) iParam.tm_lim = INT_MAX; else iParam.tm_lim = (int)(1000.0 * glpRealParam[6] ); // Choose Cutsets for mip // shut all cuts off, then start over.... iParam.gmi_cuts = GLP_OFF; iParam.mir_cuts = GLP_OFF; iParam.cov_cuts = GLP_OFF; iParam.clq_cuts = GLP_OFF; switch( glpIntParam[17] ) { case 0: break; case 1: iParam.gmi_cuts = GLP_ON; break; case 2: iParam.mir_cuts = GLP_ON; break; case 3: iParam.cov_cuts = GLP_ON; break; case 4: iParam.clq_cuts = GLP_ON; break; case 5: iParam.clq_cuts = GLP_ON; iParam.gmi_cuts = GLP_ON; iParam.mir_cuts = GLP_ON; iParam.cov_cuts = GLP_ON; iParam.clq_cuts = GLP_ON; break; default: mexErrMsgTxt("glpk: cutset bad param"); } switch( glpIntParam[18] ) { // pre-processing for mip case 0: iParam.pp_tech = GLP_PP_NONE; break; case 1: iParam.pp_tech = GLP_PP_ROOT; break; case 2: iParam.pp_tech = GLP_PP_ALL; break; default: mexErrMsgTxt("glpk: pprocess bad param"); } if (glpIntParam[16]) iParam.presolve=GLP_ON; else iParam.presolve=GLP_OFF; if (glpIntParam[19]) iParam.binarize = GLP_ON; else iParam.binarize = GLP_OFF; } else { /* Choose simplex method ('S') or interior point method ('T') or Exact method ('E') to solve the problem */ switch (lpsolver) { case 1: method = 'S'; break; case 2: method = 'T'; break; case 3: method = 'E'; break; default: mexErrMsgTxt("glpk: lpsolver != lpsolver"); longjmp (mark, -1); } } // now run the problem... int errnum = 0; switch (method) { case 'I': errnum = glp_intopt( lp, &iParam ); errnum += 200; //this is to avoid ambiguity in the return codes. break; case 'S': errnum = glp_simplex(lp, &sParam); errnum += 100; //this is to avoid ambiguity in the return codes. break; case 'T': errnum = glp_interior(lp, NULL ); errnum += 300; //this is to avoid ambiguity in the return codes. break; case 'E': errnum = glp_exact(lp, &sParam); errnum += 100; //this is to avoid ambiguity in the return codes. break; default: /*xassert (method != method); */ mexErrMsgTxt("glpk: method != method"); longjmp (mark, -1); } if (errnum==100 || errnum==200 || errnum==300 || errnum==106 || errnum==107 || errnum==108 || errnum==109 || errnum==209 || errnum==214 || errnum==308) { // Get status and object value if (isMIP) { *status = glp_mip_status (lp); *fmin = glp_mip_obj_val (lp); } else { if (lpsolver == 1 || lpsolver == 3) { *status = glp_get_status (lp); *fmin = glp_get_obj_val (lp); } else { *status = glp_ipt_status (lp); *fmin = glp_ipt_obj_val (lp); } } // Get optimal solution (if exists) if (isMIP) { for (int i = 0; i < n; i++) xmin[i] = glp_mip_col_val (lp, i+1); } else { /* Primal values */ for (int i = 0; i < n; i++) { if (lpsolver == 1 || lpsolver == 3) xmin[i] = glp_get_col_prim (lp, i+1); else xmin[i] = glp_ipt_col_prim (lp, i+1); } /* Dual values */ for (int i = 0; i < m; i++) { if (lpsolver == 1 || lpsolver == 3) lambda[i] = glp_get_row_dual (lp, i+1); else lambda[i] = glp_ipt_row_dual (lp, i+1); } /* Reduced costs */ for (int i = 0; i < glp_get_num_cols (lp); i++) { if (lpsolver == 1 || lpsolver == 3) redcosts[i] = glp_get_col_dual (lp, i+1); else redcosts[i] = glp_ipt_col_dual (lp, i+1); } } *time = (clock () - t_start) / CLOCKS_PER_SEC; size_t tpeak; glp_mem_usage(NULL, NULL, NULL, &tpeak); *mem=((double) tpeak) / (1024); lpx_delete_prob(lp); return 0; } else { // printf("errnum is %d\n", errnum); } lpx_delete_prob(lp); /* this shouldn't be nessiary with glp_deleted_prob, but try it if we have weird behavior again... */ glp_free_env(); *status = errnum; return errnum; }
int glp_main(int argc, const char *argv[]) { /* stand-alone LP/MIP solver */ struct csa _csa, *csa = &_csa; int ret; xlong_t start; /* perform initialization */ csa->prob = glp_create_prob(); glp_get_bfcp(csa->prob, &csa->bfcp); glp_init_smcp(&csa->smcp); csa->smcp.presolve = GLP_ON; glp_init_iocp(&csa->iocp); csa->iocp.presolve = GLP_ON; csa->tran = NULL; csa->graph = NULL; csa->format = FMT_MPS_FILE; csa->in_file = NULL; csa->ndf = 0; csa->out_dpy = NULL; csa->solution = SOL_BASIC; csa->in_res = NULL; csa->dir = 0; csa->scale = 1; csa->out_sol = NULL; csa->out_res = NULL; csa->out_bnds = NULL; csa->check = 0; csa->new_name = NULL; csa->out_mps = NULL; csa->out_freemps = NULL; csa->out_cpxlp = NULL; csa->out_pb = NULL; csa->out_npb = NULL; csa->log_file = NULL; csa->crash = USE_ADV_BASIS; csa->exact = 0; csa->xcheck = 0; csa->nomip = 0; /* parse command-line parameters */ ret = parse_cmdline(csa, argc, argv); if (ret < 0) { ret = EXIT_SUCCESS; goto done; } if (ret > 0) { ret = EXIT_FAILURE; goto done; } /*--------------------------------------------------------------*/ /* remove all output files specified in the command line */ if (csa->out_dpy != NULL) remove(csa->out_dpy); if (csa->out_sol != NULL) remove(csa->out_sol); if (csa->out_res != NULL) remove(csa->out_res); if (csa->out_bnds != NULL) remove(csa->out_bnds); if (csa->out_mps != NULL) remove(csa->out_mps); if (csa->out_freemps != NULL) remove(csa->out_freemps); if (csa->out_cpxlp != NULL) remove(csa->out_cpxlp); if (csa->out_pb != NULL) remove(csa->out_pb); if (csa->out_npb != NULL) remove(csa->out_npb); if (csa->log_file != NULL) remove(csa->log_file); /*--------------------------------------------------------------*/ /* open log file, if required */ if (csa->log_file != NULL) { if (lib_open_log(csa->log_file)) { xprintf("Unable to create log file\n"); ret = EXIT_FAILURE; goto done; } } /*--------------------------------------------------------------*/ /* read problem data from the input file */ if (csa->in_file == NULL) { xprintf("No input problem file specified; try %s --help\n", argv[0]); ret = EXIT_FAILURE; goto done; } if (csa->format == FMT_MPS_DECK) { ret = glp_read_mps(csa->prob, GLP_MPS_DECK, NULL, csa->in_file); if (ret != 0) err1: { xprintf("MPS file processing error\n"); ret = EXIT_FAILURE; goto done; } } else if (csa->format == FMT_MPS_FILE) { ret = glp_read_mps(csa->prob, GLP_MPS_FILE, NULL, csa->in_file); if (ret != 0) goto err1; } else if (csa->format == FMT_CPLEX_LP) { ret = glp_read_lp(csa->prob, NULL, csa->in_file); if (ret != 0) { xprintf("CPLEX LP file processing error\n"); ret = EXIT_FAILURE; goto done; } } else if (csa->format == FMT_MATHPROG) { int k; /* allocate the translator workspace */ csa->tran = glp_mpl_alloc_wksp(); /* read model section and optional data section */ if (glp_mpl_read_model(csa->tran, csa->in_file, csa->ndf > 0)) err2: { xprintf("MathProg model processing error\n"); ret = EXIT_FAILURE; goto done; } /* read optional data section(s), if necessary */ for (k = 1; k <= csa->ndf; k++) { if (glp_mpl_read_data(csa->tran, csa->in_data[k])) goto err2; } /* generate the model */ if (glp_mpl_generate(csa->tran, csa->out_dpy)) goto err2; /* build the problem instance from the model */ glp_mpl_build_prob(csa->tran, csa->prob); } else if (csa->format == FMT_MIN_COST) { csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data)); ret = glp_read_mincost(csa->graph, offsetof(v_data, rhs), offsetof(a_data, low), offsetof(a_data, cap), offsetof(a_data, cost), csa->in_file); if (ret != 0) { xprintf("DIMACS file processing error\n"); ret = EXIT_FAILURE; goto done; } glp_mincost_lp(csa->prob, csa->graph, GLP_ON, offsetof(v_data, rhs), offsetof(a_data, low), offsetof(a_data, cap), offsetof(a_data, cost)); glp_set_prob_name(csa->prob, csa->in_file); } else if (csa->format == FMT_MAX_FLOW) { int s, t; csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data)); ret = glp_read_maxflow(csa->graph, &s, &t, offsetof(a_data, cap), csa->in_file); if (ret != 0) { xprintf("DIMACS file processing error\n"); ret = EXIT_FAILURE; goto done; } glp_maxflow_lp(csa->prob, csa->graph, GLP_ON, s, t, offsetof(a_data, cap)); glp_set_prob_name(csa->prob, csa->in_file); } else xassert(csa != csa); /*--------------------------------------------------------------*/ /* change problem name, if required */ if (csa->new_name != NULL) glp_set_prob_name(csa->prob, csa->new_name); /* change optimization direction, if required */ if (csa->dir != 0) glp_set_obj_dir(csa->prob, csa->dir); /* order rows and columns of the constraint matrix */ lpx_order_matrix(csa->prob); /*--------------------------------------------------------------*/ /* write problem data in fixed MPS format, if required */ if (csa->out_mps != NULL) { ret = glp_write_mps(csa->prob, GLP_MPS_DECK, NULL, csa->out_mps); if (ret != 0) { xprintf("Unable to write problem in fixed MPS format\n"); ret = EXIT_FAILURE; goto done; } } /* write problem data in free MPS format, if required */ if (csa->out_freemps != NULL) { ret = glp_write_mps(csa->prob, GLP_MPS_FILE, NULL, csa->out_freemps); if (ret != 0) { xprintf("Unable to write problem in free MPS format\n"); ret = EXIT_FAILURE; goto done; } } /* write problem data in CPLEX LP format, if required */ if (csa->out_cpxlp != NULL) { ret = glp_write_lp(csa->prob, NULL, csa->out_cpxlp); if (ret != 0) { xprintf("Unable to write problem in CPLEX LP format\n"); ret = EXIT_FAILURE; goto done; } } /* write problem data in OPB format, if required */ if (csa->out_pb != NULL) { ret = lpx_write_pb(csa->prob, csa->out_pb, 0, 0); if (ret != 0) { xprintf("Unable to write problem in OPB format\n"); ret = EXIT_FAILURE; goto done; } } /* write problem data in normalized OPB format, if required */ if (csa->out_npb != NULL) { ret = lpx_write_pb(csa->prob, csa->out_npb, 1, 1); if (ret != 0) { xprintf( "Unable to write problem in normalized OPB format\n"); ret = EXIT_FAILURE; goto done; } } /*--------------------------------------------------------------*/ /* if only problem data check is required, skip computations */ if (csa->check) { ret = EXIT_SUCCESS; goto done; } /*--------------------------------------------------------------*/ /* determine the solution type */ if (!csa->nomip && glp_get_num_int(csa->prob) + glp_get_num_bin(csa->prob) > 0) { if (csa->solution == SOL_INTERIOR) { xprintf("Interior-point method is not able to solve MIP pro" "blem; use --simplex\n"); ret = EXIT_FAILURE; goto done; } csa->solution = SOL_INTEGER; } /*--------------------------------------------------------------*/ /* if solution is provided, read it and skip computations */ if (csa->in_res != NULL) { if (csa->solution == SOL_BASIC) ret = glp_read_sol(csa->prob, csa->in_res); else if (csa->solution == SOL_INTERIOR) ret = glp_read_ipt(csa->prob, csa->in_res); else if (csa->solution == SOL_INTEGER) ret = glp_read_mip(csa->prob, csa->in_res); else xassert(csa != csa); if (ret != 0) { xprintf("Unable to read problem solution\n"); ret = EXIT_FAILURE; goto done; } goto skip; } /*--------------------------------------------------------------*/ /* scale the problem data, if required */ if (csa->scale) { if (csa->solution == SOL_BASIC && !csa->smcp.presolve || csa->solution == SOL_INTERIOR || csa->solution == SOL_INTEGER && !csa->iocp.presolve) glp_scale_prob(csa->prob, GLP_SF_AUTO); } /* construct starting LP basis */ if (csa->solution == SOL_BASIC && !csa->smcp.presolve || csa->solution == SOL_INTEGER && !csa->iocp.presolve) { if (csa->crash == USE_STD_BASIS) glp_std_basis(csa->prob); else if (csa->crash == USE_ADV_BASIS) glp_adv_basis(csa->prob, 0); else if (csa->crash == USE_CPX_BASIS) glp_cpx_basis(csa->prob); else xassert(csa != csa); } /*--------------------------------------------------------------*/ /* solve the problem */ start = xtime(); if (csa->solution == SOL_BASIC) { if (!csa->exact) { glp_set_bfcp(csa->prob, &csa->bfcp); glp_simplex(csa->prob, &csa->smcp); if (csa->xcheck) { if (csa->smcp.presolve && glp_get_status(csa->prob) != GLP_OPT) xprintf("If you need to check final basis for non-opt" "imal solution, use --nopresol\n"); else glp_exact(csa->prob, &csa->smcp); } if (csa->out_sol != NULL || csa->out_res != NULL) { if (csa->smcp.presolve && glp_get_status(csa->prob) != GLP_OPT) xprintf("If you need actual output for non-optimal solut" "ion, use --nopresol\n"); } } else glp_exact(csa->prob, &csa->smcp); } else if (csa->solution == SOL_INTERIOR) glp_interior(csa->prob, NULL); else if (csa->solution == SOL_INTEGER) { if (!csa->iocp.presolve) { glp_set_bfcp(csa->prob, &csa->bfcp); glp_simplex(csa->prob, &csa->smcp); } glp_intopt(csa->prob, &csa->iocp); } else xassert(csa != csa); /*--------------------------------------------------------------*/ /* display statistics */ xprintf("Time used: %.1f secs\n", xdifftime(xtime(), start)); { xlong_t tpeak; char buf[50]; lib_mem_usage(NULL, NULL, NULL, &tpeak); xprintf("Memory used: %.1f Mb (%s bytes)\n", xltod(tpeak) / 1048576.0, xltoa(tpeak, buf)); } /*--------------------------------------------------------------*/ skip: /* postsolve the model, if necessary */ if (csa->tran != NULL) { if (csa->solution == SOL_BASIC) ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_SOL); else if (csa->solution == SOL_INTERIOR) ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_IPT); else if (csa->solution == SOL_INTEGER) ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_MIP); else xassert(csa != csa); if (ret != 0) { xprintf("Model postsolving error\n"); ret = EXIT_FAILURE; goto done; } } /*--------------------------------------------------------------*/ /* write problem solution in printable format, if required */ if (csa->out_sol != NULL) { if (csa->solution == SOL_BASIC) ret = lpx_print_sol(csa->prob, csa->out_sol); else if (csa->solution == SOL_INTERIOR) ret = lpx_print_ips(csa->prob, csa->out_sol); else if (csa->solution == SOL_INTEGER) ret = lpx_print_mip(csa->prob, csa->out_sol); else xassert(csa != csa); if (ret != 0) { xprintf("Unable to write problem solution\n"); ret = EXIT_FAILURE; goto done; } } /* write problem solution in printable format, if required */ if (csa->out_res != NULL) { if (csa->solution == SOL_BASIC) ret = glp_write_sol(csa->prob, csa->out_res); else if (csa->solution == SOL_INTERIOR) ret = glp_write_ipt(csa->prob, csa->out_res); else if (csa->solution == SOL_INTEGER) ret = glp_write_mip(csa->prob, csa->out_res); else xassert(csa != csa); if (ret != 0) { xprintf("Unable to write problem solution\n"); ret = EXIT_FAILURE; goto done; } } /* write sensitivity bounds information, if required */ if (csa->out_bnds != NULL) { if (csa->solution == SOL_BASIC) { ret = lpx_print_sens_bnds(csa->prob, csa->out_bnds); if (ret != 0) { xprintf("Unable to write sensitivity bounds information " "\n"); ret = EXIT_FAILURE; goto done; } } else xprintf("Cannot write sensitivity bounds information for in" "terior-point or MIP solution\n"); } /*--------------------------------------------------------------*/ /* all seems to be ok */ ret = EXIT_SUCCESS; /*--------------------------------------------------------------*/ done: /* delete the LP/MIP problem object */ if (csa->prob != NULL) glp_delete_prob(csa->prob); /* free the translator workspace, if necessary */ if (csa->tran != NULL) glp_mpl_free_wksp(csa->tran); /* delete the network problem object, if necessary */ if (csa->graph != NULL) glp_delete_graph(csa->graph); xassert(gmp_pool_count() == 0); gmp_free_mem(); /* close log file, if necessary */ if (csa->log_file != NULL) lib_close_log(); /* check that no memory blocks are still allocated */ { int count; xlong_t total; lib_mem_usage(&count, NULL, &total, NULL); if (count != 0) xerror("Error: %d memory block(s) were lost\n", count); xassert(count == 0); xassert(total.lo == 0 && total.hi == 0); } /* free the library environment */ lib_free_env(); /* return to the control program */ return ret; }
double solve_glp_grb(glp_prob *mip, wrapper_params *par){ GLPK_out = par->glp_out; GRB_out = par->grb_out; double obj_val; /** GLPK: Generate Variable indexing **/ glp_create_index(mip); /** GLPK: Generate LP **/ glp_write_mps(mip, GLP_MPS_FILE, NULL, "tmp.mps"); /************/ /** GUROBI **/ /************/ retGRB = GRBloadenv(&env, NULL); if (retGRB || env == NULL) { fprintf(stderr, "Error: could not create environment\n"); exit(1); } retGRB = GRBsetintparam(env, "OutputFlag", GRB_out?1:0); if (retGRB) freeMem(); //retGRB = GRBsetintparam(env, "Sensitivity", 1); //if (retGRB) freeMem(); /** GUROBI: Read model **/ retGRB = GRBreadmodel(env, "tmp.mps", &model); if (retGRB) freeMem(); /** Remove utility files from disk **/ //remove("tmp.mps"); /** GUROBI: Get environment **/ mipenv = GRBgetenv(model); if (!mipenv) freeMem(); /** GUROBI: Set parameters **/ /** GUROBI: Ask for more precision **/ retGRB = GRBsetdblparam(mipenv, "FeasibilityTol", 10E-6); if (retGRB) freeMem(); retGRB = GRBsetdblparam(mipenv, "IntFeasTol", 10E-5); if (retGRB) freeMem(); retGRB = GRBsetdblparam(mipenv, "MIPgap", 10E-6); if (retGRB) freeMem(); /* * Playing with gurobi parameters and attr*/ //gurobi_set_basis(); retGRB = GRBsetintparam(mipenv, "Cuts", 3); if (retGRB) freeMem(); retGRB = GRBsetintparam(mipenv, "RootMethod", 1); if (retGRB) freeMem(); retGRB = GRBsetintparam(mipenv, "Symmetry", -1); if (retGRB) freeMem(); /** GUROBI: get numvars and numrows **/ retGRB = GRBgetintattr(model, "NumVars", &numvars); if (retGRB) freeMem(); /** Test variable names */ for(int j=0;j<numvars;j++){ retGRB = GRBgetstrattrelement(model, "VarName", j, &nameGRB); printf("GRB Var %d Name %s\n",j,nameGRB); } /** GUROBI: get model type **/ retGRB = GRBgetintattr(model, "IsMIP", &GRB_IsMIP); if (retGRB) freeMem(); /** GUROBI: Optimize model **/ retGRB = GRBoptimize(model); if (retGRB) freeMem(); /** GUROBI: Retreive the optimization status **/ GRBgetintattr(model, "Status", &retGRB); switch(retGRB){ case GRB_OPTIMAL: break; case GRB_INFEASIBLE : fprintf(stderr, "Error GRB optimization failed with code GRB_INFEASIBLE\n"); case GRB_INF_OR_UNBD : fprintf(stderr, "Error GRB optimization failed with code GRB_INF_OR_UNBD \n"); case GRB_UNBOUNDED : fprintf(stderr, "Error GRB optimization failed with code GRB_UNBOUNDED \n"); case GRB_CUTOFF : fprintf(stderr, "Error GRB optimization failed with code GRB_CUTOFF \n"); case GRB_ITERATION_LIMIT : fprintf(stderr, "Error GRB optimization failed with code GRB_ITERATION_LIMIT \n"); case GRB_NODE_LIMIT : fprintf(stderr, "Error GRB optimization failed with code GRB_NODE_LIMIT \n"); case GRB_TIME_LIMIT : fprintf(stderr, "Error GRB optimization failed with code GRB_TIME_LIMIT \n"); case GRB_SOLUTION_LIMIT : fprintf(stderr, "Error GRB optimization failed with code GRB_SOLUTION_LIMIT \n"); case GRB_INTERRUPTED : fprintf(stderr, "Error GRB optimization failed with code GRB_INTERRUPTED \n"); case GRB_SUBOPTIMAL : fprintf(stderr, "Error GRB optimization failed with code GRB_SUBOPTIMAL \n"); case GRB_NUMERIC : fprintf(stderr, "Error GRB optimization failed with code GRB_NUMERIC \n"); /** GUROBI: Quit in any case non optimal **/ freeMem(); } /** GUROBI: Get obj function value **/ retGRB = GRBgetdblattr(model, "IntVio", &tmp); if (retGRB) freeMem(); retGRB = GRBgetdblattr(model, "ObjBound", &bound); if (retGRB) freeMem(); retGRB = GRBgetdblattr(model, "ObjVal", &tmp); if (retGRB) freeMem(); /* ********************** */ obj_val = tmp; /* ************ */ if (verbose) printf ("Objective %lf\n", tmp); if (verbose) printf ("Best bound %lf\n", bound); if (verbose) printf ("Absolute gap %lf\n", fabs(tmp - bound)); /** GUROBI: Get variable values **/ for (j = 0; j < numvars; ++j){ retGRB = GRBgetdblattrelement(model, "X", j, &tmp); if (retGRB) freeMem(); retGRB = GRBgetstrattrelement(model, "VarName", j, &nameGRB); printf("GRB Var %d Name %s\n",j,nameGRB); if (retGRB) freeMem(); retGRB = GRBgetcharattrelement(model, "VType", j, &type); if (retGRB) freeMem(); /** GLPK search variable index by name **/ col_index = glp_find_col(mip, nameGRB); if (col_index != 0){ /** GLPK set variable bounds **/ if ((type == 'B') || (type == 'I')){ if (verbose) printf ("Variable %s is of type %c value %lf fixed to %lf\n", nameGRB, type, tmp, round(tmp)); glp_set_col_bnds(mip, col_index, GLP_FX, round(tmp), round(tmp)); } else{ if (verbose) printf ("Variable %s is of type %c value %lf fixed to %lf\n", nameGRB, type, tmp, tmp); glp_set_col_bnds(mip, col_index, GLP_FX, tmp, tmp); } } } if (GRB_IsMIP){ /** GLPK initialize parameters **/ iparm = (glp_iocp*) malloc(sizeof(glp_iocp)); glp_init_iocp(iparm); iparm->presolve = GLP_ON; iparm->mip_gap = glpk_iparm_mip_gap; iparm->tol_int = glpk_iparm_tol_int; iparm->tol_obj = glpk_iparm_tol_obj; /** GLPK get the optimal integer solution **/ ret = glp_intopt(mip, iparm); if (ret){ fprintf(stderr, "glp_intopt, Error on optimizing the model : %d \n", ret); freeMem(); } ret = glp_mip_status(mip); switch (ret){ case GLP_OPT: break; case GLP_FEAS: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_FEAS, code %d\n", ret); freeMem(); case GLP_NOFEAS: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_NOFEAS, code %d\n", ret); freeMem(); case GLP_UNDEF: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNDEF, code %d\n", ret); freeMem(); } } else{ /*GLPK initialize parameters */ parm = (glp_smcp*) malloc(sizeof(glp_smcp)); glp_init_smcp(parm); parm->meth = GLP_DUALP; parm->tol_bnd = 10E-4; parm->tol_dj = 10E-4; /* GLPK get the optimal basis */ //ret = glp_simplex(mip, parm); if (ret){ fprintf(stderr, "glp_simplex, Error on optimizing the model : %d \n", ret); freeMem(); } ret = glp_get_status(mip); switch (ret){ case GLP_OPT: break; case GLP_FEAS: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_FEAS, code %d\n", ret); freeMem(); case GLP_INFEAS: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_INFEAS, code %d\n", ret); freeMem(); case GLP_NOFEAS: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_NOFEAS, code %d\n", ret); freeMem(); case GLP_UNBND: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNBND, code %d\n", ret); freeMem(); case GLP_UNDEF: fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNDEF, code %d\n", ret); freeMem(); } } //GRBmodel *fmod = fixed_model(model); //gurobi_sens_output(fmod, "/tmp/sens.sol"); GRBwrite(model, "/tmp/model.sol"); /** GUROBI: free structures **/ if (model) GRBfreemodel(model); if (env) GRBfreeenv(env); return obj_val; }