コード例 #1
0
int GLPKPrintFromSolver(int lpcount) {
	if (GLPKModel == NULL) {
		FErrorFile() << "Cannot print problem because problem does not exist." << endl;
		FlushErrorFile();
		return FAIL;
	}

	string Filename = CheckFilename(FOutputFilepath()+GetParameter("LP filename"));
	int Status = glp_write_lp(GLPKModel,NULL,ConvertStringToCString(Filename));

	if (Status) {
		FErrorFile() << "Unable to write problem to file due to error in writing function." << endl;
		FlushErrorFile();
		return FAIL;
	}

	Filename = CheckFilename(FOutputFilepath()+GetParameter("LP filename")+itoa(lpcount));
	Status = glp_write_lp(GLPKModel,NULL,ConvertStringToCString(Filename));

	if (Status) {
		FErrorFile() << "Unable to write problem to file due to error in writing function." << endl;
		FlushErrorFile();
		return FAIL;
	}

	return SUCCESS;
}
コード例 #2
0
ファイル: ULS.c プロジェクト: Shakit/IP2015TP2
/* Different cases :
 *     - if the created node is root, then father is NULL, the problem version in the node is the one gave as parameter.
 *     - else we copy the problem, and had the constraint "x_{y} = valy"
 */
void create_node(node* n, glp_prob* prob, node* father, int y, double valy)
{
	n->father = father;
	n->leftSon = NULL;
	n->rightSon = NULL;
	n->check = 0;
	
	int i = 0;
	int ind[] = {0,y};
	double val[] = {0,1};
	
	if (n-> father == NULL)
	{
		n->prob = prob;
	}
	else
	{
		n->prob = glp_create_prob();
		glp_copy_prob(n->prob, n->father->prob, GLP_ON);
		i = glp_add_rows(n->prob, 1);
		glp_set_mat_row(n->prob, i, 1, ind, val);
		glp_set_row_bnds(n->prob, i, GLP_FX, valy, valy);
	}

	glp_smcp parm;
	glp_init_smcp(&parm);
	parm.msg_lev = GLP_MSG_OFF;

	glp_iocp parmip;
	glp_init_iocp(&parmip);
	parmip.msg_lev = GLP_MSG_OFF;

	glp_write_lp(prob, NULL, "ULS.lp");

	n->solveFlag = glp_simplex(n->prob, &parm); glp_intopt(n->prob, &parmip);

	n->z = glp_mip_obj_val(n->prob);
	n->x = (double *) malloc (glp_get_num_cols(n->prob) * sizeof(double));
	for (i = 0; i < glp_get_num_cols(n->prob); ++i) n->x[i] = glp_mip_col_val(n->prob, i+1);
}
コード例 #3
0
int main(int argc, char *argv[]) {

	/* Structures de données propres à GLPK */
	glp_prob *prob; // Déclaration d'un pointeur sur le problème
	int ia[1 + NBCREUX];
	int ja[1 + NBCREUX];
	double ar[1 + NBCREUX]; // Déclaration des 3 tableaux servant à définir la partie creuse de la matrice des contraintes

    /* Variables récupérant les résultats de la résolution du problème (fonction objectif et valeur des variables) */
	int i, j;
	double z; 
	double x[NBVAR];

	// Autres variables
	int * p = (int*)malloc(n * sizeof(int));
	p[1] = 34;
	p[2] = 6;
	p[3] = 8;
	p[4] = 17;
	p[5] = 16;
	p[6] = 5;
	p[7] = 13;
	p[8] = 21;
	p[9] = 25;
	p[10] = 31;
	p[11] = 14;
	p[12] = 13;
	p[13] = 33;
	p[14] = 9;
	p[15] = 25;
	p[16] = 25;

	/* Transfert de ces données dans les structures utilisées par la bibliothèque GLPK */
	
	prob = glp_create_prob(); /* allocation mémoire pour le problème */ 
	glp_set_prob_name(prob, "wagons"); /* affectation d'un nom */
	glp_set_obj_dir(prob, GLP_MIN); /* Il s'agit d'un problème de minimisation */
	
	/* Déclaration du nombre de contraintes (nombre de lignes de la matrice des contraintes) */
	
	glp_add_rows(prob, NBCONTR); 

	/* On commence par préciser les bornes sur les contraintes, les indices commencent à 1 (!) dans GLPK */

	/* Premier ensemble de contraintes ( c = 1 ) */
	for(i = 1; i <= n; i++) {
		glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0);
	}

	/* Second ensembles de contraintes (c <= 0 ) */
	for(i = n + 1; i <= NBCONTR; i++) {
		glp_set_row_bnds(prob, i, GLP_UP, 0.0, 0.0);
	}

	/* Déclaration du nombre de variables */
	
	glp_add_cols(prob, NBVAR); 
	
	/* On précise le type des variables, les indices commencent à 1 également pour les variables! */
	
	for(i = 1; i <= NBVAR - 1; i++) {
		glp_set_col_bnds(prob, i, GLP_DB, 0.0, 1.0);
		glp_set_col_kind(prob, i, GLP_BV);	/* les variables sont binaires */	
	}

	glp_set_col_bnds(prob, NBVAR, GLP_LO, 0.0, 0.0); /* La dernière variables est continue (par défaut) non négative */

	/* Définition des coefficients des variables dans la fonction objectif */

	for(i = 1;i <= n*m;i++) {
		glp_set_obj_coef(prob,i,0.0); // Tous les coûts sont à 0 (sauf le dernier) 
	}

	/* Dernier coût (qui vaut 1) */
	glp_set_obj_coef(prob,n*m + 1,1.0); 
	
	/* Définition des coefficients non-nuls dans la matrice des contraintes, autrement dit les coefficients de la matrice creuse */

	int pos = 1;
	for(i = 1; i <= n; i++) {
		for(j = 1; j <= m; j++) {

			// Première moitié de la matrice
			ja[pos] = (i - 1)*m + j;
			ia[pos] = i;
			ar[pos] = 1;
			pos++;

			// Deuxième moitié de la matrice
			ja[pos] = (i - 1)*m + j;
			ia[pos] = n + j;
			ar[pos] = p[i];
			pos++;
		}
	}

	// ajout des -1 dans la dernière colonne
	for(i = n + 1; i <= n + m; i++) {
		ja[pos] = n*m + 1;
		ia[pos] = i;
		ar[pos] = -1;
		pos++;
	}

	/* Chargement de la matrice dans le problème */
	
	glp_load_matrix(prob,NBCREUX,ia,ja,ar); 
	
	/* Ecriture de la modélisation dans un fichier */

	glp_write_lp(prob,NULL,"wagons.lp");

	/* Résolution, puis lecture des résultats */
	
	glp_simplex(prob,NULL);	glp_intopt(prob,NULL); /* Résolution */
	z = glp_mip_obj_val(prob); /* Récupération de la valeur optimale. Dans le cas d'un problème en variables continues, l'appel est différent : z = glp_get_obj_val(prob); */
	for(i = 0;i < NBVAR; i++) x[i] = glp_mip_col_val(prob,i+1); /* Récupération de la valeur des variables, Appel différent dans le cas d'un problème en variables continues : for(i = 0;i < p.nbvar;i++) x[i] = glp_get_col_prim(prob,i+1); */

	printf("z = %lf\n",z);
	for(i = 0;i < NBVAR;i++) printf("x%c = %d, ",'B'+i,(int)(x[i] + 0.5)); /* un cast est ajouté, x[i] pourrait être égal à 0.99999... */ 
	puts("");

	/* Libération de la mémoire */
	glp_delete_prob(prob); 
	free(p);

	return 0;

}
コード例 #4
0
/**
 * Solves the MLP problem
 *
 * @param mlp the MLP Handle
 * @param ctx solution context
 * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
 */
int
GAS_mlp_solve_problem (struct GAS_MLP_Handle *mlp, struct GAS_MLP_SolutionContext *ctx)
{
  int res;
  /* Check if solving is already running */
  if (GNUNET_YES == mlp->semaphore)
  {
    if (mlp->mlp_task != GNUNET_SCHEDULER_NO_TASK)
    {
      GNUNET_SCHEDULER_cancel(mlp->mlp_task);
      mlp->mlp_task = GNUNET_SCHEDULER_NO_TASK;
    }
    mlp->mlp_task = GNUNET_SCHEDULER_add_delayed (mlp->exec_interval, &mlp_scheduler, mlp);
    return GNUNET_SYSERR;
  }
  mlp->semaphore = GNUNET_YES;

  mlp->last_execution = GNUNET_TIME_absolute_get ();

  ctx->lp_result = GNUNET_SYSERR;
  ctx->mlp_result = GNUNET_SYSERR;
  ctx->lp_duration = GNUNET_TIME_UNIT_FOREVER_REL;
  ctx->mlp_duration = GNUNET_TIME_UNIT_FOREVER_REL;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Solve LP problem\n");
#if WRITE_MLP
  char * name;
  static int i;
  i++;
  GNUNET_asprintf(&name, "problem_%i", i);
  glp_write_lp (mlp->prob, 0, name);
  GNUNET_free (name);
# endif

  res = mlp_solve_lp_problem (mlp, ctx);
  ctx->lp_result = res;
  if (res != GNUNET_OK)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "LP Problem solving failed\n");
    mlp->semaphore = GNUNET_NO;
    return GNUNET_SYSERR;
  }

#if WRITE_MLP
  GNUNET_asprintf(&name, "problem_%i_lp_solution", i);
  glp_print_sol (mlp->prob,  name);
  GNUNET_free (name);
# endif


  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Solve MLP problem\n");
  res = mlp_solve_mlp_problem (mlp, ctx);
  ctx->mlp_result = res;
  if (res != GNUNET_OK)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP Problem solving failed\n");
    mlp->semaphore = GNUNET_NO;
    return GNUNET_SYSERR;
  }
#if WRITE_MLP
  GNUNET_asprintf(&name, "problem_%i_mlp_solution", i);
  glp_print_mip (mlp->prob, name);
  GNUNET_free (name);
# endif

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Problem solved %s (LP duration %llu / MLP duration %llu)\n",
      (GNUNET_OK == res) ? "successfully" : "failed", ctx->lp_duration.rel_value, ctx->mlp_duration.rel_value);
  /* Process result */
  struct ATS_Peer *p = NULL;
  struct ATS_Address *a = NULL;
  struct MLP_information *mlpi = NULL;

  for (p = mlp->peer_head; p != NULL; p = p->next)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s'\n", GNUNET_i2s (&p->id));
    for (a = p->head; a != NULL; a = a->next)
    {
      double b = 0.0;
      double n = 0.0;

      mlpi = a->mlp_information;

      b = glp_mip_col_val(mlp->prob, mlpi->c_b);
      mlpi->b = b;

      n = glp_mip_col_val(mlp->prob, mlpi->c_n);
      if (n == 1.0)
        mlpi->n = GNUNET_YES;
      else
        mlpi->n = GNUNET_NO;

      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tAddress %s %f\n",
          (n == 1.0) ? "[x]" : "[ ]", b);
    }
  }

  if (mlp->mlp_task != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel(mlp->mlp_task);
    mlp->mlp_task = GNUNET_SCHEDULER_NO_TASK;
  }
  mlp->mlp_task = GNUNET_SCHEDULER_add_delayed (mlp->exec_interval, &mlp_scheduler, mlp);
  mlp->semaphore = GNUNET_NO;
  return res;
}
コード例 #5
0
ファイル: tp3.c プロジェクト: dennisman/L3
int main(int argc, char *argv[])
{	
	/* structures de données propres à GLPK */
	
	glp_prob *prob; // déclaration d'un pointeur sur le problème
	int ia[1 + NBCREUX];
	int ja[1 + NBCREUX];
	double ar[1 + NBCREUX]; // déclaration des 3 tableaux servant à définir la partie creuse de la matrice des contraintes
	int p[N+1];
	p[1] = 34;
	  p[2] = 6; p[3] = 8; p[4] = 17; p[5] = 16; p[6] = 5; p[7] = 13; p[8] = 21; p[9] = 25; p[10] = 31; p[11] = 14; p[12] = 13; p[13] = 33; p[14] = 9; p[15] = 25; p[16] = 25;

	/* variables récupérant les résultats de la résolution du problème (fonction objectif et valeur des variables) */

	int i,j,pos;
	double z;
	double x[NBVAR];
	
	/* Les déclarations suivantes sont optionnelles, leur but est de donner des noms aux variables et aux contraintes.
	   Cela permet de lire plus facilement le modèle saisi si on en demande un affichage à GLPK, ce qui est souvent utile pour détecter une erreur! */
	
	char nomcontr[NBCONTR][8]; /* ici, les contraintes seront nommées "caisse1", "caisse2",... */
	char numero[NBCONTR][3]; /* pour un nombre à deux chiffres */	
	char nomvar[NBVAR][3]; /* "xA", "xB", ... */
	
	/* Création d'un problème (initialement vide) */
	
	prob = glp_create_prob(); /* allocation mémoire pour le problème */ 
	glp_set_prob_name(prob, "wagons"); /* affectation d'un nom (on pourrait mettre NULL) */
	glp_set_obj_dir(prob, GLP_MIN); /* Il s'agit d'un problème de minimisation, on utiliserait la constante GLP_MAX dans le cas contraire */
	
	/* Déclaration du nombre de contraintes (nombre de lignes de la matrice des contraintes) : NBCONTR */
	
	glp_add_rows(prob, NBCONTR); 

	/* On commence par préciser les bornes sur les constrainte, les indices des contraintes commencent à 1 (!) dans GLPK */

	for(i = 1;i <= N;i++)
	{
		/* partie optionnelle : donner un nom aux contraintes */
		strcpy(nomcontr[i-1], "caisse");
		sprintf(numero[i-1], "%d", i);
		strcat(nomcontr[i-1], numero[i-1]); /* Les contraintes sont nommés "salle1", "salle2"... */		
		glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
		
		/* partie indispensable : les bornes sur les contraintes */
		glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0);
	}	
for(i = N+1;i <= NBCONTR;i++)
	{
	/* partie optionnelle : donner un nom aux contraintes */
		strcpy(nomcontr[i-1], "chaMax");
		sprintf(numero[i-1], "%d", i);
		strcat(nomcontr[i-1], numero[i-1]); /* Les contraintes sont nommés "chargemax", "chargemax2"... */		
		glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
		// il doit manquer un bout ici
		glp_set_row_bnds(prob, i, GLP_UP, 0.0, 0.0);
		//<=0
		// on met cmax a gauche car c'est une variable
		// il aura le coeff -1 dans la mat creuse
	}

	/* Déclaration du nombre de variables : NBVAR */
	
	glp_add_cols(prob, NBVAR); 
	
	/* On précise le type des variables, les indices commencent à 1 également pour les variables! */
	
	for(i = 1;i <= NBVAR;i++)
	{
		if(i==NBVAR){
			sprintf(nomvar[i-1],"Cm");
			glp_set_col_name(prob, i , nomvar[i-1]);
			glp_set_col_bnds(prob, i, GLP_LO, 0.0, 0.0);
		}else{
			/* partie optionnelle : donner un nom aux variables */
			sprintf(nomvar[i-1],"x%d",i-1);
			glp_set_col_name(prob, i , nomvar[i-1]); /* Les variables sont nommées "xA", "xB"... afin de respecter les noms de variables de l'exercice 2.2 */
		
			/* partie obligatoire : bornes éventuelles sur les variables, et type */
			glp_set_col_bnds(prob, i, GLP_DB, 0.0, 1.0); /* bornes sur les variables, comme sur les contraintes */
			glp_set_col_kind(prob, i, GLP_BV);	/* les variables sont par défaut continues, nous précisons ici qu'elles sont binaires avec la constante GLP_BV, on utiliserait GLP_IV pour des variables entières */	
		}
	} 

	/* définition des coefficients des variables dans la fonction objectif */

	for(i = 1;i <= N*M;i++) glp_set_obj_coef(prob,i,0.0); // Tous les coûts sont ici à 0! Mais on doit specifier quand meme
	glp_set_obj_coef(prob,N*M+1,1.0); // 1 fois cmax
	
	/* Définition des coefficients non-nuls dans la matrice des contraintes, autrement dit les coefficients de la matrice creuse */
	/* Les indices commencent également à 1 ! */



// pour i de 1 a n
//pour i de 1 a m
 /* xij intervient dans la ligne i avec un coeff 1 et dans la ligne 
 n+j avec un coeff pi
 
 ia -> i et n+j
 ar -> 1 et pi
 ja -> xij -> (i-1)*m+j
*/

	pos = 1;
	for(i=1; i<=N; i++){
		for(j=1; j<=M; j++){
			ia[pos] = i;
			ja[pos] = (i-1)*M+j;		ar[pos] = 1;
			pos++; 
			
			ia[pos] = N+j;
			ja[pos] = (i-1)*M+j;	ar[pos] = p[i];
			pos++;
		}
	}
	
//Cmax a -1 !!!
for(i=N+1; i<=N+M;i++){
	ia[pos] = i;
	ja[pos] = N*M+1;				ar[pos] = -1;
	pos++; 	
}
	

	
	/* chargement de la matrice dans le problème */
	
	glp_load_matrix(prob,NBCREUX,ia,ja,ar); 
	
	/* Optionnel : écriture de la modélisation dans un fichier (TRES utile pour debugger!) */

	glp_write_lp(prob,NULL,"wagons.lp");

	/* Résolution, puis lecture des résultats */
	
	glp_simplex(prob,NULL);	glp_intopt(prob,NULL); /* Résolution */
	z = glp_mip_obj_val(prob); /* Récupération de la valeur optimale. Dans le cas d'un problème en variables continues, l'appel est différent : z = glp_get_obj_val(prob); */
	for(i = 0;i < NBVAR; i++) x[i] = glp_mip_col_val(prob,i+1); /* Récupération de la valeur des variables, Appel différent dans le cas d'un problème en variables continues : for(i = 0;i < p.nbvar;i++) x[i] = glp_get_col_prim(prob,i+1); */

	printf("z = %lf\n",z);
	for(i = 0;i < NBVAR;i++) printf("x%d = %d, ",i,(int)(x[i] + 0.5)); /* un cast est ajouté, x[i] pourrait être égal à 0.99999... */ 
	puts("");

	/* libération mémoire */
	glp_delete_prob(prob); 

	/* J'adore qu'un plan se déroule sans accroc! */
	return 0;
}
コード例 #6
0
ファイル: glplpx01.c プロジェクト: BohanHsu/developer
int lpx_write_cpxlp(LPX *lp, const char *fname)
{     /* write problem data in CPLEX LP format */
      return glp_write_lp(lp, NULL, fname);
}
コード例 #7
0
ファイル: glplpx01.c プロジェクト: Erez-Buchnik/Bouma2
int lpx_print_prob(LPX *lp, const char *fname)
{     /* write problem data in plain text format */
      return glp_write_lp(lp, NULL, fname);
}
コード例 #8
0
ファイル: lp.c プロジェクト: danielriosgarza/pyglpk
static PyObject* LPX_write(LPXObject *self, PyObject *args, PyObject *keywds)
{
	static char* kwlist[] = {"mps", "freemps", "prob", "sol", "sens_bnds",
		"ips", "mip", NULL};
	char* fnames[] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL};
	char* fname;
	const char* err_msg = "writer for '%s' failed to write to '%s'";
	int rv;

	rv = PyArg_ParseTupleAndKeywords(args, keywds, "|sssssss", kwlist,
	fnames,fnames+1,fnames+2,fnames+3, fnames+4,fnames+5,fnames+6);

	if (!rv)
		return NULL;

	fname = fnames[0];
	if (fname != NULL) {
		rv = glp_write_mps(LP, GLP_MPS_DECK, NULL, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[0], fname);
			return NULL;
		}
	}

	fname = fnames[1];
	if (fname != NULL) {
		rv = glp_write_mps(LP, GLP_MPS_FILE, NULL, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[1], fname);
			return NULL;
		}
	}

	fname = fnames[2];
	if (fname != NULL) {
		rv = glp_write_lp(LP, NULL, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[2], fname);
			return NULL;
		}
	}

	fname = fnames[3];
	if (fname != NULL) {
		rv = glp_print_sol(LP, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[3], fname);
			return NULL;
		}
	}

	fname = fnames[4];
	if (fname != NULL) {
		if (glp_get_status(LP) == GLP_OPT && !glp_bf_exists(LP))
			glp_factorize(LP);
		rv = glp_print_ranges(LP, 0, NULL, 0, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[4], fname);
			return NULL;
		}
	}

	fname = fnames[5];
	if (fname != NULL) {
		rv = glp_print_ipt(LP, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[5], fname);
			return NULL;
		}
	}

	fname = fnames[6];
	if (fname != NULL) {
		glp_print_mip(LP, fname);
		if (rv != 0) {
			PyErr_Format(PyExc_RuntimeError, err_msg, kwlist[6], fname);
			return NULL;
		}
	}
	Py_RETURN_NONE;
}
コード例 #9
0
ファイル: ULS.c プロジェクト: Shakit/IP2015TP2
int main(int argc, char** argv)
{
	/*==================================================*/
	/* Variables */
	data d;
	int* M;

	/* GLPK */
	int *ia, *ja;
	double *ar;
	double z;
	double *x;
	int notZeroCount;

	/* Misc */
	int i, pos;

	/* Check up */
	if(argc != 2)
	{
		printf("ERROR : no data file !\n");
		exit(1);		
	}
	
	/* Initialization */
	filereader(argv[1], &d);

	if(d.nbjour < 1)
	{
		printf("Obvious...\n");
		return 0;	
	}
	
	M = (int*) malloc ((d.nbjour +1)* sizeof(int));
	M[d.nbjour] = d.d[d.nbjour];
	for (i = d.nbjour-1; i >=0; --i)
	{
		M[i] = d.d[i] + M[i+1];
	}

	/* Problem creation*/
	glp_prob *prob;
	prob = glp_create_prob();
	glp_set_prob_name(prob, "ULS");
	glp_set_obj_dir(prob, GLP_MIN);

	glp_smcp parm;
	glp_init_smcp(&parm);
	parm.msg_lev = GLP_MSG_OFF;

	glp_iocp parmip;
	glp_init_iocp(&parmip);
	parmip.msg_lev = GLP_MSG_OFF;

	/* Number of constraints : 2 * nbjour +2 */
	glp_add_rows(prob, 2*d.nbjour +2);
	for (i = 1; i <= d.nbjour; ++i)
	{
		glp_set_row_bnds(prob, i, GLP_FX, d.d[i], d.d[i]);
	}
	for (i = d.nbjour+1; i <= 2*d.nbjour; ++i)
	{
		glp_set_row_bnds(prob, i, GLP_LO, 0, 0);
	}	
	glp_set_row_bnds(prob, 2*d.nbjour+1, GLP_FX, 0.0, 0.0);
	glp_set_row_bnds(prob, 2*d.nbjour+2, GLP_FX, 0.0, 0.0);

	/* Number of variables : 3*(nbjour +1)*/
	glp_add_cols(prob, 3*(d.nbjour+1));
	for (i = 0; i < d.nbjour +1; ++i)
	{
		glp_set_col_bnds(prob, i*3 +1, GLP_LO, 0.0, 0.0);
		glp_set_col_bnds(prob, i*3 +2, GLP_LO, 0.0, 0.0);
		glp_set_col_bnds(prob, i*3 +3, GLP_DB, 0.0, 1.0);
	}
	for (i = 1; i <= 3*(d.nbjour+1); ++i)
	{
		glp_set_col_kind(prob, i, GLP_CV);
	}

	/* Coefficients of the economic function */
	glp_set_obj_coef(prob, 1, 0);
	glp_set_obj_coef(prob, 2, 0);
	glp_set_obj_coef(prob, 3, 0);
	for (i = 1; i <=d.nbjour; ++i)
	{
		glp_set_obj_coef(prob, 3*i+1, d.p[i]);
		glp_set_obj_coef(prob, 3*i+2, d.h[i]);
		glp_set_obj_coef(prob, 3*i+3, d.f[i]);
	}

	/* Matrix */
	notZeroCount = 5 * d.nbjour + 2;

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

	pos = 1;
	for (i = 1; i <= d.nbjour; ++i)
	{
		ia[pos] = i;
		ia[pos+1] = i;
		ia[pos+2] = i;

		ja[pos] = i*3-1;
		ja[pos+1] = i*3+1;
		ja[pos+2] = i*3+2;

		ar[pos] = 1.0;
		ar[pos+1] = 1.0;
		ar[pos+2] = -1.0;
			
		pos += 3;
	}

	for (i = 1; i <= d.nbjour; ++i)
	{
		ia[pos] = i + d.nbjour;
		ia[pos+1] = i + d.nbjour;

		ja[pos] = i*3+1;
		ja[pos+1] = i*3+3;

		ar[pos] = -1.0;
		ar[pos+1] = M[i];
			
		pos += 2;
	}
	
	ia[pos] = 2*d.nbjour +1;
	ia[pos+1] = 2 * d.nbjour+2;

	ja[pos] = 3*(d.nbjour+1)-1;
	ja[pos+1] = 2;

	ar[pos] = 1.0;
	ar[pos+1] = 1.0;

	pos += 2;

	glp_load_matrix(prob, notZeroCount, ia, ja , ar);

	/* Writing in a file */
	glp_write_lp(prob, NULL, "ULS.lp");

	/* Branch and bound */
	node* res = branchAndBound(prob);
	displayNode(res);
}
コード例 #10
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;
}
コード例 #11
0
ファイル: glpk.c プロジェクト: joshcc3/HaskellMiniProjects
int c_glp_write_lp(glp_prob *lp, const char * fname){
  	return glp_write_lp(lp, 0, fname);
}
コード例 #12
0
ファイル: glpapi17.c プロジェクト: phantomas1234/fbaproject
int glp_main(int argc, const char *argv[])
{     /* stand-alone LP/MIP solver */
      struct csa _csa, *csa = &_csa;
      int ret;
      xlong_t start;
      /* perform initialization */
      csa->prob = glp_create_prob();
      glp_get_bfcp(csa->prob, &csa->bfcp);
      glp_init_smcp(&csa->smcp);
      csa->smcp.presolve = GLP_ON;
      glp_init_iocp(&csa->iocp);
      csa->iocp.presolve = GLP_ON;
      csa->tran = NULL;
      csa->graph = NULL;
      csa->format = FMT_MPS_FILE;
      csa->in_file = NULL;
      csa->ndf = 0;
      csa->out_dpy = NULL;
      csa->solution = SOL_BASIC;
      csa->in_res = NULL;
      csa->dir = 0;
      csa->scale = 1;
      csa->out_sol = NULL;
      csa->out_res = NULL;
      csa->out_bnds = NULL;
      csa->check = 0;
      csa->new_name = NULL;
      csa->out_mps = NULL;
      csa->out_freemps = NULL;
      csa->out_cpxlp = NULL;
      csa->out_pb = NULL;
      csa->out_npb = NULL;
      csa->log_file = NULL;
      csa->crash = USE_ADV_BASIS;
      csa->exact = 0;
      csa->xcheck = 0;
      csa->nomip = 0;
      /* parse command-line parameters */
      ret = parse_cmdline(csa, argc, argv);
      if (ret < 0)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      if (ret > 0)
      {  ret = EXIT_FAILURE;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* remove all output files specified in the command line */
      if (csa->out_dpy != NULL) remove(csa->out_dpy);
      if (csa->out_sol != NULL) remove(csa->out_sol);
      if (csa->out_res != NULL) remove(csa->out_res);
      if (csa->out_bnds != NULL) remove(csa->out_bnds);
      if (csa->out_mps != NULL) remove(csa->out_mps);
      if (csa->out_freemps != NULL) remove(csa->out_freemps);
      if (csa->out_cpxlp != NULL) remove(csa->out_cpxlp);
      if (csa->out_pb != NULL) remove(csa->out_pb);
      if (csa->out_npb != NULL) remove(csa->out_npb);
      if (csa->log_file != NULL) remove(csa->log_file);
      /*--------------------------------------------------------------*/
      /* open log file, if required */
      if (csa->log_file != NULL)
      {  if (lib_open_log(csa->log_file))
         {  xprintf("Unable to create log file\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* read problem data from the input file */
      if (csa->in_file == NULL)
      {  xprintf("No input problem file specified; try %s --help\n",
            argv[0]);
         ret = EXIT_FAILURE;
         goto done;
      }
      if (csa->format == FMT_MPS_DECK)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->in_file);
         if (ret != 0)
err1:    {  xprintf("MPS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MPS_FILE)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->in_file);
         if (ret != 0) goto err1;
      }
      else if (csa->format == FMT_CPLEX_LP)
      {  ret = glp_read_lp(csa->prob, NULL, csa->in_file);
         if (ret != 0)
         {  xprintf("CPLEX LP file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MATHPROG)
      {  int k;
         /* allocate the translator workspace */
         csa->tran = glp_mpl_alloc_wksp();
         /* read model section and optional data section */
         if (glp_mpl_read_model(csa->tran, csa->in_file, csa->ndf > 0))
err2:    {  xprintf("MathProg model processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         /* read optional data section(s), if necessary */
         for (k = 1; k <= csa->ndf; k++)
         {  if (glp_mpl_read_data(csa->tran, csa->in_data[k]))
               goto err2;
         }
         /* generate the model */
         if (glp_mpl_generate(csa->tran, csa->out_dpy)) goto err2;
         /* build the problem instance from the model */
         glp_mpl_build_prob(csa->tran, csa->prob);
      }
      else if (csa->format == FMT_MIN_COST)
      {  csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_mincost(csa->graph, offsetof(v_data, rhs),
            offsetof(a_data, low), offsetof(a_data, cap),
            offsetof(a_data, cost), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_mincost_lp(csa->prob, csa->graph, GLP_ON,
            offsetof(v_data, rhs), offsetof(a_data, low),
            offsetof(a_data, cap), offsetof(a_data, cost));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else if (csa->format == FMT_MAX_FLOW)
      {  int s, t;
         csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_maxflow(csa->graph, &s, &t,
            offsetof(a_data, cap), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_maxflow_lp(csa->prob, csa->graph, GLP_ON, s, t,
            offsetof(a_data, cap));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* change problem name, if required */
      if (csa->new_name != NULL)
         glp_set_prob_name(csa->prob, csa->new_name);
      /* change optimization direction, if required */
      if (csa->dir != 0)
         glp_set_obj_dir(csa->prob, csa->dir);
      /* order rows and columns of the constraint matrix */
      lpx_order_matrix(csa->prob);
      /*--------------------------------------------------------------*/
      /* write problem data in fixed MPS format, if required */
      if (csa->out_mps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->out_mps);
         if (ret != 0)
         {  xprintf("Unable to write problem in fixed MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in free MPS format, if required */
      if (csa->out_freemps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->out_freemps);
         if (ret != 0)
         {  xprintf("Unable to write problem in free MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in CPLEX LP format, if required */
      if (csa->out_cpxlp != NULL)
      {  ret = glp_write_lp(csa->prob, NULL, csa->out_cpxlp);
         if (ret != 0)
         {  xprintf("Unable to write problem in CPLEX LP format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in OPB format, if required */
      if (csa->out_pb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_pb, 0, 0);
         if (ret != 0)
         {  xprintf("Unable to write problem in OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in normalized OPB format, if required */
      if (csa->out_npb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_npb, 1, 1);
         if (ret != 0)
         {  xprintf(
               "Unable to write problem in normalized OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* if only problem data check is required, skip computations */
      if (csa->check)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* determine the solution type */
      if (!csa->nomip &&
          glp_get_num_int(csa->prob) + glp_get_num_bin(csa->prob) > 0)
      {  if (csa->solution == SOL_INTERIOR)
         {  xprintf("Interior-point method is not able to solve MIP pro"
               "blem; use --simplex\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         csa->solution = SOL_INTEGER;
      }
      /*--------------------------------------------------------------*/
      /* if solution is provided, read it and skip computations */
      if (csa->in_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_read_sol(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_read_ipt(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_read_mip(csa->prob, csa->in_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to read problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         goto skip;
      }
      /*--------------------------------------------------------------*/
      /* scale the problem data, if required */
      if (csa->scale)
      {  if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
             csa->solution == SOL_INTERIOR ||
             csa->solution == SOL_INTEGER && !csa->iocp.presolve)
            glp_scale_prob(csa->prob, GLP_SF_AUTO);
      }
      /* construct starting LP basis */
      if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
          csa->solution == SOL_INTEGER && !csa->iocp.presolve)
      {  if (csa->crash == USE_STD_BASIS)
            glp_std_basis(csa->prob);
         else if (csa->crash == USE_ADV_BASIS)
            glp_adv_basis(csa->prob, 0);
         else if (csa->crash == USE_CPX_BASIS)
            glp_cpx_basis(csa->prob);
         else
            xassert(csa != csa);
      }
      /*--------------------------------------------------------------*/
      /* solve the problem */
      start = xtime();
      if (csa->solution == SOL_BASIC)
      {  if (!csa->exact)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
            if (csa->xcheck)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
                  xprintf("If you need to check final basis for non-opt"
                     "imal solution, use --nopresol\n");
               else
                  glp_exact(csa->prob, &csa->smcp);
            }
            if (csa->out_sol != NULL || csa->out_res != NULL)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
               xprintf("If you need actual output for non-optimal solut"
                  "ion, use --nopresol\n");
            }
         }
         else
            glp_exact(csa->prob, &csa->smcp);
      }
      else if (csa->solution == SOL_INTERIOR)
         glp_interior(csa->prob, NULL);
      else if (csa->solution == SOL_INTEGER)
      {  if (!csa->iocp.presolve)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
         }
         glp_intopt(csa->prob, &csa->iocp);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* display statistics */
      xprintf("Time used:   %.1f secs\n", xdifftime(xtime(), start));
      {  xlong_t tpeak;
         char buf[50];
         lib_mem_usage(NULL, NULL, NULL, &tpeak);
         xprintf("Memory used: %.1f Mb (%s bytes)\n",
            xltod(tpeak) / 1048576.0, xltoa(tpeak, buf));
      }
      /*--------------------------------------------------------------*/
skip: /* postsolve the model, if necessary */
      if (csa->tran != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_SOL);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_IPT);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_MIP);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Model postsolving error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* write problem solution in printable format, if required */
      if (csa->out_sol != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = lpx_print_sol(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTERIOR)
            ret = lpx_print_ips(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTEGER)
            ret = lpx_print_mip(csa->prob, csa->out_sol);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem solution in printable format, if required */
      if (csa->out_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_write_sol(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_write_ipt(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_write_mip(csa->prob, csa->out_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write sensitivity bounds information, if required */
      if (csa->out_bnds != NULL)
      {  if (csa->solution == SOL_BASIC)
         {  ret = lpx_print_sens_bnds(csa->prob, csa->out_bnds);
            if (ret != 0)
            {  xprintf("Unable to write sensitivity bounds information "
                  "\n");
               ret = EXIT_FAILURE;
               goto done;
            }
         }
         else
            xprintf("Cannot write sensitivity bounds information for in"
               "terior-point or MIP solution\n");
      }
      /*--------------------------------------------------------------*/
      /* all seems to be ok */
      ret = EXIT_SUCCESS;
      /*--------------------------------------------------------------*/
done: /* delete the LP/MIP problem object */
      if (csa->prob != NULL)
         glp_delete_prob(csa->prob);
      /* free the translator workspace, if necessary */
      if (csa->tran != NULL)
         glp_mpl_free_wksp(csa->tran);
      /* delete the network problem object, if necessary */
      if (csa->graph != NULL)
         glp_delete_graph(csa->graph);
      xassert(gmp_pool_count() == 0);
      gmp_free_mem();
      /* close log file, if necessary */
      if (csa->log_file != NULL) lib_close_log();
      /* check that no memory blocks are still allocated */
      {  int count;
         xlong_t total;
         lib_mem_usage(&count, NULL, &total, NULL);
         if (count != 0)
            xerror("Error: %d memory block(s) were lost\n", count);
         xassert(count == 0);
         xassert(total.lo == 0 && total.hi == 0);
      }
      /* free the library environment */
      lib_free_env();
      /* return to the control program */
      return ret;
}
コード例 #13
0
ファイル: glpk_wrapper.cpp プロジェクト: jadecastro/dreal3
int glpk_wrapper::print_to_file(const char *fname) {
    return glp_write_lp(lp, nullptr, fname);
}