Example #1
0
void printResult(glp_prob * Prob, FILE * out) {
	int i;
	char buf[AUXSIZE];
	glp_smcp * param = malloc(sizeof(glp_smcp));
	glp_init_smcp(param);
	param->msg_lev = GLP_MSG_ERR;
	param->presolve = GLP_ON;
	int solution[MAXSIZE];

	for( i = 0 ; i < n ; ++i )
		solution[planes[i].pos] = i;

	mapSolution(Prob,solution);
	glp_simplex(Prob,param);
	
	if( simpleOutput ) {
		time(&final);
		fprintf(out,"%i & %i \\\\ \n",(int)glp_get_obj_val(Prob),(int)difftime(final,initial));
		return;
	}
	
	fprintf(out,"Best found solution's value: %lf\n\n",glp_get_obj_val(Prob));
	
	double time;
	for( i = 0 ; i < n ; ++i ) {
        sprintf(buf,"x%i",solution[i]);
		time = glp_get_col_prim(Prob, glp_find_col(Prob, buf));
		fprintf(out,"The %i-th airplane to arrive is airplane %i, at the time %lf\n",
		        i+1,solution[i]+1,time);
	}
}
Example #2
0
double glpk_wrapper::get_objective() {
    assert(is_sat());
    if (solver_type == SIMPLEX || solver_type == EXACT) {
        return glp_get_obj_val(lp);
    } else {
        assert(solver_type == INTERIOR);
        return glp_ipt_obj_val(lp);
    }
}
Example #3
0
 double solve()
 {
   glp_smcp smcp;
   glp_iocp iocp;
   glp_init_smcp(&smcp); smcp.msg_lev = GLP_MSG_ERR;
   glp_init_iocp(&iocp); iocp.msg_lev = GLP_MSG_ERR;
   glp_load_matrix(ip_, ia_.size()-1, &ia_[0], &ja_[0], &ar_[0]);
   glp_simplex(ip_, &smcp);
   glp_intopt(ip_, &iocp);
   return glp_get_obj_val(ip_);
 }
Example #4
0
int CMyProblem::PrintLPSolution(ostream &out)
{
	glp_create_index(lp);
	out << "LP solution" << endl;
	out << "Dir;" << ((glp_get_obj_dir(lp)==GLP_MIN) ? "min" : "max") << endl;
	out << "f; " << glp_get_obj_val(lp) << ";/*" << RealResult() << "*/" << endl; 
	out << "Status;" << DecodeStatus(glp_get_status(lp)) << endl;
	PrintSolArray(lp,"x",out);
	PrintSolArray(lp,"y",out);
	glp_delete_index(lp);
	return 0;
}
int main(void) {

	glp_prob *lp;
	int ia[1+1000], ja[1+1000];
	double ar[1+1000], z, x1, x2, x3;

	s1: lp = glp_create_prob();
	s2: glp_set_prob_name(lp, "sample");
	s3: glp_set_obj_dir(lp, GLP_MAX);
	s4: glp_add_rows(lp, 3);
	s5: glp_set_row_name(lp, 1, "p");
	s6: glp_set_row_bnds(lp, 1, GLP_UP, 0.0, 100.0);
	s7: glp_set_row_name(lp, 2, "q");
	s8: glp_set_row_bnds(lp, 2, GLP_UP, 0.0, 600.0);
	s9: glp_set_row_name(lp, 3, "r");
	s10: glp_set_row_bnds(lp, 3, GLP_UP, 0.0, 300.0);
	s11: glp_add_cols(lp, 3);
	s12: glp_set_col_name(lp, 1, "x1");
	s13: glp_set_col_bnds(lp, 1, GLP_LO, 0.0, 0.0);
	s14: glp_set_obj_coef(lp, 1, 10.0);
	s15: glp_set_col_name(lp, 2, "x2");
	s16: glp_set_col_bnds(lp, 2, GLP_LO, 0.0, 0.0);
	s17: glp_set_obj_coef(lp, 2, 6.0);
	s18: glp_set_col_name(lp, 3, "x3");
	s19: glp_set_col_bnds(lp, 3, GLP_LO, 0.0, 0.0);
	s20: glp_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: glp_load_matrix(lp, 9, ia, ja, ar);
	s31: glp_simplex(lp, NULL);
	s32: z = glp_get_obj_val(lp);

	s33: x1 = glp_get_col_prim(lp, 1);
	s34: x2 = glp_get_col_prim(lp, 2);
	s35: x3 = glp_get_col_prim(lp, 3);

	s36: printf("\nz = %g; x1 = %g; x2 = %g; x3 = %g\n", z, x1, x2, x3);

	s37: glp_delete_prob(lp);
	
return 0;
}
Example #6
0
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;
}
Example #7
0
int c_simplex_sparse(int m, int n, DMAT(c), DMAT(b), DVEC(s)) {
    glp_prob *lp;
    lp = glp_create_prob();
    glp_set_obj_dir(lp, GLP_MAX);
    int i,j,k;
    int tot = cr - n;
    glp_add_rows(lp, m);
    glp_add_cols(lp, n);

    //printf("%d %d\n",m,n);

    // the first n values
    for (k=1;k<=n;k++) {
        glp_set_obj_coef(lp, k, AT(c, k-1, 2));
        //printf("%d %f\n",k,AT(c, k-1, 2));
    }

    int * ia = malloc((1+tot)*sizeof(int));
    int * ja = malloc((1+tot)*sizeof(int));
    double * ar = malloc((1+tot)*sizeof(double));

    for (k=1; k<= tot; k++) {
        ia[k] = rint(AT(c,k-1+n,0));
        ja[k] = rint(AT(c,k-1+n,1));
        ar[k] =      AT(c,k-1+n,2);
        //printf("%d %d %f\n",ia[k],ja[k],ar[k]);
    }
    glp_load_matrix(lp, tot, ia, ja, ar);

    int t;
    for (i=1;i<=m;i++) {
    switch((int)rint(AT(b,i-1,0))) {
        case 0: { t = GLP_FR; break; }
        case 1: { t = GLP_LO; break; }
        case 2: { t = GLP_UP; break; }
        case 3: { t = GLP_DB; break; }
       default: { t = GLP_FX; break; }
    }
    glp_set_row_bnds(lp, i, t , AT(b,i-1,1), AT(b,i-1,2));
    }
    for (j=1;j<=n;j++) {
    switch((int)rint(AT(b,m+j-1,0))) {
        case 0: { t = GLP_FR; break; }
        case 1: { t = GLP_LO; break; }
        case 2: { t = GLP_UP; break; }
        case 3: { t = GLP_DB; break; }
       default: { t = GLP_FX; break; }
    }
    glp_set_col_bnds(lp, j, t , AT(b,m+j-1,1), AT(b,m+j-1,2));
    }
    glp_term_out(0);
    glp_simplex(lp, NULL);
    sp[0] = glp_get_status(lp);
    sp[1] = glp_get_obj_val(lp);
    for (k=1; k<=n; k++) {
        sp[k+1] = glp_get_col_prim(lp, k);
    }
    glp_delete_prob(lp);
    free(ia);
    free(ja);
    free(ar);

    return 0;
}
Example #8
0
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;
}
Example #9
0
double lpx_get_obj_val(LPX *lp)
{     /* retrieve objective value (basic solution) */
      return glp_get_obj_val(lp);
}
Example #10
0
/*
    R is the random contraint data in row major memory layout
    ridx is an N array of integers 
    soln is an array of length (n+1) soln[n] is t (objective value)
    active_constr is an N-length 0-1 array
*/
void solve_lp(int N, int n, double* R, int* ridx, double* soln, int* active_constr)
{
    double tol = 1.0e-14;
    int size = (N+1)*(n+1) + 1; // We add one because GLPK indexes arrays
                                // starting at 1 instead of 0.

    glp_prob *lp;
    int* ia = malloc(size * sizeof(int));
    int* ja = malloc(size * sizeof(int));
    double* ar = malloc(size * sizeof(double));

    int i, j;
  
    lp = glp_create_prob();
    glp_set_prob_name(lp, "portfolio");
    glp_set_obj_dir(lp, GLP_MAX);

    glp_add_rows(lp, N+1);

    // Sampled constraints are ">= 0"
    for (i = 1; i <= N; i++) {
        glp_set_row_bnds(lp, i, GLP_LO, 0.0, 0.0);
    }
  
    // Sum = 1 constraint
    glp_set_row_name(lp, N+1, "sum");
    glp_set_row_bnds(lp, N+1, GLP_FX, 1.0, 1.0);
  
    glp_add_cols(lp, n+1);
  
    // Nonnegative variables y
    for (i = 1; i <= n; i++) {
        glp_set_col_bnds(lp, i, GLP_LO, 0.0, 0.0);
        glp_set_obj_coef(lp, i, 0.0);
    }
  
    // Free variable t
    glp_set_col_name(lp, n+1, "t");
    glp_set_col_bnds(lp, n+1, GLP_FR, 0.0, 0.0);
    glp_set_obj_coef(lp, n+1, 1.0);
    
    // for (i = 0; i < N*(n-1); i++) {
    //     printf("%d: %g\n", i, R[i]);
    // }

    int idx = 1;
    // Sampled constraints
    for (i = 1; i <= N; i++) {
        // Uncertain assets
        for (j = 1; j < n; j++) {
            ia[idx] = i;
            ja[idx] = j;
            ar[idx] = R[ ridx[(i-1)] * (n-1) + (j-1) ];
            idx += 1;
        }

        // Fixed return asset
        ia[idx] = i;
        ja[idx] = n;
        ar[idx] = 1.05;
        idx += 1;

        // t
        ia[idx] = i;
        ja[idx] = n+1;
        ar[idx] = -1.0;
        idx += 1;
    }

    // Sum = 1 constraint
    for (i = 1; i <= n; i++) {
        ia[idx] = N+1;
        ja[idx] = i;
        ar[idx] = 1.0;
        idx += 1;
    }
    // t
    ia[idx] = N+1;
    ja[idx] = n+1;
    ar[idx] = 0.0;
    idx += 1;

    // for (i = 1; i < size; i++) {
    //     printf("%d %d %g\n", ia[i], ja[i], ar[i]);
    // }

    glp_load_matrix(lp, size-1, ia, ja, ar);

    // glp_scale_prob(lp, GLP_SF_AUTO);

    glp_smcp param;
    glp_init_smcp(&param);
    param.meth = GLP_PRIMAL;
    //glp_std_basis(lp);
    glp_simplex(lp, &param);
  
    double z = glp_get_obj_val(lp);
    // printf("z = %g\n", z);
    if (soln) {
        for (i = 0; i < n; i++) {
            double y = glp_get_col_prim(lp, i+1);
            soln[i] = y;
            // printf("y%d = %g\n", i, y);
        }
        double t = glp_get_col_prim(lp, n+1);
        soln[n] = t;
        // printf("t = %g\n", glp_get_col_prim(lp, n+1));
    }
  

    for (i = 1; i <= N; i++) {
        double slack = glp_get_row_prim(lp, i);
        active_constr[i-1] = fabs(slack) < tol ? 1 : 0;
        // printf("constr%d %d\n", i, active_constr[i-1]);
    }


    glp_delete_prob(lp);
    // glp_free_env();
    free(ia);
    free(ja);
    free(ar);
}
Example #11
0
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;
}
Example #12
0
static bool Graph_solve(Graph& graph, size_t loops, PositionList* position_tbl) {
    glp_prob* lp = glp_create_prob();
    glp_set_prob_name(lp, "scaffold");
    glp_set_obj_dir(lp, GLP_MIN);

    size_t rows = 0, cols = 0, vals = 0;
    for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) {
        ++cols; // var x_i
        for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) {
            rows += 3;
            cols += 2; // var e_i_j; var E_i_j;
            vals += 7;
        }
    }

    glp_add_rows(lp, rows);
    glp_add_cols(lp, cols);

    std::map< std::pair< size_t, size_t >, size_t > mapping;
    {
        size_t row = 1, col = 1;
        for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) {
            mapping[std::make_pair(i->first, -1)] = col;

            glp_set_col_bnds(lp, col++, GLP_LO, 0.0, 0.0); // x_i >= 0
            for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) {
                glp_set_row_bnds(lp, row++, GLP_FX, j->second, j->second);
                glp_set_row_bnds(lp, row++, GLP_LO, 0.0, 0.0);
                glp_set_row_bnds(lp, row++, GLP_LO, 0.0, 0.0);

                mapping[std::make_pair(i->first, j->first)] = col;

                ++col; // var e_i
                glp_set_obj_coef(lp, col++, 1.0);
            }
        }
    }

    LOG4CXX_TRACE(logger, boost::format(" rows = %d, cols = %d, vals = %d") % rows % cols % vals);

    int* ia = new int[vals + 1];
    int* ja = new int[vals + 1];
    double* ra = new double[vals + 1];

    {
        size_t l = 1, row = 1, col = 1;
        for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) {
            for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) {
                // x_j - x_i + e_i_j = d_i_j
                ia[l] = row;
                ja[l] = mapping[std::make_pair(j->first, -1)];
                ra[l] = 1.0;
                ++l;

                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, -1)];
                ra[l] = -1.0;
                ++l;

                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, j->first)] + 0;
                ra[l] = 1.0;
                ++l;

                ++row;

                // E_i_j + e_i_j >= 0
                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, j->first)] + 1;
                ra[l] = 1.0;
                ++l;

                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, j->first)] + 0;
                ra[l] = 1.0;
                ++l;

                ++row;

                // E_i_j - e_i_j >= 0
                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, j->first)] + 1;
                ra[l] = 1.0;
                ++l;

                ia[l] = row;
                ja[l] = mapping[std::make_pair(i->first, j->first)] + 0;
                ra[l] = -1.0;
                ++l;

                ++row;
            }
        }
    }

    glp_load_matrix(lp, vals, ia, ja, ra);

    glp_smcp parm;
    glp_init_smcp(&parm);
    parm.it_lim = loops;
    //parm.pricing = GLP_PT_PSE;
    //parm.presolve = GLP_ON;
    parm.msg_lev = GLP_MSG_ERR;
    glp_simplex(lp, &parm);

    double z = glp_get_obj_val(lp);
    LOG4CXX_TRACE(logger, boost::format("z = %f") % z);

    for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) {
        size_t val = glp_get_col_prim(lp, mapping[std::make_pair(i->first, -1)]);
        if (position_tbl != NULL) {
            (*position_tbl)[i->first] = val;
        }
        LOG4CXX_TRACE(logger, boost::format("x\t%d\t%d") % i->first % val);
    }

    delete[] ra;
    delete[] ja;
    delete[] ia;

    glp_delete_prob(lp);
    return true;
}
Example #13
0
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;
}
Example #14
0
int CConstraints::GLPK_lp(CModel* pmodel)
{
    glp_prob* lp = glp_create_prob();

    int iRow = (int) m_vWeights.size();
    //int iCol = (int) m_iWeightLength + m_iPatternNum;
    int iSize = iRow * ( m_iWeightLength + 1);
    int ia[10 + iSize], ja[1 + iSize];
    double ar[1 + iSize];
    glp_set_prob_name(lp, "StrLP");
    glp_set_obj_dir(lp, GLP_MIN);
    glp_add_rows(lp, (int) m_vWeights.size());
    // setup rows
    for (int i = 0; i < (int) m_vWeights.size(); i ++)
    {
        char tmp[200];
        sprintf(tmp, "cc_%d", i + 1);
        glp_set_row_name(lp, i + 1, tmp);
        glp_set_row_bnds(lp, i + 1, GLP_LO, m_fDistance - m_fEpsilon, 0);
    }
    glp_add_cols(lp, m_iWeightLength + m_iPatternNum);
    for (int i = 0; i < m_iWeightLength; i ++)
    {
        char tmp[200];
        sprintf(tmp, "w%d", i + 1);
        glp_set_col_name(lp, i + 1, tmp);
        glp_set_col_bnds(lp, i + 1, GLP_LO, 0, 0.0);
        glp_set_obj_coef(lp, i + 1, 1.0);
    }

    for (int i = 0; i < m_iPatternNum; i ++)
    {
        char tmp[200];
        sprintf(tmp, "e%d", i + 1);
        glp_set_col_name(lp, m_iWeightLength + i + 1, tmp);
        glp_set_col_bnds(lp, m_iWeightLength + i + 1, GLP_LO, 0, 0.0);
        glp_set_obj_coef(lp, m_iWeightLength + i + 1, m_fC / m_iPatternNum);
    }
    int iIndex = 1;
    for (int i = 0; i < (int)m_vWeights.size(); i ++)
    {
        double* pd = m_vWeights[i];
        for (int j = 0; j < (int) m_iWeightLength; j ++)
        {
            ia[iIndex] = i + 1, ja[iIndex] = j + 1;
            if (pmodel->m_vSign[j] <= 0)
            {
                ar[iIndex] = -pd[j];
            }
            else
            {
                ar[iIndex] = pd[j];
            }
            iIndex ++;
        }
        ia[iIndex] = i + 1;
        ja[iIndex] = m_iWeightLength + m_vPatternIndex[i] + 1;
        //ar[iIndex] = 1;
        ar[iIndex] = m_vLoss[i];
        iIndex ++;
    }
    glp_load_matrix(lp, iIndex - 1, ia, ja, ar);
    glp_simplex(lp, NULL);
    double z = glp_get_obj_val(lp);
    fprintf(stderr, "minimal value %f \n", z);
    for (int i = 0; i < m_iWeightLength; i ++)
    {
        double x = glp_get_col_prim(lp, i + 1);
        if (pmodel->m_vSign[i] <=0)
        {
            pmodel->m_vWeight[i] = -x;
        }
        else
        {
            pmodel->m_vWeight[i] = x;
        }

        if (x != 0) fprintf(stderr, "(w%d, %f)\t", i + 1, pmodel->m_vWeight[i]);
    }
    for (int i = 0; i < m_iPatternNum; i ++)
    {
        double x = glp_get_col_prim(lp, m_iWeightLength + i + 1);
        pmodel->m_vTheta[i] = x;
        if (x != 0)  fprintf(stderr, "(e%d, %f)\t", i + 1, pmodel->m_vTheta[i]);
    }
    glp_delete_prob(lp);
    return 1;
}
Example #15
0
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;
}
Example #16
0
double c_glp_get_obj_val(glp_prob *lp){
  	return glp_get_obj_val(lp);
}
Example #17
0
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;
}
Example #18
0
bool isFeasible()
{
	int nCons;
	int coef1[MAXNEDGES], coef2[MAXNEDGES];
	int ind[MAXNEDGES+1];
	double val[MAXNEDGES+1];


	glp_prob * lp = glp_create_prob();
	glp_set_obj_dir(lp, GLP_MAX);
	glp_add_cols(lp, nEdges+1);
	for (int i=0; i<nEdges+1; i++) 
		glp_set_col_bnds(lp, i+1, GLP_LO, 0, 0);
	glp_set_obj_coef(lp, nEdges+1, 1);
	nCons = 0;
	for (int i=0; i<nEdges; i++) {
		nCons++;
		glp_add_rows(lp,1);
		glp_set_row_bnds(lp, nCons, GLP_UP, 0, 0);
		ind[1] = nEdges+1; val[1] = 1; //gamma <= l_e
		ind[2] = i+1; val[2] = -1;
		glp_set_mat_row(lp, nCons, 2, ind, val);
	}
	for (int m=0; m<k; m++) {
		int first = -1;
		for (int i=0; i<paths[m].n; i++) if (paths[m].isShort[i]) { first = i; break; }
		assert(first>=0);
		setCoef(coef1, m, first);
		for (int i=first+1; i<paths[m].n; i++) if (paths[m].isShort[i]) {
			setCoef(coef2, m, i);
			nCons++;
			glp_add_rows(lp,1);
			glp_set_row_bnds(lp, nCons, GLP_FX, 0, 0);
			int nEle = 0;
			for (int j=0; j<nEdges; j++) if (coef1[j] ^ coef2[j]) {
				nEle++;
				ind[nEle] = j+1;
				val[nEle] = (coef1[j])? 1:-1;
			}
			glp_set_mat_row(lp, nCons, nEle, ind, val);
		}
		for (int i=0; i<paths[m].n; i++) if (!paths[m].isShort[i]){
			setCoef(coef2, m, i);
			nCons++;
			glp_add_rows(lp,1);
			glp_set_row_bnds(lp, nCons, GLP_UP, 0, 0);
			int nEle = 0;
			for (int j=0; j<nEdges; j++) if (coef1[j] ^ coef2[j]) {
				nEle++;
				ind[nEle] = j+1;
				val[nEle] = (coef1[j])? 1:-1;
			}
			glp_set_mat_row(lp, nCons, nEle, ind, val);
		}
	}
	nCons++;
	glp_add_rows(lp,1);
	glp_set_row_bnds(lp, nCons, GLP_UP, 0, 1);
	for (int j=0; j<nEdges; j++) {
		ind[j+1] = j+1;
		val[j+1] = 1;
	}
	glp_set_mat_row(lp, nCons, nEdges, ind, val);
	glp_term_out(GLP_OFF);
	glp_simplex(lp, NULL);
	double ret = glp_get_obj_val(lp);
	glp_delete_prob(lp);
	return (ret>0);
}