예제 #1
0
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;
}
예제 #2
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;
}
예제 #3
0
inline void GetSolArray(glp_prob* lp,  char* name, vector<vector<double>> &arr, bool integer=false)
{
    arr.clear();
    char buff[256];
    int i=1;
    int j=1;
    double value;
    glp_create_index(lp);
    int col_num=glp_find_col(lp,GenerateColName(buff, name, i, j));
    vector<double> row;
    while( col_num )
    {
        if (!integer)
        {
            value = glp_get_col_prim(lp,col_num);
        }
        else
        {
            value = glp_mip_col_val(lp,col_num);
        }
        row.push_back(value);

        //cout << value << ";";

        j++;
        col_num=glp_find_col(lp,GenerateColName(buff, name, i, j));
        if (!col_num)
        {
            arr.push_back(row);
            //cout << endl;
            row.clear();
            i++;
            j=1;
            col_num=glp_find_col(lp,GenerateColName(buff, name, i, j));
        }
    }
}
예제 #4
0
void lpx_create_index(LPX *lp)
{     /* create the name index */
      glp_create_index(lp);
      return;
}
예제 #5
0
파일: avioes.c 프로젝트: bfiss/Avioes-Grasp
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;
}
예제 #6
0
void c_glp_create_index(glp_prob *lp){
  	glp_create_index(lp);
}
예제 #7
0
파일: glpcpx.c 프로젝트: emersonxsu/glpk
int glp_read_lp(glp_prob *P, const glp_cpxcp *parm, const char *fname)
{     /* read problem data in CPLEX LP format */
      glp_cpxcp _parm;
      struct csa _csa, *csa = &_csa;
      int ret;
      xprintf("Reading problem data from '%s'...\n", fname);
      if (parm == NULL)
         glp_init_cpxcp(&_parm), parm = &_parm;
      /* check control parameters */
      check_parm("glp_read_lp", parm);
      /* initialize common storage area */
      csa->P = P;
      csa->parm = parm;
      csa->fname = fname;
      csa->fp = NULL;
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->count = 0;
      csa->c = '\n';
      csa->token = T_EOF;
      csa->image[0] = '\0';
      csa->imlen = 0;
      csa->value = 0.0;
      csa->n_max = 100;
      csa->ind = xcalloc(1+csa->n_max, sizeof(int));
      csa->val = xcalloc(1+csa->n_max, sizeof(double));
      csa->flag = xcalloc(1+csa->n_max, sizeof(char));
      memset(&csa->flag[1], 0, csa->n_max * sizeof(char));
      csa->lb = xcalloc(1+csa->n_max, sizeof(double));
      csa->ub = xcalloc(1+csa->n_max, sizeof(double));
#if 1 /* 27/VII-2013 */
      csa->lb_warn = csa->ub_warn = 0;
#endif
      /* erase problem object */
      glp_erase_prob(P);
      glp_create_index(P);
      /* open input CPLEX LP file */
      csa->fp = glp_open(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open '%s' - %s\n", fname, get_err_msg());
         ret = 1;
         goto done;
      }
      /* scan very first token */
      scan_token(csa);
      /* parse definition of the objective function */
      if (!(csa->token == T_MINIMIZE || csa->token == T_MAXIMIZE))
         error(csa, "'minimize' or 'maximize' keyword missing\n");
      parse_objective(csa);
      /* parse constraints section */
      if (csa->token != T_SUBJECT_TO)
         error(csa, "constraints section missing\n");
      parse_constraints(csa);
      /* parse optional bounds section */
      if (csa->token == T_BOUNDS) parse_bounds(csa);
      /* parse optional general, integer, and binary sections */
      while (csa->token == T_GENERAL ||
             csa->token == T_INTEGER ||
             csa->token == T_BINARY) parse_integer(csa);
      /* check for the keyword 'end' */
      if (csa->token == T_END)
         scan_token(csa);
      else if (csa->token == T_EOF)
         warning(csa, "keyword 'end' missing\n");
      else
         error(csa, "symbol '%s' in wrong position\n", csa->image);
      /* nothing must follow the keyword 'end' (except comments) */
      if (csa->token != T_EOF)
         error(csa, "extra symbol(s) detected beyond 'end'\n");
      /* set bounds of variables */
      {  int j, type;
         double lb, ub;
         for (j = 1; j <= P->n; j++)
         {  lb = csa->lb[j];
            ub = csa->ub[j];
            if (lb == +DBL_MAX) lb = 0.0;      /* default lb */
            if (ub == -DBL_MAX) ub = +DBL_MAX; /* default ub */
            if (lb == -DBL_MAX && ub == +DBL_MAX)
               type = GLP_FR;
            else if (ub == +DBL_MAX)
               type = GLP_LO;
            else if (lb == -DBL_MAX)
               type = GLP_UP;
            else if (lb != ub)
               type = GLP_DB;
            else
               type = GLP_FX;
            glp_set_col_bnds(csa->P, j, type, lb, ub);
         }
      }
      /* print some statistics */
      xprintf("%d row%s, %d column%s, %d non-zero%s\n",
         P->m, P->m == 1 ? "" : "s", P->n, P->n == 1 ? "" : "s",
         P->nnz, P->nnz == 1 ? "" : "s");
      if (glp_get_num_int(P) > 0)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         if (ni == 1)
         {  if (nb == 0)
               xprintf("One variable is integer\n");
            else
               xprintf("One variable is binary\n");
         }
         else
         {  xprintf("%d integer variables, ", ni);
            if (nb == 0)
               xprintf("none");
            else if (nb == 1)
               xprintf("one");
            else if (nb == ni)
               xprintf("all");
            else
               xprintf("%d", nb);
            xprintf(" of which %s binary\n", nb == 1 ? "is" : "are");
         }
      }
      xprintf("%d lines were read\n", csa->count);
      /* problem data has been successfully read */
      glp_delete_index(P);
      glp_sort_matrix(P);
      ret = 0;
done: if (csa->fp != NULL) glp_close(csa->fp);
      xfree(csa->ind);
      xfree(csa->val);
      xfree(csa->flag);
      xfree(csa->lb);
      xfree(csa->ub);
      if (ret != 0) glp_erase_prob(P);
      return ret;
}
예제 #8
0
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;
}