void lpx_get_col_info(glp_prob *lp, int j, int *tagx, double *vx, double *dx) { /* obtain column solution information */ if (tagx != NULL) *tagx = lpx_get_col_stat(lp, j); if (vx != NULL) *vx = lpx_get_col_prim(lp, j); if (dx != NULL) *dx = lpx_get_col_dual(lp, j); return; }
int main(void) { LPX *lp; int ia[1+1000], ja[1+1000]; double ar[1+1000], Z, x1, x2, x3; s1: lp = lpx_create_prob(); s2: lpx_set_prob_name(lp, "sample"); s3: lpx_set_obj_dir(lp, LPX_MAX); s4: lpx_add_rows(lp, 3); s5: lpx_set_row_name(lp, 1, "p"); s6: lpx_set_row_bnds(lp, 1, LPX_UP, 0.0, 100.0); s7: lpx_set_row_name(lp, 2, "q"); s8: lpx_set_row_bnds(lp, 2, LPX_UP, 0.0, 600.0); s9: lpx_set_row_name(lp, 3, "r"); s10: lpx_set_row_bnds(lp, 3, LPX_UP, 0.0, 300.0); s11: lpx_add_cols(lp, 3); s12: lpx_set_col_name(lp, 1, "x1"); s13: lpx_set_col_bnds(lp, 1, LPX_LO, 0.0, 0.0); s14: lpx_set_obj_coef(lp, 1, 10.0); s15: lpx_set_col_name(lp, 2, "x2"); s16: lpx_set_col_bnds(lp, 2, LPX_LO, 0.0, 0.0); s17: lpx_set_obj_coef(lp, 2, 6.0); s18: lpx_set_col_name(lp, 3, "x3"); s19: lpx_set_col_bnds(lp, 3, LPX_LO, 0.0, 0.0); s20: lpx_set_obj_coef(lp, 3, 4.0); s21: ia[1] = 1, ja[1] = 1, ar[1] = 1.0; /* a[1,1] = 1 */ s22: ia[2] = 1, ja[2] = 2, ar[2] = 1.0; /* a[1,2] = 1 */ s23: ia[3] = 1, ja[3] = 3, ar[3] = 1.0; /* a[1,3] = 1 */ s24: ia[4] = 2, ja[4] = 1, ar[4] = 10.0; /* a[2,1] = 10 */ s25: ia[5] = 3, ja[5] = 1, ar[5] = 2.0; /* a[3,1] = 2 */ s26: ia[6] = 2, ja[6] = 2, ar[6] = 4.0; /* a[2,2] = 4 */ s27: ia[7] = 3, ja[7] = 2, ar[7] = 2.0; /* a[3,2] = 2 */ s28: ia[8] = 2, ja[8] = 3, ar[8] = 5.0; /* a[2,3] = 5 */ s29: ia[9] = 3, ja[9] = 3, ar[9] = 6.0; /* a[3,3] = 6 */ s30: lpx_load_matrix(lp, 9, ia, ja, ar); s31: lpx_simplex(lp); s32: Z = lpx_get_obj_val(lp); s33: x1 = lpx_get_col_prim(lp, 1); s34: x2 = lpx_get_col_prim(lp, 2); s35: x3 = lpx_get_col_prim(lp, 3); s36: printf("\nZ = %g; x1 = %g; x2 = %g; x3 = %g\n", Z, x1, x2, x3); s37: lpx_delete_prob(lp); return 0; }
double lpx_eval_row(LPX *lp, int len, int ind[], double val[]) { int n = lpx_get_num_cols(lp); int j, k; double sum = 0.0; if (len < 0) fault("lpx_eval_row: len = %d; invalid row length", len); for (k = 1; k <= len; k++) { j = ind[k]; if (!(1 <= j && j <= n)) fault("lpx_eval_row: j = %d; column number out of range", j); sum += val[k] * lpx_get_col_prim(lp, j); } return sum; }
static void show_status(LPX *prob, int prob_m, int prob_nz) { int n, j, count; double x, tol_int; /* determine the number of structural variables of integer kind whose current values are still fractional */ n = lpx_get_num_cols(prob); tol_int = lpx_get_real_parm(prob, LPX_K_TOLINT); count = 0; for (j = 1; j <= n; j++) { if (lpx_get_col_kind(prob, j) != LPX_IV) continue; x = lpx_get_col_prim(prob, j); if (fabs(x - floor(x + 0.5)) <= tol_int) continue; count++; } print("&%6d: obj = %17.9e frac = %5d cuts = %5d (%d)", lpx_get_int_parm(prob, LPX_K_ITCNT), lpx_get_obj_val(prob), count, lpx_get_num_rows(prob) - prob_m, lpx_get_num_nz(prob) - prob_nz); return; }
int main(int argc, char *argv[]) { LPX *lp; MPL *mpl = NULL; int ret; double start; /* parse command line parameters */ parse_cmdline(argc, argv); /* remove all output files specified in the command line */ if (display != NULL) remove(display); if (out_sol != NULL) remove(out_sol); if (out_bnds != NULL) remove(out_bnds); if (out_mps != NULL) remove(out_mps); if (out_lpt != NULL) remove(out_lpt); if (out_txt != NULL) remove(out_txt); if (out_glp != NULL) remove(out_glp); /* read problem from the input file */ if (in_file == NULL) { print("No input file specified; try %s --help", argv[0]); exit(EXIT_FAILURE); } switch (format) { case 0: lp = lpx_read_mps(in_file); if (lp == NULL) { print("MPS file processing error"); exit(EXIT_FAILURE); } break; case 1: lp = lpx_read_lpt(in_file); if (lp == NULL) { print("CPLEX LP file processing error"); exit(EXIT_FAILURE); } break; case 2: #if 0 /* 01/VIII-2004 */ lp = lpx_read_model(in_file, in_data, display); if (lp == NULL) { print("Model processing error"); exit(EXIT_FAILURE); } #else /* initialize the translator database */ mpl = mpl_initialize(); /* read model section and optional data section */ ret = mpl_read_model(mpl, in_file, in_data != NULL); if (ret == 4) err: { print("Model processing error"); exit(EXIT_FAILURE); } insist(ret == 1 || ret == 2); /* read data section, if necessary */ if (in_data != NULL) { insist(ret == 1); ret = mpl_read_data(mpl, in_data); if (ret == 4) goto err; insist(ret == 2); } /* generate model */ ret = mpl_generate(mpl, display); if (ret == 4) goto err; /* extract problem instance */ lp = lpx_extract_prob(mpl); insist(lp != NULL); #endif if (lpx_get_num_rows(lp) == 0) { print("Problem has no rows"); exit(EXIT_FAILURE); } if (lpx_get_num_cols(lp) == 0) { print("Problem has no columns"); exit(EXIT_FAILURE); } break; case 3: lp = lpx_read_prob(in_file); if (lp == NULL) { print("GNU LP file processing error"); exit(EXIT_FAILURE); } break; default: insist(format != format); } /* change problem name (if required) */ if (newname != NULL) lpx_set_prob_name(lp, newname); /* change optimization direction (if required) */ if (dir != 0) lpx_set_obj_dir(lp, dir); /* write problem in MPS format (if required) */ if (out_mps != NULL) { lpx_set_int_parm(lp, LPX_K_MPSORIG, orig); ret = lpx_write_mps(lp, out_mps); if (ret != 0) { print("Unable to write problem in MPS format"); exit(EXIT_FAILURE); } } /* write problem in CPLEX LP format (if required) */ if (out_lpt != NULL) { lpx_set_int_parm(lp, LPX_K_LPTORIG, orig); ret = lpx_write_lpt(lp, out_lpt); if (ret != 0) { print("Unable to write problem in CPLEX LP format"); exit(EXIT_FAILURE); } } /* write problem in plain text format (if required) */ if (out_txt != NULL) { lpx_set_int_parm(lp, LPX_K_LPTORIG, orig); ret = lpx_print_prob(lp, out_txt); if (ret != 0) { print("Unable to write problem in plain text format"); exit(EXIT_FAILURE); } } /* write problem in GNU LP format (if required) */ if (out_glp != NULL) { ret = lpx_write_prob(lp, out_glp); if (ret != 0) { print("Unable to write problem in GNU LP format"); exit(EXIT_FAILURE); } } /* if only data check is required, skip computations */ if (check) goto skip; /* scale the problem data (if required) */ if (scale && (!presol || method == 1)) lpx_scale_prob(lp); /* build advanced initial basis (if required) */ if (method == 0 && basis && !presol) lpx_adv_basis(lp); /* set some control parameters, which might be changed in the command line */ lpx_set_int_parm(lp, LPX_K_PRICE, price); if (!relax) lpx_set_real_parm(lp, LPX_K_RELAX, 0.0); lpx_set_int_parm(lp, LPX_K_PRESOL, presol); lpx_set_int_parm(lp, LPX_K_BRANCH, branch); lpx_set_int_parm(lp, LPX_K_BTRACK, btrack); lpx_set_real_parm(lp, LPX_K_TMLIM, (double)tmlim); /* solve the problem */ start = utime(); switch (method) { case 0: if (nomip || lpx_get_class(lp) == LPX_LP) { ret = lpx_simplex(lp); if (presol && ret != LPX_E_OK && out_sol != NULL) print("If you need actual output for non-optimal solu" "tion, use --nopresol"); } else { method = 2; lpx_simplex(lp); if (!intopt) lpx_integer(lp); else lpx_intopt(lp); } break; case 1: if (nomip || lpx_get_class(lp) == LPX_LP) lpx_interior(lp); else { print("Interior point method is not able to solve MIP pr" "oblem; use --simplex"); exit(EXIT_FAILURE); } break; default: insist(method != method); } /* display statistics */ print("Time used: %.1f secs", utime() - start); print("Memory used: %.1fM (%d bytes)", (double)lib_env_ptr()->mem_tpeak / (double)(1024 * 1024), lib_env_ptr()->mem_tpeak); #if 1 /* 01/VIII-2004 */ if (mpl != NULL && mpl_has_solve_stmt(mpl)) { int n, j, round; /* store the solution to the translator database */ n = lpx_get_num_cols(lp); round = lpx_get_int_parm(lp, LPX_K_ROUND); lpx_set_int_parm(lp, LPX_K_ROUND, 1); switch (method) { case 0: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_get_col_prim(lp, j)); break; case 1: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_ipt_col_prim(lp, j)); break; case 2: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_mip_col_val(lp, j)); break; default: insist(method != method); } lpx_set_int_parm(lp, LPX_K_ROUND, round); /* perform postsolving */ ret = mpl_postsolve(mpl, display); if (ret == 4) { print("Model postsolving error"); exit(EXIT_FAILURE); } insist(ret == 3); } #endif /* write problem solution found by the solver (if required) */ if (out_sol != NULL) { switch (method) { case 0: ret = lpx_print_sol(lp, out_sol); break; case 1: ret = lpx_print_ips(lp, out_sol); break; case 2: ret = lpx_print_mip(lp, out_sol); break; default: insist(method != method); } if (ret != 0) { print("Unable to write problem solution"); exit(EXIT_FAILURE); } } /* write sensitivity bounds information (if required) */ if (out_bnds != NULL) { if (method != 0) { print("Cannot write sensitivity bounds information for inte" "rior-point or MIP solution"); exit(EXIT_FAILURE); } ret = lpx_print_sens_bnds(lp, out_bnds); if (ret != 0) { print("Unable to write sensitivity bounds information"); exit(EXIT_FAILURE); } } skip: /* delete the problem object */ lpx_delete_prob(lp); #if 1 /* 01/VIII-2004 */ /* if the translator database exists, destroy it */ if (mpl != NULL) mpl_terminate(mpl); #endif /* check that no memory blocks are still allocated */ insist(lib_env_ptr()->mem_total == 0); insist(lib_env_ptr()->mem_count == 0); /* return to the control program */ return 0; }
int main(int argc, char *argv[]) { LPX *lp; MPL *mpl = NULL; int ret; ulong_t start; /* parse command line parameters */ parse_cmdline(argc, argv); /* set available memory limit */ if (memlim >= 0) lib_mem_limit(ulmul(ulset(0, 1048576), ulset(0, memlim))); /* remove all output files specified in the command line */ if (display != NULL) remove(display); if (out_bas != NULL) remove(out_bas); if (out_sol != NULL) remove(out_sol); if (out_bnds != NULL) remove(out_bnds); if (out_mps != NULL) remove(out_mps); if (out_freemps != NULL) remove(out_freemps); if (out_cpxlp != NULL) remove(out_cpxlp); if (out_txt != NULL) remove(out_txt); if (out_glp != NULL) remove(out_glp); if (log_file != NULL) remove(log_file); /* open hardcopy file, if necessary */ if (log_file != NULL) { if (lib_open_log(log_file)) { print("Unable to create log file"); exit(EXIT_FAILURE); } } /* read problem data from the input file */ if (in_file == NULL) { print("No input file specified; try %s --help", argv[0]); exit(EXIT_FAILURE); } switch (format) { case 0: lp = lpx_read_mps(in_file); if (lp == NULL) { print("MPS file processing error"); exit(EXIT_FAILURE); } orig = 1; break; case 1: lp = lpx_read_cpxlp(in_file); if (lp == NULL) { print("CPLEX LP file processing error"); exit(EXIT_FAILURE); } break; case 2: /* initialize the translator database */ mpl = mpl_initialize(); /* read model section and optional data section */ ret = mpl_read_model(mpl, in_file, in_data != NULL); if (ret == 4) err: { print("Model processing error"); exit(EXIT_FAILURE); } xassert(ret == 1 || ret == 2); /* read data section, if necessary */ if (in_data != NULL) { xassert(ret == 1); ret = mpl_read_data(mpl, in_data); if (ret == 4) goto err; xassert(ret == 2); } /* generate model */ ret = mpl_generate(mpl, display); if (ret == 4) goto err; /* extract problem instance */ lp = lpx_extract_prob(mpl); xassert(lp != NULL); break; case 3: lp = lpx_read_prob(in_file); if (lp == NULL) { print("GNU LP file processing error"); exit(EXIT_FAILURE); } break; case 4: lp = lpx_read_freemps(in_file); if (lp == NULL) { print("MPS file processing error"); exit(EXIT_FAILURE); } break; default: xassert(format != format); } /* order rows and columns of the constraint matrix */ lpx_order_matrix(lp); /* change problem name (if required) */ if (newname != NULL) lpx_set_prob_name(lp, newname); /* change optimization direction (if required) */ if (dir != 0) lpx_set_obj_dir(lp, dir); /* write problem in fixed MPS format (if required) */ if (out_mps != NULL) { lpx_set_int_parm(lp, LPX_K_MPSORIG, orig); ret = lpx_write_mps(lp, out_mps); if (ret != 0) { print("Unable to write problem in fixed MPS format"); exit(EXIT_FAILURE); } } /* write problem in free MPS format (if required) */ if (out_freemps != NULL) { ret = lpx_write_freemps(lp, out_freemps); if (ret != 0) { print("Unable to write problem in free MPS format"); exit(EXIT_FAILURE); } } /* write problem in CPLEX LP format (if required) */ if (out_cpxlp != NULL) { ret = lpx_write_cpxlp(lp, out_cpxlp); if (ret != 0) { print("Unable to write problem in CPLEX LP format"); exit(EXIT_FAILURE); } } /* write problem in plain text format (if required) */ if (out_txt != NULL) { lpx_set_int_parm(lp, LPX_K_LPTORIG, orig); ret = lpx_print_prob(lp, out_txt); if (ret != 0) { print("Unable to write problem in plain text format"); exit(EXIT_FAILURE); } } /* write problem in GNU LP format (if required) */ if (out_glp != NULL) { ret = lpx_write_prob(lp, out_glp); if (ret != 0) { print("Unable to write problem in GNU LP format"); exit(EXIT_FAILURE); } } /* if only data check is required, skip computations */ if (check) goto skip; /* scale the problem data (if required) */ if (scale && (!presol || method == 1)) lpx_scale_prob(lp); /* build initial LP basis */ if (method == 0 && !presol && in_bas == NULL) { switch (basis) { case 0: lpx_std_basis(lp); break; case 1: if (lpx_get_num_rows(lp) > 0 && lpx_get_num_cols(lp) > 0) lpx_adv_basis(lp); break; case 2: if (lpx_get_num_rows(lp) > 0 && lpx_get_num_cols(lp) > 0) lpx_cpx_basis(lp); break; default: xassert(basis != basis); } } /* or read initial basis from input text file in MPS format */ if (in_bas != NULL) { if (method != 0) { print("Initial LP basis is useless for interior-point solve" "r and therefore ignored"); goto nobs; } lpx_set_int_parm(lp, LPX_K_MPSORIG, orig); ret = lpx_read_bas(lp, in_bas); if (ret != 0) { print("Unable to read initial LP basis"); exit(EXIT_FAILURE); } if (presol) { presol = 0; print("LP presolver disabled because initial LP basis has b" "een provided"); } nobs: ; } /* set some control parameters, which might be changed in the command line */ lpx_set_int_parm(lp, LPX_K_BFTYPE, bf_type); lpx_set_int_parm(lp, LPX_K_PRICE, price); if (!relax) lpx_set_real_parm(lp, LPX_K_RELAX, 0.0); lpx_set_int_parm(lp, LPX_K_PRESOL, presol); lpx_set_int_parm(lp, LPX_K_BRANCH, branch); lpx_set_int_parm(lp, LPX_K_BTRACK, btrack); lpx_set_real_parm(lp, LPX_K_TMLIM, (double)tmlim); lpx_set_int_parm(lp, LPX_K_BINARIZE, binarize); lpx_set_int_parm(lp, LPX_K_USECUTS, use_cuts); /* solve the problem */ start = xtime(); switch (method) { case 0: if (nomip || lpx_get_class(lp) == LPX_LP) { ret = (!exact ? lpx_simplex(lp) : lpx_exact(lp)); if (xcheck) { if (!presol || ret == LPX_E_OK) lpx_exact(lp); else print("If you need checking final basis for non-op" "timal solution, use --nopresol"); } if (presol && ret != LPX_E_OK && (out_bas != NULL || out_sol != NULL)) print("If you need actual output for non-optimal solu" "tion, use --nopresol"); } else { method = 2; if (!intopt) { ret = (!exact ? lpx_simplex(lp) : lpx_exact(lp)); if (xcheck && (!presol || ret == LPX_E_OK)) lpx_exact(lp); lpx_integer(lp); } else lpx_intopt(lp); } break; case 1: if (nomip || lpx_get_class(lp) == LPX_LP) lpx_interior(lp); else { print("Interior-point method is not able to solve MIP pr" "oblem; use --simplex"); exit(EXIT_FAILURE); } break; default: xassert(method != method); } /* display statistics */ print("Time used: %.1f secs", xdifftime(xtime(), start)); { ulong_t tpeak; char buf[50]; lib_mem_usage(NULL, NULL, NULL, &tpeak); print("Memory used: %.1f Mb (%s bytes)", (4294967296.0 * tpeak.hi + tpeak.lo) / 1048576.0, ultoa(tpeak, buf, 10)); } if (mpl != NULL && mpl_has_solve_stmt(mpl)) { int n, j, round; /* store the solution to the translator database */ n = lpx_get_num_cols(lp); round = lpx_get_int_parm(lp, LPX_K_ROUND); lpx_set_int_parm(lp, LPX_K_ROUND, 1); switch (method) { case 0: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_get_col_prim(lp, j)); break; case 1: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_ipt_col_prim(lp, j)); break; case 2: for (j = 1; j <= n; j++) mpl_put_col_value(mpl, j, lpx_mip_col_val(lp, j)); break; default: xassert(method != method); } lpx_set_int_parm(lp, LPX_K_ROUND, round); /* perform postsolving */ ret = mpl_postsolve(mpl); if (ret == 4) { print("Model postsolving error"); exit(EXIT_FAILURE); } xassert(ret == 3); } /* write final LP basis (if required) */ if (out_bas != NULL) { lpx_set_int_parm(lp, LPX_K_MPSORIG, orig); ret = lpx_write_bas(lp, out_bas); if (ret != 0) { print("Unable to write final LP basis"); exit(EXIT_FAILURE); } } /* write problem solution found by the solver (if required) */ if (out_sol != NULL) { switch (method) { case 0: ret = lpx_print_sol(lp, out_sol); break; case 1: ret = lpx_print_ips(lp, out_sol); break; case 2: ret = lpx_print_mip(lp, out_sol); break; default: xassert(method != method); } if (ret != 0) { print("Unable to write problem solution"); exit(EXIT_FAILURE); } } /* write sensitivity bounds information (if required) */ if (out_bnds != NULL) { if (method != 0) { print("Cannot write sensitivity bounds information for inte" "rior-point or MIP solution"); exit(EXIT_FAILURE); } ret = lpx_print_sens_bnds(lp, out_bnds); if (ret != 0) { print("Unable to write sensitivity bounds information"); exit(EXIT_FAILURE); } } skip: /* delete the problem object */ lpx_delete_prob(lp); /* if the translator database exists, destroy it */ if (mpl != NULL) mpl_terminate(mpl); xassert(gmp_pool_count() == 0); gmp_free_mem(); /* close the hardcopy file */ if (log_file != NULL) lib_close_log(); /* check that no memory blocks are still allocated */ { int count; ulong_t total; lib_mem_usage(&count, NULL, &total, NULL); xassert(count == 0); xassert(total.lo == 0 && total.hi == 0); } /* free the library environment */ lib_free_env(); /* return to the control program */ return 0; }
int lpx_clique_cut(LPX *lp, void *_cog, int ind[], double val[]) { struct COG *cog = _cog; int n = lpx_get_num_cols(lp); int j, t, v, card, temp, len = 0, *w, *sol; double x, sum, b, *vec; /* allocate working arrays */ w = xcalloc(1 + 2 * cog->nb, sizeof(int)); sol = xcalloc(1 + 2 * cog->nb, sizeof(int)); vec = xcalloc(1+n, sizeof(double)); /* assign weights to vertices of the conflict graph */ for (t = 1; t <= cog->nb; t++) { j = cog->orig[t]; x = lpx_get_col_prim(lp, j); temp = (int)(100.0 * x + 0.5); if (temp < 0) temp = 0; if (temp > 100) temp = 100; w[t] = temp; w[cog->nb + t] = 100 - temp; } /* find a clique of maximum weight */ card = wclique(2 * cog->nb, w, cog->a, sol); /* compute the clique weight for unscaled values */ sum = 0.0; for ( t = 1; t <= card; t++) { v = sol[t]; xassert(1 <= v && v <= 2 * cog->nb); if (v <= cog->nb) { /* vertex v corresponds to binary variable x[j] */ j = cog->orig[v]; x = lpx_get_col_prim(lp, j); sum += x; } else { /* vertex v corresponds to the complement of x[j] */ j = cog->orig[v - cog->nb]; x = lpx_get_col_prim(lp, j); sum += 1.0 - x; } } /* if the sum of binary variables and their complements in the clique greater than 1, the clique cut is violated */ if (sum >= 1.01) { /* construct the inquality */ for (j = 1; j <= n; j++) vec[j] = 0; b = 1.0; for (t = 1; t <= card; t++) { v = sol[t]; if (v <= cog->nb) { /* vertex v corresponds to binary variable x[j] */ j = cog->orig[v]; xassert(1 <= j && j <= n); vec[j] += 1.0; } else { /* vertex v corresponds to the complement of x[j] */ j = cog->orig[v - cog->nb]; xassert(1 <= j && j <= n); vec[j] -= 1.0; b -= 1.0; } } xassert(len == 0); for (j = 1; j <= n; j++) { if (vec[j] != 0.0) { len++; ind[len] = j, val[len] = vec[j]; } } ind[0] = 0, val[0] = b; } /* free working arrays */ xfree(w); xfree(sol); xfree(vec); /* return to the calling program */ return len; }
int TankBlendOptimiser::go() { lp = lpx_create_prob(); lpx_set_int_parm(lp, LPX_K_MSGLEV, 0); // 0 = no output lpx_set_int_parm(lp, LPX_K_SCALE, 3); // 3 = geometric mean scaling, then equilibration scaling lpx_set_int_parm(lp, LPX_K_DUAL, 1); // 1 = if initial basic solution is dual feasible, use the dual simplex lpx_set_int_parm(lp, LPX_K_ROUND, 1); // 1 = replace tiny primal and dual values by exact zero lpx_set_int_parm(lp, LPX_K_PRESOL, 1); // 1 = use the built-in presolver. lpx_set_prob_name(lp, "Blend Optimiser"); lpx_set_obj_dir(lp, LPX_MIN); // Columns... lpx_add_cols(lp, cols); for (int i=0; i<tanks; i++) // 0.0 < x < tankMax { if (tankMax[i]>0.0) lpx_set_col_bnds(lp, col, LPX_DB, 0.0, tankMax[i]); else lpx_set_col_bnds(lp, col, LPX_FX, 0.0, 0.0); col++; } for (int i=0; i<tanks; i++) // 0.0 < slackTankLow { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, tankLowPenalty[i]); // penalty weight. col++; } for (int i=0; i<tanks; i++) // 0.0 < slackTankHigh { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, tankHighPenalty[i]); // penalty weight. col++; } for (int i=0; i<assays; i++) // 0.0 < slackAssayLow { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, assayLowPenalty[i]); // penalty weight. col++; } for (int i=0; i<assays; i++) // 0.0 < slackAssayHigh { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, assayHighPenalty[i]); // penalty weight. col++; } for (int i=0; i<assays; i++) // 0.0 < slackAssayRatioLow for (int j=0; j<assays; j++) { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, assayRatioLowPenalty[i][j]); // penalty weight. col++; } for (int i=0; i<assays; i++) // 0.0 < slackAssayRatioHigh for (int j=0; j<assays; j++) { lpx_set_col_bnds(lp, col, LPX_LO, 0.0, 0.0); lpx_set_obj_coef(lp, col, assayRatioHighPenalty[i][j]); // penalty weight. col++; } // Rows... lpx_add_rows(lp, rows); { // x1 + ... + xn = 1.0 lpx_set_row_bnds(lp, row, LPX_FX, 1.0, 1.0); for (int i=0; i<tanks; i++) ia[constraint] = row, ja[constraint] = 1+i, ar[constraint++] = 1.0; row++; } for (int i=0; i<tanks; i++) // tankLow < tank + slackTankLow { lpx_set_row_bnds(lp, row, LPX_LO, tankLow[i], 0.0); ia[constraint] = row, ja[constraint] = 1+i, ar[constraint++] = 1.0; ia[constraint] = row, ja[constraint] = 1+i+tanks, ar[constraint++] = 1.0; row++; } for (int i=0; i<tanks; i++) // tank - slackTankHigh < tankHigh { lpx_set_row_bnds(lp, row, LPX_UP, 0.0, tankHigh[i]); ia[constraint] = row, ja[constraint] = 1+i, ar[constraint++] = 1.0; ia[constraint] = row, ja[constraint] = 1+i+2*tanks, ar[constraint++] = -1.0; row++; } for (int i=0; i<assays; i++) // assayLow < assay + slackAssayLow { lpx_set_row_bnds(lp, row, LPX_LO, assayLow[i], 0.0); for (int j=0; j<tanks; j++) { if (assayConc[i][j]>0.0) ia[constraint] = row, ja[constraint] = 1+j, ar[constraint++] = assayConc[i][j]; } ia[constraint] = row, ja[constraint] = 1+i+3*tanks, ar[constraint++] = 1.0; row++; } for (int i=0; i<assays; i++) // assay - slackAssayHigh < assayHigh { lpx_set_row_bnds(lp, row, LPX_UP, 0.0, assayHigh[i]); for (int j=0; j<tanks; j++) { if (assayConc[i][j]>0.0) ia[constraint] = row, ja[constraint] = 1+j, ar[constraint++] = assayConc[i][j]; } ia[constraint] = row, ja[constraint] = 1+i+3*tanks+assays, ar[constraint++] = -1.0; row++; } for (int i=0; i<assays; i++) // 0 < assayNum - assayRatioLow*assayDen + slackAssayLow for (int j=0; j<assays; j++) { if (assayRatioLowEnabled[i][j]) lpx_set_row_bnds(lp, row, LPX_LO, 0.0, 0.0); else lpx_set_row_bnds(lp, row, LPX_FR, 0.0, 0.0); for (int k=0; k<tanks; k++) { if (assayConc[i][k] - assayRatioLow[i][j]*assayConc[j][k]!=0.0) ia[constraint] = row, ja[constraint] = 1+k, ar[constraint++] = assayConc[i][k] - assayRatioLow[i][j]*assayConc[j][k]; } ia[constraint] = row, ja[constraint] = 1+i*assays+j+3*tanks+2*assays, ar[constraint++] = 1.0; row++; } for (int i=0; i<assays; i++) // assayNum - assayRatioHigh*assayDen - slackAssayHigh < 0 for (int j=0; j<assays; j++) { if (assayRatioHighEnabled[i][j]) lpx_set_row_bnds(lp, row, LPX_UP, 0.0, 0.0); else lpx_set_row_bnds(lp, row, LPX_FR, 0.0, 0.0); for (int k=0; k<tanks; k++) { if (assayConc[i][k] - assayRatioHigh[i][j]*assayConc[j][k]!=0.0) ia[constraint] = row, ja[constraint] = 1+k, ar[constraint++] = assayConc[i][k] - assayRatioHigh[i][j]*assayConc[j][k]; } ia[constraint] = row, ja[constraint] = 1+i*assays+j+3*tanks+2*assays+assays*assays, ar[constraint++] = -1.0; row++; } lpx_load_matrix(lp, constraint-1, ia, ja, ar); int exitCode = lpx_simplex(lp); for (int i=0; i<tanks; i++) tank[i] = lpx_get_col_prim(lp, 1+i); for (int i=0; i<assays; i++) { assay[i] = 0.0; for (int j=0; j<tanks; j++) assay[i] += lpx_get_col_prim(lp, 1+j)*assayConc[i][j]; } return exitCode; // LPX_E_OK 200 /* success */ // LPX_E_FAULT 204 /* unable to start the search */ // LPX_E_ITLIM 207 /* iterations limit exhausted */ // LPX_E_TMLIM 208 /* time limit exhausted */ // LPX_E_SING 211 /* problems with basis matrix */ // LPX_E_NOPFS 213 /* no primal feas. sol. (LP presolver) */ // LPX_E_NODFS 214 /* no dual feas. sol. (LP presolver) */ // Usually: // LPX_E_OK = Solution found. // LPX_E_NOPFS = Sum-to-1.0 or tank-max constraints not met. // Others = Some major fault has occurred. }
OptSolutionData* GLPKRunSolver(int ProbType) { OptSolutionData* NewSolution = NULL; int NumVariables = lpx_get_num_cols(GLPKModel); int Status = 0; if (ProbType == MILP) { Status = lpx_simplex(GLPKModel); if (Status != LPX_E_OK) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } Status = lpx_integer(GLPKModel); if (Status != LPX_E_OK) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } NewSolution = new OptSolutionData; Status = lpx_mip_status(GLPKModel); if (Status == LPX_I_UNDEF || Status == LPX_I_NOFEAS) { NewSolution->Status = INFEASIBLE; return NewSolution; } else if (Status == LPX_I_FEAS) { NewSolution->Status = UNBOUNDED; return NewSolution; } else if (Status == LPX_I_OPT) { NewSolution->Status = SUCCESS; } else { delete NewSolution; FErrorFile() << "Problem status unrecognized." << endl; FlushErrorFile(); return NULL; } NewSolution->Objective = lpx_mip_obj_val(GLPKModel); NewSolution->SolutionData.resize(NumVariables); for (int i=0; i < NumVariables; i++) { NewSolution->SolutionData[i] = lpx_mip_col_val(GLPKModel, i+1); } } else if (ProbType == LP) { //First we check the basis matrix to ensure it is not sigular if (lpx_warm_up(GLPKModel) != LPX_E_OK) { lpx_adv_basis(GLPKModel); } Status = lpx_simplex(GLPKModel); if (Status == LPX_E_FAULT) { Status = lpx_warm_up(GLPKModel); if (Status == LPX_E_BADB) { /* the basis is invalid; build some valid basis */ lpx_adv_basis(GLPKModel); Status = lpx_simplex(GLPKModel); } } if (Status != LPX_E_OK) { FErrorFile() << "Failed to optimize problem." << endl; FlushErrorFile(); return NULL; } NewSolution = new OptSolutionData; Status = lpx_get_status(GLPKModel); if (Status == LPX_INFEAS || Status == LPX_NOFEAS || Status == LPX_UNDEF) { cout << "Model is infeasible" << endl; FErrorFile() << "Model is infeasible" << endl; FlushErrorFile(); NewSolution->Status = INFEASIBLE; return NewSolution; } else if (Status == LPX_FEAS || Status == LPX_UNBND) { cout << "Model is unbounded" << endl; FErrorFile() << "Model is unbounded" << endl; FlushErrorFile(); NewSolution->Status = UNBOUNDED; return NewSolution; } else if (Status == LPX_OPT) { NewSolution->Status = SUCCESS; } else { delete NewSolution; FErrorFile() << "Problem status unrecognized." << endl; FlushErrorFile(); return NULL; } NewSolution->Objective = lpx_get_obj_val(GLPKModel); NewSolution->SolutionData.resize(NumVariables); for (int i=0; i < NumVariables; i++) { NewSolution->SolutionData[i] = lpx_get_col_prim(GLPKModel, i+1); } } else { FErrorFile() << "Optimization problem type cannot be handled by GLPK solver." << endl; FlushErrorFile(); return NULL; } return NewSolution; }
int lpx_prim_ratio_test(LPX *lp, int len, const int ind[], const double val[], int how, double tol) { int i, k, m, n, p, t, typx, tagx; double alfa_i, abs_alfa_i, big, eps, bbar_i, lb_i, ub_i, temp, teta; if (!lpx_is_b_avail(lp)) xfault("lpx_prim_ratio_test: LP basis is not available\n"); if (lpx_get_prim_stat(lp) != LPX_P_FEAS) xfault("lpx_prim_ratio_test: current basic solution is not pri" "mal feasible\n"); if (!(how == +1 || how == -1)) xfault("lpx_prim_ratio_test: how = %d; invalid parameter\n", how); m = lpx_get_num_rows(lp); n = lpx_get_num_cols(lp); /* compute the largest absolute value of the specified influence coefficients */ big = 0.0; for (t = 1; t <= len; t++) { temp = val[t]; if (temp < 0.0) temp = - temp; if (big < temp) big = temp; } /* compute the absolute tolerance eps used to skip small entries of the column */ if (!(0.0 < tol && tol < 1.0)) xfault("lpx_prim_ratio_test: tol = %g; invalid tolerance\n", tol); eps = tol * (1.0 + big); /* initial settings */ p = 0, teta = DBL_MAX, big = 0.0; /* walk through the entries of the specified column */ for (t = 1; t <= len; t++) { /* get the ordinal number of basic variable */ k = ind[t]; if (!(1 <= k && k <= m+n)) xfault("lpx_prim_ratio_test: ind[%d] = %d; variable number " "out of range\n", t, k); if (k <= m) tagx = lpx_get_row_stat(lp, k); else tagx = lpx_get_col_stat(lp, k-m); if (tagx != LPX_BS) xfault("lpx_prim_ratio_test: ind[%d] = %d; non-basic variab" "le not allowed\n", t, k); /* determine index of the variable x[k] in the vector xB */ if (k <= m) i = lpx_get_row_b_ind(lp, k); else i = lpx_get_col_b_ind(lp, k-m); xassert(1 <= i && i <= m); /* determine unscaled bounds and value of the basic variable xB[i] in the current basic solution */ if (k <= m) { typx = lpx_get_row_type(lp, k); lb_i = lpx_get_row_lb(lp, k); ub_i = lpx_get_row_ub(lp, k); bbar_i = lpx_get_row_prim(lp, k); } else { typx = lpx_get_col_type(lp, k-m); lb_i = lpx_get_col_lb(lp, k-m); ub_i = lpx_get_col_ub(lp, k-m); bbar_i = lpx_get_col_prim(lp, k-m); } /* determine influence coefficient for the basic variable x[k] = xB[i] in the explicitly specified column and turn to the case of increasing the variable y in order to simplify the program logic */ alfa_i = (how > 0 ? +val[t] : -val[t]); abs_alfa_i = (alfa_i > 0.0 ? +alfa_i : -alfa_i); /* analyze main cases */ switch (typx) { case LPX_FR: /* xB[i] is free variable */ continue; case LPX_LO: lo: /* xB[i] has an lower bound */ if (alfa_i > - eps) continue; temp = (lb_i - bbar_i) / alfa_i; break; case LPX_UP: up: /* xB[i] has an upper bound */ if (alfa_i < + eps) continue; temp = (ub_i - bbar_i) / alfa_i; break; case LPX_DB: /* xB[i] has both lower and upper bounds */ if (alfa_i < 0.0) goto lo; else goto up; case LPX_FX: /* xB[i] is fixed variable */ if (abs_alfa_i < eps) continue; temp = 0.0; break; default: xassert(typx != typx); } /* if the value of the variable xB[i] violates its lower or upper bound (slightly, because the current basis is assumed to be primal feasible), temp is negative; we can think this happens due to round-off errors and the value is exactly on the bound; this allows replacing temp by zero */ if (temp < 0.0) temp = 0.0; /* apply the minimal ratio test */ if (teta > temp || teta == temp && big < abs_alfa_i) p = k, teta = temp, big = abs_alfa_i; } /* return the ordinal number of the chosen basic variable */ return p; }
void Gspan::lpboost(){ std::cout << "in lpboost" << std::endl; const char *out = "model"; //initialize unsigned int gnum = gdata.size(); weight.resize(gnum); std::fill(weight.begin(),weight.end(),1.0); corlab.resize(gnum); for(unsigned int gid=0;gid<gnum;++gid){ corlab[gid]=gdata[gid].class_label; } wbias=0.0; Hypothesis model; first_flag=true; need_to_cooc = false; cooc_is_opt = false; std::cout.setf(std::ios::fixed,std::ios::floatfield); std::cout.precision(8); //Initialize GLPK int* index = new int[gnum+2]; double* value = new double[gnum+2]; LPX* lp = lpx_create_prob(); lpx_add_cols(lp, gnum+1); // set u_1,...u_l, beta for (unsigned int i = 0; i < gnum; ++i){ lpx_set_col_bnds(lp, COL(i), LPX_DB, 0.0, 1/(nu*gnum)); lpx_set_obj_coef(lp, COL(i), 0); // u } lpx_set_col_bnds(lp, COL(gnum), LPX_FR, 0.0, 0.0); lpx_set_obj_coef(lp, COL(gnum), 1); // beta lpx_set_obj_dir(lp, LPX_MIN); //optimization direction: min objective lpx_add_rows(lp,1); // Add one row constraint s.t. sum_u == 1 for (unsigned int i = 0; i < gnum; ++i){ index[i+1] = COL(i); value[i+1] = 1; } lpx_set_mat_row(lp, ROW(0), gnum, index, value); lpx_set_row_bnds(lp, ROW(0), LPX_FX, 1, 1); double beta = 0.0; double margin = 0.0; //main loop for(unsigned int itr=0;itr < max_itr;++itr){ std::cout <<"itrator : "<<itr+1<<std::endl; if(itr==coocitr) need_to_cooc=true; opt_pat.gain=0.0;//gain init opt_pat.size=0; opt_pat.locsup.resize(0); pattern.resize(0); opt_pat.dfscode=""; Crun(); //std::cout<<opt_pat.gain<<" :"<<opt_pat.dfscode<<std::endl; std::vector <int> result (gnum); int _y; vector<int> locvec; std::string dfscode; if(cooc_is_opt == false){ _y = opt_pat.gain > 0 ? +1 :-1; locvec =opt_pat.locsup; dfscode=opt_pat.dfscode; }else{ _y = opt_pat_cooc.gain > 0 ? +1 :-1; locvec =opt_pat_cooc.locsup; dfscode=opt_pat_cooc.dfscode[0]+"\t"+opt_pat_cooc.dfscode[1];//=opt_pat_cooc.dfscode; } model.flag.resize(itr+1); model.flag[itr]=_y; std::fill (result.begin (), result.end(), -_y); for (unsigned int i = 0; i < locvec.size(); ++i) result[locvec[i]] = _y; double uyh = 0; for (unsigned int i = 0; i < gnum; ++i) { // summarizing hypotheses uyh += weight[i]*corlab[i]*result[i]; } std::cout << "Stopping criterion: " << uyh << "<=?" << beta << " + " << conv_epsilon << std::endl; if( (uyh <= beta + conv_epsilon ) ){ std::cout << "*********************************" << std::endl; std::cout << "Convergence ! at iteration: " << itr+1 << std::endl; std::cout << "*********************************" << std::endl; if(!end_of_cooc || need_to_cooc == true) break; need_to_cooc = true; } lpx_add_rows(lp,1); // Add one row constraint s.t. sum( uyh - beta ) <= 0 for (unsigned int i = 0; i < gnum; ++i){ index[i+1] = COL(i); value[i+1] = result[i] * corlab[i]; } index[gnum+1] = COL(gnum); value[gnum+1] = -1; lpx_set_mat_row(lp, ROW(itr+1), gnum+1, index, value); lpx_set_row_bnds(lp, ROW(itr+1), LPX_UP, 0.0, 0.0); model.weight.push_back(0); model.dfs_vector.push_back(dfscode); lpx_simplex(lp); beta = lpx_get_obj_val(lp); for (unsigned int i = 0; i < gnum; ++i){ double new_weight; new_weight = lpx_get_col_prim(lp, COL(i)); if(new_weight < 0) new_weight = 0; // weight > 0 weight[i] = new_weight; } margin = lpx_get_row_dual(lp, ROW(0)); double margin_error = 0.0; for (unsigned int i = 0; i < gnum; ++i) { // summarizing hypotheses if (corlab[i]*result[i] < margin){ ++margin_error; } } margin_error /= gnum; //next rule is estimated wbias = 0.0; for (unsigned int i = 0; i < gnum; ++i){ wbias += corlab[i] * weight[i]; } std::ofstream os (out); if (! os) { std::cerr << "FATAL: Cannot open output file: " << out << std::endl; return; } os.setf(std::ios::fixed,std::ios::floatfield); os.precision(12); for (unsigned int r = 0; r < itr; ++r){ model.weight[r] = - lpx_get_row_dual(lp, ROW(r+1)); if(model.weight[r] < 0) model.weight[r] = 0; // alpha > 0 os << model.flag[r] * model.weight[r] << "\t" << model.dfs_vector[r] << std::endl; std::cout << model.flag[r] * model.weight[r] << "\t" << model.dfs_vector[r] << std::endl; } std::cout << "After iteration " << itr+1 << std::endl; std::cout << "Margin: " << margin << std::endl; std::cout << "Margin Error: " << margin_error << std::endl; } std::cout << "end lpboost" << std::endl; }
static void gen_gomory_cut(LPX *prob, int maxlen) { int m = lpx_get_num_rows(prob); int n = lpx_get_num_cols(prob); int i, j, k, len, cut_j, *ind; double x, d, r, temp, cut_d, cut_r, *val, *work; insist(lpx_get_status(prob) == LPX_OPT); /* allocate working arrays */ ind = ucalloc(1+n, sizeof(int)); val = ucalloc(1+n, sizeof(double)); work = ucalloc(1+m+n, sizeof(double)); /* nothing is chosen so far */ cut_j = 0; cut_d = 0.0; cut_r = 0.0; /* look through all structural variables */ for (j = 1; j <= n; j++) { /* if the variable is continuous, skip it */ if (lpx_get_col_kind(prob, j) != LPX_IV) continue; /* if the variable is non-basic, skip it */ if (lpx_get_col_stat(prob, j) != LPX_BS) continue; /* if the variable is fixed, skip it */ if (lpx_get_col_type(prob, j) == LPX_FX) continue; /* obtain current primal value of the variable */ x = lpx_get_col_prim(prob, j); /* if the value is close enough to nearest integer, skip the variable */ if (fabs(x - floor(x + 0.5)) < 1e-4) continue; /* compute the row of the simplex table corresponding to the variable */ len = lpx_eval_tab_row(prob, m+j, ind, val); len = lpx_remove_tiny(len, ind, NULL, val, 1e-10); /* generate Gomory's mixed integer cut: a[1]*x[1] + ... + a[n]*x[n] >= b */ len = lpx_gomory_cut(prob, len, ind, val, work); if (len < 0) continue; insist(0 <= len && len <= n); len = lpx_remove_tiny(len, ind, NULL, val, 1e-10); if (fabs(val[0]) < 1e-10) val[0] = 0.0; /* if the cut is too long, skip it */ if (len > maxlen) continue; /* if the cut contains coefficients with too large magnitude, do not use it to prevent numeric instability */ for (k = 0; k <= len; k++) /* including rhs */ if (fabs(val[k]) > 1e+6) break; if (k <= len) continue; /* at the current point the cut inequality is violated, i.e. the residual b - (a[1]*x[1] + ... + a[n]*x[n]) > 0; note that for Gomory's cut the residual is less than 1.0 */ /* in order not to depend on the magnitude of coefficients we use scaled residual: r = [b - (a[1]*x[1] + ... + a[n]*x[n])] / max(1, |a[j]|) */ temp = 1.0; for (k = 1; k <= len; k++) if (temp < fabs(val[k])) temp = fabs(val[k]); r = (val[0] - lpx_eval_row(prob, len, ind, val)) / temp; if (r < 1e-5) continue; /* estimate degradation (worsening) of the objective function by one dual simplex step if the cut row would be introduced in the problem */ d = lpx_eval_degrad(prob, len, ind, val, LPX_LO, val[0]); /* ignore the sign of degradation */ d = fabs(d); /* which cut should be used? there are two basic cases: 1) if the degradation is non-zero, we are interested in a cut providing maximal degradation; 2) if the degradation is zero (i.e. a non-basic variable which would enter the basis in the adjacent vertex has zero reduced cost), we are interested in a cut providing maximal scaled residual; in both cases it is desired that the cut length (the number of inequality coefficients) is possibly short */ /* if both degradation and scaled residual are small, skip the cut */ if (d < 0.001 && r < 0.001) continue; /* if there is no cut chosen, choose this cut */ else if (cut_j == 0) ; /* if this cut provides stronger degradation and has shorter length, choose it */ else if (cut_d != 0.0 && cut_d < d) ; /* if this cut provides larger scaled residual and has shorter length, choose it */ else if (cut_d == 0.0 && cut_r < r) ; /* otherwise skip the cut */ else continue; /* save attributes of the cut choosen */ cut_j = j, cut_r = r, cut_d = d; } /* if a cut has been chosen, include it to the problem */ if (cut_j != 0) { j = cut_j; /* compute the row of the simplex table */ len = lpx_eval_tab_row(prob, m+j, ind, val); len = lpx_remove_tiny(len, ind, NULL, val, 1e-10); /* generate the cut */ len = lpx_gomory_cut(prob, len, ind, val, work); insist(0 <= len && len <= n); len = lpx_remove_tiny(len, ind, NULL, val, 1e-10); if (fabs(val[0]) < 1e-10) val[0] = 0.0; /* include the corresponding row in the problem */ i = lpx_add_rows(prob, 1); lpx_set_row_bnds(prob, i, LPX_LO, val[0], 0.0); lpx_set_mat_row(prob, i, len, ind, val); } /* free working arrays */ ufree(ind); ufree(val); ufree(work); return; }