bool CFeasibilityMap::SolveLP(Matrix &A, ColumnVector &b) {
  lprec *lp ;
  int n_row = A.nrows(); int n_col = A.ncols();
  lp = make_lp(0,n_col) ; 

  double *input_row = new double[1+n_col];
  for (int i_row=1; i_row<=n_row; i_row++){
      input_row[0] = 0 ;
      for (int j=1; j<=n_col; j++){
          input_row[j] = A(i_row,j) ;
      }
      add_constraint(lp, input_row, LE, b(i_row)) ;
  }
  delete [] input_row;
  
  double *input_obj = new double[1+n_col];    // The first zero is for matrix form
  input_obj[0] = 0 ;
  for (int j=1; j<=n_col; j++){
      input_obj[j] = 1 ;
  }
  set_obj_fn(lp, input_obj) ;
  delete [] input_obj;
  set_verbose(lp, IMPORTANT); // NEUTRAL (0), IMPORTANT (3), NORMAL (4), FULL (6)
  bool is_feasible = (solve(lp)==0); // 0: feasible solution found,  2: not found
		                                 // solution for minimizing objective function
	delete_lp(lp);

  return is_feasible;
}
Beispiel #2
0
int main( ) {
  double x[state_dim+1];
  double objective[state_dim+1] = {0, -2.5, -5.0, -3.4};
  double ieq_coeff[ieq_dim] = {425, 400, 600};
  double ieq_matrix[ieq_dim][state_dim+1]
    = {{0,2,10,4}, {0,6,5,8}, {0, 7, 10, 8}};
  double eq_coeff[eq_dim]; // = {30};
  double eq_matrix[eq_dim][state_dim+1];
  //
  lprec *lp;
  //
  lp = make_lp(eq_dim+ieq_dim, state_dim);
  set_obj_fn (lp, objective);
  for(int i=0; i<ieq_dim; i++) {
    add_constraint( lp, ieq_matrix[i], LE, ieq_coeff[i] );
  }
  for(int i=0; i<eq_dim; i++) {
    add_constraint( lp, eq_matrix[i], EQ, eq_coeff[i] );
  }
  //
  set_verbose(lp, 0);
  set_presolve(lp, PRESOLVE_ROWS | PRESOLVE_COLS | PRESOLVE_LINDEP, get_presolveloops(lp));
  solve(lp);
  //
  std::cout << "f : " << get_objective(lp) << std::endl;
  std::cout << "x :"  ;
  double col0 = get_Norig_columns(lp);
  double row0 = get_Norig_rows(lp);
  for(int i = 1; i <= col0; i++) {
    double _x = get_var_primalresult(lp, row0 + i);
    std::cout << " " << _x ;
  }
  std::cout << std::endl;
}
Beispiel #3
0
    void LP::setObjective(const bool maximize) {
        set_obj_fn(pimpl_->lp_.get(), pimpl_->conversionData());

        if (maximize)
            set_maxim(pimpl_->lp_.get());
        else
            set_minim(pimpl_->lp_.get());
        maximize_ = maximize;
    }
Beispiel #4
0
/* set the objective function (Row 0) of the matrix */
long __declspec(dllexport) WINAPI _set_obj_fn(lprec *lp, double *row)
 {
  long ret;

  if (lp != NULL) {
   freebuferror();
   ret = set_obj_fn(lp, row);
  }
  else
   ret = 0;
  return(ret);
 }
bool CFeasibilityMap::SolveLP(Matrix &A, ColumnVector &b, ColumnVector &x) {
  lprec *lp ;
  int n_row = A.nrows(); int n_col = A.ncols();
  x = ColumnVector(n_col); x = 0;
  lp = make_lp(0,n_col) ; 
  
  double *input_row = new double[1+n_col];
  for (int i_row=1; i_row<=n_row; i_row++){
      input_row[0] = 0 ; // The first zero is for matrix form
      for (int j=1; j<=n_col; j++){
          input_row[j] = A(i_row,j) ;
      }
      add_constraint(lp, input_row, LE, b(i_row)) ;
  }
  delete [] input_row;
  
  double *input_obj = new double[1+n_col];    // The first zero is for matrix form
  input_obj[0] = 0 ;
  for (int j=1; j<=n_col; j++){
      input_obj[j] = 1 ;
  }
  set_obj_fn(lp, input_obj) ;
  delete [] input_obj;
  set_verbose(lp, IMPORTANT); // NEUTRAL (0), IMPORTANT (3), NORMAL (4), FULL (6)
  bool is_feasible = (solve(lp)==0); // 0: feasible solution found,  2: not found
                                     // solution for minimizing objective function                               
  double* x_min = new double[n_col];
  double* x_max = new double[n_col];                      
  if (is_feasible) {
    get_variables(lp, x_min);
    set_maxim(lp);
    is_feasible = (solve(lp)==0); // 0: feasible solution found,  2: not found
    if (is_feasible) {
      get_variables(lp, x_max);
      for (int i = 0; i < n_col; i++) {
        x(i+1) = (x_min[i] + x_max[i]) / 2.0;
      }
    }
  }
  
  delete [] x_min;
  delete [] x_max;
                                     
  delete_lp(lp);
  return is_feasible;
}
/*
	Solve the LP subproblem by calling lp_solve API 
*/
int LLW_solve_lp(double **gradient, const struct TrainingCache *cache, const struct Model *model)
{
	long i,k,l,ind_pattern,y_i;
	const long Q = model->Q;
	const double Qd = (double)Q;
	const long chunk_size = cache->chunk_size;
	const double *C = model->C;
	
	const int nRows = Q-1; 
	const int nCols = chunk_size * Q;

	double *obj = (double*)malloc(sizeof(double) * (1+nCols));
	double *row = (double*)malloc(sizeof(double) * (1+nCols));
	double *rhs = (double*)malloc(sizeof(double) * Q);
	long **lp_sol_table = matrix_l(nCols, 2);
	long **lp_sol_table_inv = matrix_l(chunk_size, Q);
	double *sol = (double*)malloc(sizeof(double) * (1+nRows+nCols));
	double epsel;
		
	// Make LP
	lprec *lp = make_lp(0, nCols);
	set_add_rowmode(lp, TRUE);

	// Make objective function
	int col = 1;
	for(i=1; i<=chunk_size; i++)
	  {
	  ind_pattern = cache->table_chunk[i];
	  for(k=1; k<=Q; k++)
	      {
	      	obj[col] = gradient[ind_pattern][k];
		lp_sol_table[col][1] = i;	// keep a table of correspondance between
		lp_sol_table[col][2] = k;	// LPSOLVE vector of variables and lp_sol matrix
		lp_sol_table_inv[i][k] = col++; // lp_sol[i][k] = the 'lp_solve_table_inv[i][k]'-th variable for LPSOLVE
	      }
	  }
	set_obj_fn(lp, obj);


/*	// Make RHS of constraints
	// -- complete computation --
	for(k=1; k<Q; k++)
	  {
	  rhs[k] = 0.0;
	  for(i=1; i<=nb_data; i++)
	    if(cache->in_chunk[i] == 0)
	      {
	      for(l=1; l<=Q; l++)
		 rhs[k] += model->alpha[i][l];
	      rhs[k] -= Qd * model->alpha[i][k];
		
	      }
	  }
*/	  

	// Make RHS of constraints
	// -- updates to cache->rhs are made in compute_new_alpha()
	//    to keep track of rhs
	//    we only need to remove the contribution of the examples in the chunk
	for(k=1; k<Q; k++)
	  {
	  rhs[k] = cache->lp_rhs[k];
	  for(i=1; i<=chunk_size; i++)
	      {
	      ind_pattern = cache->table_chunk[i];
	      for(l=1; l<=Q; l++)
		 rhs[k] -= model->alpha[ind_pattern][l];
	      rhs[k] += Qd * model->alpha[ind_pattern][k];		
	      }
	  }
	
	
	// Make constraints
	for(k=1; k<Q; k++)
	  {
	  for(col = 1;col <=nCols; col++)
	     row[col] = 0.0;

	  for(i=1; i<=chunk_size; i++)
	    {
	    ind_pattern = cache->table_chunk[i];
	    y_i = model->y[ind_pattern];

            for(l=1; l<=Q; l++)
              if(l != y_i)
        	{
        	row[lp_sol_table_inv[i][l]] = -1.0;
        	if(l == k)
        	     row[lp_sol_table_inv[i][l]] += Qd;
		}
	    }

	  add_constraint(lp, row, EQ, rhs[k]);
	  }

	// Upper bound constraints: alpha <= Cy_i
	for(col=1;col<=nCols;col++)
		set_upbo(lp, col, C[model->y[cache->table_chunk[lp_sol_table[col][1]]]]);

	/*
	for(i=1; i<=chunk_size; i++) {
	  for(k=1; k<=Q; k++)
	    if(k != model->y[cache->table_chunk[i]]) {
	    	col = (int)lp_sol_table_inv[i][k];
		set_upbo(lp, col, C);
	    }
	}
	*/
	
	// End of LP making
	set_add_rowmode(lp, FALSE);	
	//print_lp(lp);
	
	// Solve LP
	int jump = false;
	set_outputfile(lp,"");

	if(solve(lp)) {
		printf("Problem with the LP... \n");
		jump = true;
	}
	else {
		// Recover solution in the matrix lp_sol
		get_primal_solution(lp, sol);	// sol: template for lp_solve solution format
						// 	sol=[obj, constraints, variables] 

		epsel = get_epsel(lp);	// tolerance in lp_solve
		
		// Put solution into lp_sol
		for(col=1; col<= nCols; col++) {

			// Check feasibility of the col-th variable
			if((sol[nRows+col] < -epsel) || (sol[nRows+col] > C[model->y[cache->table_chunk[lp_sol_table[col][1]]]] + epsel)) {
				jump = true;
				break;
			}
			// Round off tolerance
			if(fabs(sol[nRows+col]) < epsel) 
				sol[nRows+col] = 0.0;
				
			else if(fabs(sol[nRows+col] - C[model->y[cache->table_chunk[lp_sol_table[col][1]]]]) < epsel)
				sol[nRows+col] = C[model->y[cache->table_chunk[lp_sol_table[col][1]]]];
				
			// Set the value in lp_sol matrix
			cache->lp_sol[lp_sol_table[col][1]][lp_sol_table[col][2]] = sol[nRows+col];
		}
		
	}

	delete_lp(lp);

	free(obj);
	free(row);
	free(rhs);
	free(lp_sol_table[1]);free(lp_sol_table);
	free(lp_sol_table_inv[1]);free(lp_sol_table_inv);
	free(sol);

	return jump;	
}
Beispiel #7
0
int StateConstraints::fireVectorSize(const PetriNet& net,
									 const MarkVal* m0,
									 const VarVal*) const{
	assert(nPlaces == net.numberOfPlaces());
	assert(nVars == net.numberOfVariables());

	// Create linary problem
	lprec* lp;
	lp = make_lp(0, net.numberOfTransitions());	// One variable for each entry in the firing vector
	assert(lp);
	if(!lp) return false;

	// Set verbosity
	set_verbose(lp, IMPORTANT);

	// Set transition names (not strictly needed)
	for(size_t i = 0; i < net.numberOfTransitions(); i++)
		set_col_name(lp, i+1, const_cast<char*>(net.transitionNames()[i].c_str()));

	// Start adding rows
	set_add_rowmode(lp, TRUE);

	REAL row[net.numberOfTransitions() + 1];
	for(size_t p = 0; p < nPlaces; p++){
		// Set row zero
		memset(row, 0, sizeof(REAL) * net.numberOfTransitions() + 1);
		for(size_t t = 0; t < net.numberOfTransitions(); t++){
			int d = net.outArc(t, p) - net.inArc(p, t);
			row[1+t] = d;
		}

		if(pcs[p].min == pcs[p].max &&
		   pcs[p].max != CONSTRAINT_INFTY){
			double target = pcs[p].min - m0[p];
			add_constraint(lp, row, EQ,  target);
		}else{
			// There's always a min, even zero is interesting
			double target = pcs[p].min - m0[p];
			add_constraint(lp, row, GE,  target);
			if(pcs[p].max != CONSTRAINT_INFTY){
				double target = pcs[p].max - m0[p];
				add_constraint(lp, row, LE,  target);
			}
		}
	}

	// Finished adding rows
	set_add_rowmode(lp, FALSE);

	// Create objective
	memset(row, 0, sizeof(REAL) * net.numberOfTransitions() + 1);
	for(size_t t = 0; t < net.numberOfTransitions(); t++)
		row[1+t] = 1;	// The sum the components in the firing vector

	// Set objective
	set_obj_fn(lp, row);

	// Minimize the objective
	set_minim(lp);

	// Set variables as integer variables
	for(size_t i = 0; i < net.numberOfTransitions(); i++)
		set_int(lp, 1+i, TRUE);

	// Attempt to solve the problem
	int result = solve(lp);

	// Limit on traps to test
	size_t traplimit = nPlaces * OVER_APPROX_TRAP_FACTOR;
	// Try to add a minimal trap constraint
	while((result == OPTIMAL) && traplimit-- < 0){
		memset(row, 0, sizeof(REAL) * net.numberOfTransitions() + 1);
		// Get the firing vector
		get_variables(lp, row);
		// Compute the resulting marking
		MarkVal rMark[net.numberOfPlaces()];
		for(size_t p = 0; p < nPlaces; p++){
			rMark[p] = m0[p];
			for(size_t t = 0; t < net.numberOfTransitions(); t++)
				rMark[p] += (net.outArc(t, p) - net.inArc(p, t)) * (int)row[t];
		}

		// Find an M-trap
		BitField trap(minimalTrap(net, m0, rMark));

		//Break if there's no trap
		if(trap.none()) break;

		// Compute the new equation
		for(size_t t = 0; t < net.numberOfTransitions(); t++){
			row[1+t] = 0;
			for(size_t p = 0; p < nPlaces; p++)
				if(trap.test(p))
					row[1+t] += net.outArc(t, p) - net.inArc(p, t);
		}

		// Add a new row with target as greater than equal to 1
		set_add_rowmode(lp, TRUE);
		add_constraint(lp, row, GE,  1);
		set_add_rowmode(lp, FALSE);

		// Attempt to solve the again
		result = solve(lp);
	}

	int retval = 0;

	if(result != INFEASIBLE){
		get_variables(lp, row);
		for(size_t t = 0; t < net.numberOfTransitions(); t++)
			retval += (int)row[t];
	}

	// Delete the linear problem
	delete_lp(lp);
	lp = NULL;

	// Return true, if it was infeasible
	return retval;
}
Beispiel #8
0
int main ( int argv, char * argc[] )
{

# if defined ERROR
#  undef ERROR
# endif
# define ERROR() { fprintf(stderr, "Error\n"); exit(1); }
  lprec *lp;
  int majorversion, minorversion, release, build;

#if defined FORTIFY
  Fortify_EnterScope();
#endif

  lp_solve_version(&majorversion, &minorversion, &release, &build);
  printf("lp_solve %d.%d.%d.%d demo\n\n", majorversion, minorversion, release, build);
  printf("This demo will show most of the features of lp_solve %d.%d.%d.%d\n", majorversion, minorversion, release, build);
  press_ret();
  printf("\nWe start by creating a new problem with 4 variables and 0 constraints\n");
  printf("We use: lp=make_lp(0,4);\n");
  if ((lp = make_lp(0,4)) == NULL)
    ERROR();
  press_ret();

  printf("We can show the current problem with print_lp(lp)\n");
  print_lp(lp);
  press_ret();
  printf("Now we add some constraints\n");
  printf("add_constraint(lp, {0, 3, 2, 2, 1}, LE, 4)\n");
  {
    double row[] = {0, 3, 2, 2, 1};
    if (!add_constraint(lp, row, LE, 4))
      ERROR();
  }
  print_lp(lp);
  press_ret();
  printf("add_constraintex is now used to add a row. Only the npn-zero values must be specfied with this call.\n");
  printf("add_constraintex(lp, 3, {4, 3, 1}, {2, 3, 4}, GE, 3)\n");
  {
    int colno[] = {2, 3, 4};
    double row[] = {4, 3, 1};
    if (!add_constraintex(lp, sizeof(colno) / sizeof(*colno), row, colno, GE, 3))
      ERROR();
  }
  print_lp(lp);
  press_ret();
  printf("Set the objective function\n");
  printf("set_obj_fn(lp, {0, 2, 3, -2, 3})\n");
  {
    double row[] = {0, 2, 3, -2, 3};
    if (!set_obj_fn(lp, row))
      ERROR();
  }
  print_lp(lp);
  press_ret();
  printf("Now solve the problem with printf(solve(lp));\n");
  printf("%d",solve(lp));
  press_ret();
  printf("The value is 0, this means we found an optimal solution\n");
  printf("We can display this solution with print_objective(lp) and print_solution(lp)\n");
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);

  press_ret();
  printf("The dual variables of the solution are printed with\n");
  printf("print_duals(lp);\n");
  print_duals(lp);
  press_ret();
  printf("We can change a single element in the matrix with\n");
  printf("set_mat(lp,2,1,0.5)\n");
  if (!set_mat(lp,2,1,0.5))
    ERROR();
  print_lp(lp);
  press_ret();
  printf("If we want to maximize the objective function use set_maxim(lp);\n");
  set_maxim(lp);
  print_lp(lp);
  press_ret();
  printf("after solving this gives us:\n");
  solve(lp);
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  print_duals(lp);
  press_ret();
  printf("Change the value of a rhs element with set_rh(lp,1,7.45)\n");
  set_rh(lp,1,7.45);
  print_lp(lp);
  solve(lp);
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  press_ret();
  printf("We change %s to the integer type with\n", get_col_name(lp, 4));
  printf("set_int(lp, 4, TRUE)\n");
  set_int(lp, 4, TRUE);
  print_lp(lp);
  printf("We set branch & bound debugging on with set_debug(lp, TRUE)\n");
  set_debug(lp, TRUE);
  printf("and solve...\n");
  press_ret();
  solve(lp);
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  press_ret();
  printf("We can set bounds on the variables with\n");
  printf("set_lowbo(lp,2,2); & set_upbo(lp,4,5.3)\n");
  set_lowbo(lp,2,2);
  set_upbo(lp,4,5.3);
  print_lp(lp);
  press_ret();
  solve(lp);
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  press_ret();
  printf("Now remove a constraint with del_constraint(lp, 1)\n");
  del_constraint(lp,1);
  print_lp(lp);
  printf("Add an equality constraint\n");
  {
    double row[] = {0, 1, 2, 1, 4};
    if (!add_constraint(lp, row, EQ, 8))
      ERROR();
  }
  print_lp(lp);
  press_ret();
  printf("A column can be added with:\n");
  printf("add_column(lp,{3, 2, 2});\n");
  {
    double col[] = {3, 2, 2};
    if (!add_column(lp, col))
      ERROR();
  }
  print_lp(lp);
  press_ret();
  printf("A column can be removed with:\n");
  printf("del_column(lp,3);\n");
  del_column(lp,3);
  print_lp(lp);
  press_ret();
  printf("We can use automatic scaling with:\n");
  printf("set_scaling(lp, SCALE_MEAN);\n");
  set_scaling(lp, SCALE_MEAN);
  print_lp(lp);
  press_ret();
  printf("The function get_mat(lprec *lp, int row, int column) returns a single\n");
  printf("matrix element\n");
  printf("%s get_mat(lp,2,3), get_mat(lp,1,1); gives\n","printf(\"%f %f\\n\",");
  printf("%f %f\n", (double)get_mat(lp,2,3), (double)get_mat(lp,1,1));
  printf("Notice that get_mat returns the value of the original unscaled problem\n");
  press_ret();
  printf("If there are any integer type variables, then only the rows are scaled\n");
  printf("set_scaling(lp, SCALE_MEAN);\n");
  set_scaling(lp, SCALE_MEAN);
  printf("set_int(lp,3,FALSE);\n");
  set_int(lp,3,FALSE);
  print_lp(lp);
  press_ret();
  solve(lp);
  printf("print_objective, print_solution gives the solution to the original problem\n");
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  press_ret();
  printf("Scaling is turned off with unscale(lp);\n");
  unscale(lp);
  print_lp(lp);
  press_ret();
  printf("Now turn B&B debugging off and simplex tracing on with\n");
  printf("set_debug(lp, FALSE), set_trace(lp, TRUE) and solve(lp)\n");
  set_debug(lp, FALSE);
  set_trace(lp, TRUE);
  press_ret();
  solve(lp);
  printf("Where possible, lp_solve will start at the last found basis\n");
  printf("We can reset the problem to the initial basis with\n");
  printf("default_basis(lp). Now solve it again...\n");
  press_ret();
  default_basis(lp);
  solve(lp);

  printf("It is possible to give variables and constraints names\n");
  printf("set_row_name(lp,1,\"speed\"); & set_col_name(lp,2,\"money\")\n");
  if (!set_row_name(lp,1,"speed"))
    ERROR();
  if (!set_col_name(lp,2,"money"))
    ERROR();
  print_lp(lp);
  printf("As you can see, all column and rows are assigned default names\n");
  printf("If a column or constraint is deleted, the names shift place also:\n");
  press_ret();
  printf("del_column(lp,1);\n");
  del_column(lp,1);
  print_lp(lp);
  press_ret();

  write_lp(lp, "lp.lp");

  delete_lp(lp);

  printf("An lp structure can be created and read from a .lp file\n");
  printf("lp = read_lp(\"lp.lp\", TRUE);\n");
  printf("The verbose option is used\n");
  if ((lp = read_LP("lp.lp", TRUE, "test")) == NULL)
    ERROR();
  press_ret();
  printf("lp is now:\n");
  print_lp(lp);

  press_ret();
  printf("solution:\n");
  set_debug(lp, TRUE);
  solve(lp);
  set_debug(lp, FALSE);
  print_objective(lp);
  print_solution(lp, 1);
  print_constraints(lp, 1);
  press_ret();

  delete_lp(lp);

#if defined FORTIFY
  Fortify_LeaveScope();
#endif

    return 0;
}
void CLPLpsolve::setFunction(CLPFunction* function)
{
	m_status = 0;

	m_lpFunction = function;
	const int nVars = function->getNumCoefficients();

	// Creates an empty problem with getNumCoefficients variables
	m_env = make_lp(0, nVars);

	if(m_env == NULL)
	{	
		m_status = 1;
	}

	//if(!set_add_rowmode(m_env, FALSE))
	//{
	//	m_status = 1;
	//}
	
	//Allowing memory for rows
	//int * colno = new int[nVars];
    REAL * row= new REAL[nVars + 1];

	//set variables names
	for (int i = 0; i < nVars; ++i)
	{
		int lpIndex = i + 1;
		row[lpIndex] = function->getCoefficients().at(i);
		//colno[i] = lpIndex;

		

		//Determines the type
		switch(function->getIntegers().at(i)) {
			case 'C' :
				m_status = set_unbounded(m_env, lpIndex);
				break;

			case 'B' :
				m_status = set_binary(m_env, lpIndex, TRUE);
				break;

			case 'I' :
				m_status = set_int(m_env, lpIndex, TRUE);
				break;

			case 'S' :
				m_status = set_semicont(m_env, lpIndex, TRUE);
				break;

			default:
				assert(false);
				break;
		}
		
		//Sets upper bound and lower bound
		set_upbo(m_env, lpIndex, function->getUpperBounds().at(i));
		set_lowbo(m_env, lpIndex, function->getLowerBounds().at(i));
		set_col_name(m_env, lpIndex, const_cast<char*>(function->getVarNames().at(i).c_str()));

	}

	//set_obj_fnex(m_env, nVars, row, colno); 
	set_obj_fn(m_env, row);

	// Set the type of the problem (Min or Max)
	switch (function->getType()) {
	case lpMinFunction:
		set_minim(m_env);
		break;

	case lpMaxFunction:
		set_maxim(m_env);
		break;
	}

	if(!set_add_rowmode(m_env, TRUE))
	{
		m_status = 1;
	}
	
	delete [] row;

}