int lpx_mip_status(glp_prob *lp) { /* retrieve status of MIP solution */ int status; switch (glp_mip_status(lp)) { case GLP_UNDEF: status = LPX_I_UNDEF; break; case GLP_OPT: status = LPX_I_OPT; break; case GLP_FEAS: status = LPX_I_FEAS; break; case GLP_NOFEAS: status = LPX_I_NOFEAS; break; default: xassert(lp != lp); } return status; }
int CMyProblem::PrintMIPSolution(ostream &out) { glp_create_index(lp); out << "MIP solution" << endl; out << "Dir;" << ((glp_get_obj_dir(lp)==GLP_MIN) ? "min" : "max") << endl; out << "f;" << glp_mip_obj_val(lp) << endl; out << "Status;" << DecodeStatus(glp_mip_status(lp)) << endl; PrintSolArray(lp,"x",out,true); PrintSolArray(lp,"y",out,true); glp_delete_index(lp); return 0; }
static PyObject* LPX_getstatus(LPXObject *self, void *closure) { int status; switch (self->last_solver) { case -1: case 0: status=glp_get_status(LP); break; case 1: status=glp_ipt_status(LP); break; case 2: status=glp_mip_status(LP); break; default: PyErr_SetString(PyExc_RuntimeError, "bad internal state for last solver identifier"); return NULL; } return glpstatus2string(status); }
int main() { // Variáveis auxiliares int i, j, constraintNumber, *constraintIndices; double *constraintCoefficients; // Aloca os vetores utilizados para criar as restrições do problema // *********************************************************************************************** // ATENÇÃO ===> É importante dizer que estes vetores serão utilizados da posição 1 em diante // Ou seja, no GLPK você aloca uma posição a mais e descarta a posição 0 dos vetores. // *********************************************************************************************** constraintIndices = (int*)malloc((n+1)*sizeof(int)); constraintCoefficients = (double*)malloc((n+1)*sizeof(double)); // Cria um modelo com nenhuma variável e nenhuma restrição glp_prob *model = glp_create_prob(); // Define o sentido da otimização que, para este problema, é minimização glp_set_obj_dir(model, GLP_MIN); // Cria as variáveis (colunas) no modelo // Para este problema são necessárias n*n variáveis // Estas n*n variáveis são definidas pelo GLPK através dos indices que vão de 1 até n*n (x1, x2, ..., x(n*n)) // Portanto, neste momento é importante determinar qual variável no GLPK (índice) representará qual variável x[i,j] // Para tanto, fazemos o mapeamento das variáveis x[i,j] utilizando a fórmula (i-1)*n + j // Isto é, a variável x[i,j] será representada pela variável de índice (i-1)*n + j no modelo do GLPK // Note que é imprescindível que cada índice (variável do GLPK) seja associado a no máximo uma variável x[i,j] // Caso contrário, uma variável do GLPK pode representar duas variáveis x[i,j] diferentes que assumem valores distintos nas soluções ótimas // Neste caso, o modelo estará incorreto glp_add_cols(model, n*n); // Ajuste dos tipos, limitantes e coeficientes da função objetivo das variáveis do modelo for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { // Define o tipo da variável como sendo binária (em outros modelos poderia ser contínua (GLP_CV) ou inteira (GLP_IV)) glp_set_col_kind(model, (i-1)*n + j, GLP_BV); // Define o limitante inferior (0) e superior (1) da variável // Consultem no manual as outras forma para definir apenas o limitante inferior ou superior glp_set_col_bnds(model, (i-1)*n + j, GLP_DB, 0.0, 1.0); // Define o coeficiente da variável na função objetivo glp_set_obj_coef(model, (i-1)*n + j, c[i-1][j-1]); } // Cria no modelo 2n restrições (linhas) nulas (com os coeficientes e limitantes zerados) // Ou seja, neste momento é criada uma matriz de zeros que correspondem aos coeficientes das restrições do modelo // O próximo passo será modificar esta matriz de tal forma que ela represente as restrições do problema descrito glp_add_rows(model, 2*n); // Esta variável define qual das restrições (qual linha da matriz de coeficientes) estamos modificando // ************************************************************************************************************ // ATENÇÃO: perceba que as restrições (linhas), assim como as variáveis (colunas), são indexadas a partir de 1. // ************************************************************************************************************ constraintNumber = 1; // Preenchimento das restrições limitando a soma das linhas: // sum{j in 1..n} w[i,j]*x[i,j] <= u[i] para i in 1..n for (i = 1; i <= n; i++) { // Define o limite superior (RHS) da restrição glp_set_row_bnds(model, constraintNumber, GLP_UP, 0.0, u[i-1]); for (j = 1; j <= n; j++) { // Ajusta o índice da variável que será informado à rotina do GLPK constraintIndices[j] = (i-1)*n + j; // Ajusta o coeficiente da variável cujo índice foi definido na linha anterior para ser informado ao GLPK // ****************************************************************************************************** // ATENÇÃO: perceba que na matriz w os índices e colunas são indexados a partir de ZERO ! // ****************************************************************************************************** constraintCoefficients[j] = w[i-1][j-1]; } // Passa ao GLPK a restrição que acabou de ser definida nos vetores constraintIndices e constraintCoefficients glp_set_mat_row(model, constraintNumber, n, constraintIndices, constraintCoefficients); // atualiza o indice da próxima restrição a ser inserida constraintNumber++; } // Preenchimento das restrições limitando a soma das colunas: // sum{i in 1..n} w[i,j]*x[i,j] >= l[i] para j in 1..n for (j = 1; j <= n; j++) { // Define o limite inferior (RHS) da restrição glp_set_row_bnds(model, constraintNumber, GLP_LO, l[j-1], 0.0); for (i = 1; i <= n; i++) { // Ajusta o índice da variável que será informado a rotina do GLPK constraintIndices[i] = (i-1)*n + j; // Ajusta o coeficiente da variável cujo índice foi definido na linha anterior para ser informado ao GLPK constraintCoefficients[i] = w[i-1][j-1]; } // Passa ao GLPK a restrição que acabou de ser definida nos vetores constraintIndices e constraintCoefficients glp_set_mat_row(model, constraintNumber, n, constraintIndices, constraintCoefficients); // atualiza o indice da próxima restrição a ser inserida constraintNumber++; } // Define os parâmetros que serão passados ao resolvedor glp_iocp param; glp_init_iocp(¶m); // Ativa o presolver param.presolve = GLP_ON; // Resolve o modelo int status = glp_intopt(model, ¶m); // Verifica se houve algum erro durante a otimização if (status) { printf("Ocorreu um erro durante o processo de otimizacao.\n"); } else { // Verifica se o método encontrou uma solução status = glp_mip_status(model); if ((status == GLP_OPT) || (status == GLP_FEAS)) { // Imprime a solução encontrada if (status == GLP_OPT) printf("Solucao otima encontrada!\n"); else printf("A solucao encontrada pode nao ser otima!\n"); printf("Custo da solucao: %f\n", glp_mip_obj_val(model)); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) printf("%f ", glp_mip_col_val(model, (i-1)*n + j)); printf("\n"); } } else { printf("Nenhuma solucao foi encontrada!\n"); } } // Desaloca os vetores free(constraintIndices); free(constraintCoefficients); return 0; }
/** * Solves the MLP problem * * @param mlp the MLP Handle * @param s_ctx context to return results * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure */ int mlp_solve_mlp_problem (struct GAS_MLP_Handle *mlp, struct GAS_MLP_SolutionContext *s_ctx) { int res; struct GNUNET_TIME_Relative duration; struct GNUNET_TIME_Absolute end; struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get(); /* solve MLP problem */ res = glp_intopt(mlp->prob, &mlp->control_param_mlp); if (res == 0) { /* The MLP problem instance has been successfully solved. */ } else if (res == GLP_EITLIM) { /* simplex iteration limit has been exceeded. */ // TODO Increase iteration limit? } else if (res == GLP_ETMLIM) { /* Time limit has been exceeded. */ // TODO Increase time limit? } else { /* Problem was ill-defined, no way to handle that */ GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-mlp", "Solving MLP problem failed: %s\n", mlp_solve_to_string(res)); return GNUNET_SYSERR; } end = GNUNET_TIME_absolute_get (); duration = GNUNET_TIME_absolute_get_difference (start, end); mlp->mlp_solved++; mlp->mlp_total_duration =+ duration.rel_value; s_ctx->mlp_duration = duration; GNUNET_STATISTICS_update (mlp->stats,"# MLP problem solved", 1, GNUNET_NO); GNUNET_STATISTICS_set (mlp->stats,"# MLP execution time (ms)", duration.rel_value, GNUNET_NO); GNUNET_STATISTICS_set (mlp->stats,"# MLP execution time average (ms)", mlp->mlp_total_duration / mlp->mlp_solved, GNUNET_NO); /* Analyze problem status */ res = glp_mip_status(mlp->prob); switch (res) { /* solution is optimal */ case GLP_OPT: /* solution is feasible */ case GLP_FEAS: break; /* Problem was ill-defined, no way to handle that */ default: GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-mlp", "Solving MLP problem failed, %s\n\n", mlp_status_to_string(res)); return GNUNET_SYSERR; break; } return GNUNET_OK; }
int glp_print_mip(glp_prob *P, const char *fname) { /* write MIP solution in printable format */ glp_file *fp; GLPROW *row; GLPCOL *col; int i, j, t, ae_ind, re_ind, ret; double ae_max, re_max; xprintf("Writing MIP solution to '%s'...\n", fname); fp = glp_open(fname, "w"); if (fp == NULL) { xprintf("Unable to create '%s' - %s\n", fname, get_err_msg()); ret = 1; goto done; } xfprintf(fp, "%-12s%s\n", "Problem:", P->name == NULL ? "" : P->name); xfprintf(fp, "%-12s%d\n", "Rows:", P->m); xfprintf(fp, "%-12s%d (%d integer, %d binary)\n", "Columns:", P->n, glp_get_num_int(P), glp_get_num_bin(P)); xfprintf(fp, "%-12s%d\n", "Non-zeros:", P->nnz); t = glp_mip_status(P); xfprintf(fp, "%-12s%s\n", "Status:", t == GLP_OPT ? "INTEGER OPTIMAL" : t == GLP_FEAS ? "INTEGER NON-OPTIMAL" : t == GLP_NOFEAS ? "INTEGER EMPTY" : t == GLP_UNDEF ? "INTEGER UNDEFINED" : "???"); xfprintf(fp, "%-12s%s%s%.10g (%s)\n", "Objective:", P->obj == NULL ? "" : P->obj, P->obj == NULL ? "" : " = ", P->mip_obj, P->dir == GLP_MIN ? "MINimum" : P->dir == GLP_MAX ? "MAXimum" : "???"); xfprintf(fp, "\n"); xfprintf(fp, " No. Row name Activity Lower bound " " Upper bound\n"); xfprintf(fp, "------ ------------ ------------- ------------- " "-------------\n"); for (i = 1; i <= P->m; i++) { row = P->row[i]; xfprintf(fp, "%6d ", i); if (row->name == NULL || strlen(row->name) <= 12) xfprintf(fp, "%-12s ", row->name == NULL ? "" : row->name); else xfprintf(fp, "%s\n%20s", row->name, ""); xfprintf(fp, "%3s", ""); xfprintf(fp, "%13.6g ", fabs(row->mipx) <= 1e-9 ? 0.0 : row->mipx); if (row->type == GLP_LO || row->type == GLP_DB || row->type == GLP_FX) xfprintf(fp, "%13.6g ", row->lb); else xfprintf(fp, "%13s ", ""); if (row->type == GLP_UP || row->type == GLP_DB) xfprintf(fp, "%13.6g ", row->ub); else xfprintf(fp, "%13s ", row->type == GLP_FX ? "=" : ""); xfprintf(fp, "\n"); } xfprintf(fp, "\n"); xfprintf(fp, " No. Column name Activity Lower bound " " Upper bound\n"); xfprintf(fp, "------ ------------ ------------- ------------- " "-------------\n"); for (j = 1; j <= P->n; j++) { col = P->col[j]; xfprintf(fp, "%6d ", j); if (col->name == NULL || strlen(col->name) <= 12) xfprintf(fp, "%-12s ", col->name == NULL ? "" : col->name); else xfprintf(fp, "%s\n%20s", col->name, ""); xfprintf(fp, "%s ", col->kind == GLP_CV ? " " : col->kind == GLP_IV ? "*" : "?"); xfprintf(fp, "%13.6g ", fabs(col->mipx) <= 1e-9 ? 0.0 : col->mipx); if (col->type == GLP_LO || col->type == GLP_DB || col->type == GLP_FX) xfprintf(fp, "%13.6g ", col->lb); else xfprintf(fp, "%13s ", ""); if (col->type == GLP_UP || col->type == GLP_DB) xfprintf(fp, "%13.6g ", col->ub); else xfprintf(fp, "%13s ", col->type == GLP_FX ? "=" : ""); xfprintf(fp, "\n"); } xfprintf(fp, "\n"); xfprintf(fp, "Integer feasibility conditions:\n"); xfprintf(fp, "\n"); glp_check_kkt(P, GLP_MIP, GLP_KKT_PE, &ae_max, &ae_ind, &re_max, &re_ind); xfprintf(fp, "KKT.PE: max.abs.err = %.2e on row %d\n", ae_max, ae_ind); xfprintf(fp, " max.rel.err = %.2e on row %d\n", re_max, re_ind); xfprintf(fp, "%8s%s\n", "", re_max <= 1e-9 ? "High quality" : re_max <= 1e-6 ? "Medium quality" : re_max <= 1e-3 ? "Low quality" : "SOLUTION IS WRONG"); xfprintf(fp, "\n"); glp_check_kkt(P, GLP_MIP, GLP_KKT_PB, &ae_max, &ae_ind, &re_max, &re_ind); xfprintf(fp, "KKT.PB: max.abs.err = %.2e on %s %d\n", ae_max, ae_ind <= P->m ? "row" : "column", ae_ind <= P->m ? ae_ind : ae_ind - P->m); xfprintf(fp, " max.rel.err = %.2e on %s %d\n", re_max, re_ind <= P->m ? "row" : "column", re_ind <= P->m ? re_ind : re_ind - P->m); xfprintf(fp, "%8s%s\n", "", re_max <= 1e-9 ? "High quality" : re_max <= 1e-6 ? "Medium quality" : re_max <= 1e-3 ? "Low quality" : "SOLUTION IS INFEASIBLE"); xfprintf(fp, "\n"); xfprintf(fp, "End of output\n"); #if 0 /* FIXME */ xfflush(fp); #endif if (glp_ioerr(fp)) { xprintf("Write error on '%s' - %s\n", fname, get_err_msg()); ret = 1; goto done; } ret = 0; done: if (fp != NULL) glp_close(fp); return ret; }
static void maybe_check_results(const int ppl_status, const double ppl_optimum_value) { const char* ppl_status_string; const char* glpk_status_string; int glpk_status; int treat_as_lp = 0; glp_smcp glpk_smcp; if (!check_results) return; if (no_mip || glpk_lp_num_int == 0) treat_as_lp = 1; glp_set_obj_dir(glpk_lp, (maximize ? GLP_MAX : GLP_MIN)); glp_init_smcp(&glpk_smcp); /* Disable GLPK output. */ glpk_smcp.msg_lev = GLP_MSG_OFF; if (treat_as_lp) { /* Set the problem class to LP: MIP problems are thus treated as LP ones. */ glp_exact(glpk_lp, &glpk_smcp); glpk_status = glp_get_status(glpk_lp); } else { /* MIP case. */ glp_simplex(glpk_lp, &glpk_smcp); glpk_status = glp_get_status(glpk_lp); if (glpk_status != GLP_NOFEAS && glpk_status != GLP_UNBND) { glp_iocp glpk_iocp; glp_init_iocp(&glpk_iocp); /* Disable GLPK output. */ glpk_iocp.msg_lev = GLP_MSG_OFF; glp_intopt(glpk_lp, &glpk_iocp); glpk_status = glp_mip_status(glpk_lp); } } /* If no_optimization is enabled, the second case is not possibile. */ if (!((ppl_status == PPL_MIP_PROBLEM_STATUS_UNFEASIBLE && glpk_status == GLP_NOFEAS) || (ppl_status == PPL_MIP_PROBLEM_STATUS_UNBOUNDED && glpk_status == GLP_UNBND) || (ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED && (glpk_status == GLP_OPT /* If no_optimization is enabled, check if the problem is unbounded for GLPK. */ || (no_optimization && (glpk_status == GLP_UNBND || glpk_status == GLP_UNDEF)))))) { if (ppl_status == PPL_MIP_PROBLEM_STATUS_UNFEASIBLE) ppl_status_string = "unfeasible"; else if (ppl_status == PPL_MIP_PROBLEM_STATUS_UNBOUNDED) ppl_status_string = "unbounded"; else if (ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED) ppl_status_string = "optimizable"; else ppl_status_string = "<?>"; switch (glpk_status) { case GLP_NOFEAS: glpk_status_string = "unfeasible"; break; case GLP_UNBND: glpk_status_string = "unbounded"; break; case GLP_OPT: glpk_status_string = "optimizable"; break; case GLP_UNDEF: glpk_status_string = "undefined"; break; default: glpk_status_string = "<?>"; break; } error("check failed: for GLPK the problem is %s, not %s", glpk_status_string, ppl_status_string); check_results_failed = 1; } else if (!no_optimization && ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED) { double glpk_optimum_value = (treat_as_lp ? glp_get_obj_val(glpk_lp) : glp_mip_obj_val(glpk_lp)); if (fabs(ppl_optimum_value - glpk_optimum_value) > check_threshold) { error("check failed: for GLPK the problem's optimum is %.20g," " not %.20g", glpk_optimum_value, ppl_optimum_value); check_results_failed = 1; } } return; }
OptSolutionData* GLPKRunSolver(int ProbType) { OptSolutionData* NewSolution = NULL; int NumVariables = glp_get_num_cols(GLPKModel); int Status = 0; if (ProbType == MILP) { Status = glp_simplex(GLPKModel, NULL); // Use default settings if (Status != 0) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } Status = glp_intopt(GLPKModel, NULL); // Use default settings if (Status != 0) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } NewSolution = new OptSolutionData; Status = glp_mip_status(GLPKModel); if (Status == GLP_UNDEF || Status == GLP_NOFEAS) { NewSolution->Status = INFEASIBLE; return NewSolution; } else if (Status == GLP_FEAS) { NewSolution->Status = UNBOUNDED; return NewSolution; } else if (Status == GLP_OPT) { NewSolution->Status = SUCCESS; } else { delete NewSolution; FErrorFile() << "Problem status unrecognized." << endl; FlushErrorFile(); return NULL; } NewSolution->Objective = glp_mip_obj_val(GLPKModel); NewSolution->SolutionData.resize(NumVariables); for (int i=0; i < NumVariables; i++) { NewSolution->SolutionData[i] = glp_mip_col_val(GLPKModel, i+1); } } else if (ProbType == LP) { //First we check the basis matrix to ensure it is not singular if (glp_warm_up(GLPKModel) != 0) { glp_adv_basis(GLPKModel, 0); } Status = glp_simplex(GLPKModel, NULL); // Use default settings if (Status == GLP_EBADB) { /* the basis is invalid; build some valid basis */ glp_adv_basis(GLPKModel, 0); Status = glp_simplex(GLPKModel, NULL); // Use default settings } if (Status != 0) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } NewSolution = new OptSolutionData; Status = glp_get_status(GLPKModel); if (Status == GLP_INFEAS || Status == GLP_NOFEAS || Status == GLP_UNDEF) { cout << "Model is infeasible" << endl; FErrorFile() << "Model is infeasible" << endl; FlushErrorFile(); NewSolution->Status = INFEASIBLE; return NewSolution; } else if (Status == GLP_FEAS || Status == GLP_UNBND) { cout << "Model is unbounded" << endl; FErrorFile() << "Model is unbounded" << endl; FlushErrorFile(); NewSolution->Status = UNBOUNDED; return NewSolution; } else if (Status == GLP_OPT) { NewSolution->Status = SUCCESS; } else { delete NewSolution; FErrorFile() << "Problem status unrecognized." << endl; FlushErrorFile(); return NULL; } NewSolution->Objective = glp_get_obj_val(GLPKModel); NewSolution->SolutionData.resize(NumVariables); for (int i=0; i < NumVariables; i++) { NewSolution->SolutionData[i] = glp_get_col_prim(GLPKModel, i+1); } } else { FErrorFile() << "Optimization problem type cannot be handled by GLPK solver." << endl; FlushErrorFile(); return NULL; } return NewSolution; }
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(); // Obsolete //lib_set_fault_hook (NULL, glpk_fault_hook); //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 glp_prob *lp = glp_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]) 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; } 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 (lpx_write_cpxlp (lp, save_filename) != 0) { mexErrMsgTxt("glpkcc: unable to write the problem"); longjmp (mark, -1); } }else{ if (!strcmp(filetype,"fixedmps")){ if (lpx_write_mps (lp, save_filename) != 0) { mexErrMsgTxt("glpkcc: unable to write the problem"); longjmp (mark, -1); } }else{ if (!strcmp(filetype,"freemps")){ if (lpx_write_freemps (lp, save_filename) != 0) { mexErrMsgTxt("glpkcc: unable to write the problem"); longjmp (mark, -1); } }else{// plain text if (lpx_print_prob (lp, save_filename) != 0) { mexErrMsgTxt("glpkcc: unable to write the problem"); longjmp (mark, -1); } } } } } //-- scale the problem data (if required) if (glpIntParam[1] && (! glpIntParam[16] || lpsolver != 1)) lpx_scale_prob (lp); //-- build advanced initial basis (if required) if (lpsolver == 1 && ! glpIntParam[16]) lpx_adv_basis (lp); glp_smcp sParam; glp_init_smcp(&sParam); //-- set control parameters if (lpsolver==1){ //remap of control parameters for simplex method sParam.msg_lev=glpIntParam[0]; // message level // simplex method: primal/dual if (glpIntParam[2]==0) sParam.meth=GLP_PRIMAL; else sParam.meth=GLP_DUALP; // pricing technique if (glpIntParam[3]==0) sParam.pricing=GLP_PT_STD; else sParam.pricing=GLP_PT_PSE; //sParam.r_test not available 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++) 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]); } // Choose simplex method ('S') or interior point method ('T') to solve the problem if (lpsolver == 1) method = 'S'; else method = 'T'; int errnum; switch (method){ case 'S': { if (isMIP){ method = 'I'; errnum = lpx_intopt (lp); } else{ errnum = glp_simplex(lp, &sParam); errnum += 100; //this is to avoid ambiguity in the return codes. } } break; case 'T': errnum = lpx_interior(lp); break; default: xassert (method != method); } /* errnum assumes the following results: errnum = 0 <=> No errors errnum = 1 <=> Iteration limit exceeded. errnum = 2 <=> Numerical problems with basis matrix. */ if (errnum == LPX_E_OK || errnum==100){ // Get status and object value if (isMIP) { *status = glp_mip_status (lp); *fmin = glp_mip_obj_val (lp); } else { if (lpsolver == 1) { *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) 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) 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) 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; glp_ulong tpeak; lib_mem_usage(NULL, NULL, NULL, &tpeak); *mem=(double)(4294967296.0 * tpeak.hi + tpeak.lo) / (1024); glp_delete_prob (lp); return 0; } glp_delete_prob (lp); *status = errnum; return errnum; }
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; }
void fence_insertert::solve() { #ifdef HAVE_GLPK ilpt ilp; instrumenter.message.statistics() << "po^+ edges considered:" << unique << " cycles:" << instrumenter.set_of_cycles.size() << messaget::eom; /* sets the variables and coefficients */ //nb of po+ considered * types of fences (_e) unsigned i=1; mip_set_var(ilp, i); /* sets the constraints */ mip_set_cst(ilp, i); instrumenter.message.debug() << "3: " << i << messaget::eom; assert(i-1==constraints_number); const unsigned const_constraints_number=constraints_number; const unsigned const_unique=unique; const unsigned mat_size=const_unique*fence_options*const_constraints_number; instrumenter.message.statistics() << "size of the system: " << mat_size << messaget::eom; instrumenter.message.statistics() << "# of constraints: " << const_constraints_number << messaget::eom; instrumenter.message.statistics() << "# of variables: " << const_unique*fence_options << messaget::eom; ilp.set_size(mat_size); #ifdef DEBUG print_vars(); #endif /* fills the constraints coeff */ /* tables read from 1 in glpk -- first row/column ignored */ mip_fill_matrix(ilp, i, const_constraints_number, const_unique); instrumenter.message.statistics() << "i: " << i << " mat_size: " << mat_size << messaget::eom; //assert(i-1==mat_size); #ifdef DEBUG for(i=1; i<=mat_size; ++i) instrumenter.message.debug() << i << "[" << ilp.imat[i] << "," << ilp.jmat[i] << "]=" << ilp.vmat[i] << messaget::eom; #endif /* solves MIP by branch-and-cut */ ilp.solve(); #ifdef DEBUG print_vars(); #endif /* checks optimality */ switch(glp_mip_status(ilp.lp)) { case GLP_OPT: instrumenter.message.result() << "Optimal solution found" << messaget::eom; break; case GLP_UNDEF: instrumenter.message.result() << "Solution undefined" << messaget::eom; assert(0); case GLP_FEAS: instrumenter.message.result() << "Solution feasible, yet not proven \ optimal, due to early termination" << messaget::eom; break; case GLP_NOFEAS: instrumenter.message.result() << "No feasible solution, the system is UNSAT" << messaget::eom; assert(0); } event_grapht& egraph=instrumenter.egraph; /* loads results (x_i) */ instrumenter.message.statistics() << "minimal cost: " << glp_mip_obj_val(ilp.lp) << messaget::eom; for(unsigned j=1; j<=const_unique*fence_options; ++j) { if(glp_mip_col_val(ilp.lp, j)>=1) { /* insert that fence */ assert(map_to_e.find(col_to_var(j))!=map_to_e.end()); const edget& delay = map_to_e.find(col_to_var(j))->second; instrumenter.message.statistics() << delay.first << " -> " << delay.second << " : " << to_string(col_to_fence(j)) << messaget::eom; instrumenter.message.statistics() << "(between " << egraph[delay.first].source_location << " and " << egraph[delay.second].source_location << messaget::eom; fenced_edges.insert(std::pair<edget,fence_typet>(delay, col_to_fence(j))); } } #else throw "Sorry, musketeer requires glpk; please recompile\ musketeer with glpk."; #endif }
int DBWorker::_RememberRun(CMyProblem &P, int idobjectives, const char* modelfile, double time, bool mip, int idruns) { int idrun = -1; try { sql::PreparedStatement *PrepStmt; sql::ResultSet *res; PrepStmt = con->prepareStatement( "INSERT INTO runs(idobjectives,modelfile,runtype,res_status,res_value,time_in_seconds,idruns) VALUES(?,?,?,?,?,?,?)" ); PrepStmt->setInt(1, idobjectives); PrepStmt->setString(2, modelfile); PrepStmt->setString(3, mip ? "mip" : "lp"); if(!mip) { PrepStmt->setInt(4, glp_get_status(P.GetProblem())); PrepStmt->setDouble(5, glp_get_obj_val(P.GetProblem())); PrepStmt->setNull(7,0); } else { PrepStmt->setInt(4, glp_mip_status(P.GetProblem())); PrepStmt->setDouble(5, glp_mip_obj_val(P.GetProblem())); PrepStmt->setInt(7,idruns); } PrepStmt->setDouble(6, time); PrepStmt->execute(); delete PrepStmt; if(!mip) { PrepStmt = con->prepareStatement( "SELECT LAST_INSERT_ID()" ); res = PrepStmt->executeQuery(); delete PrepStmt; res->next(); idrun = res->getInt(1); delete res; } else { idrun = idruns; } cout << "Run ID " << idrun << endl; PrepStmt = con->prepareStatement( "INSERT INTO results(idrun,var_name,i,j,value,runtype) VALUES(?,?,?,?,?,?)" ); PrepStmt->setInt(1, idrun); PrepStmt->setString(6, mip ? "mip" : "lp"); vector<vector<double>> arr; for (int vvv=1; vvv>=0; vvv--) { char* var_name = (vvv ? "x" : "y"); GetSolArray(P.GetProblem(),var_name,arr,mip); PrepStmt->setString(2, var_name); int i=1; for (std::vector<vector<double>>::iterator it = arr.begin() ; it != arr.end(); ++it) { int j=1; for (std::vector<double>::iterator it2 = (*it).begin() ; it2 != (*it).end(); ++it2) { PrepStmt->setInt(3, i); PrepStmt->setInt(4, j); PrepStmt->setDouble(5, *it2); PrepStmt->execute(); j++; } i++; } } delete PrepStmt; } catch (sql::SQLException &e) { SQLError(e); } return idrun; }
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; }