bool placement_problem::is_solution_correct(std::vector<point> const pos) const{
    /*
    for(int i=0; i<cells.size(); ++i){
        if(pos[i].x % cells[i].x_pitch != 0) return false;
        if(pos[i].y % cells[i].y_pitch != 0) return false;
    }
    */
    /*for(int i=0; i<cells.size(); ++i){
        rect const & cur = position_constraints[i];
        if(cur.xmin > cur.xmax or cur.xmin > pos[i].x or cur.xmax < pos[i].x) return false;
        if(cur.ymin > cur.ymax or cur.ymin > pos[i].y or cur.ymax < pos[i].y) return false;
    }*/
    if(not is_feasible()) return false;

    for(rect const R : fixed_elts){
        for(int i=0; i<cells.size(); ++i){
            if(pos[i].x + cells[i].width  > R.xmin
           and pos[i].y + cells[i].height > R.ymin
           and R.xmax  > pos[i].x
           and R.ymax  > pos[i].y) return false;
        }
    }
    
    // TODO: Should use a line sweep to verify that there is no overlap
    for(int i=0; i+1<cells.size(); ++i){
        for(int j=i+1; j<cells.size(); ++j){
            if(pos[i].x + cells[i].width  > pos[j].x
           and pos[j].x + cells[j].width  > pos[i].x
           and pos[i].y + cells[i].height > pos[j].y
           and pos[j].y + cells[j].height > pos[i].y) return false;
        }
    }
    
    return true;
}
Example #2
0
/* print all 0-1 solutions to the lp into the outstream */
void print_bin_solutions_lp(LinearProgram* lp) {
    num_t* configuration = allocate(lp->cols, sizeof(*configuration));
    unsigned long count = 1UL << lp->cols;
    unsigned int feasible_solutions = 0;

    print_matrix(lp);
    printf("\n");

    clock_t start = clock();

    unsigned int i;
    for (i = 0; i < count; i++) {
        if (is_feasible(configuration, lp)) {
            __print_config(configuration, lp->cols);
            feasible_solutions++;
        }
        next_configuration(configuration, lp->cols);
    }

    double elapsed = GET_SEC(start, clock());
    printf("Checked %lu vectors in %.3f s = %.3f kvecs/s\n",
            count, elapsed, (double) count / elapsed / 1000.0);

    deallocate(configuration);
    printf("found %u feasible solutions\n", feasible_solutions);
}
Example #3
0
File: windll.c Project: ks6g10/CA
/* returns TRUE if the vector in values is a feasible solution to the lp */
long __declspec(dllexport) WINAPI _is_feasible(lprec *lp, double *values)
 {
  long ret;

  if (lp != NULL) {
   freebuferror();
   ret = is_feasible(lp, values);
  }
  else
   ret = FALSE;
  return(ret);
 }
void n_queens_helper (int n, int k, 
        std::vector<std::vector<int>>& res,
        std::vector<int>& rows) {

    if (n == k) {
        res.emplace_back(rows);
        return;
    }
    for (int i = 0; i < n; ++i) {
        if (is_feasible(i, k, rows)) {
            rows[k] = i;
            n_queens_helper(n, k+1, res, rows);
            rows[k] = -1;
        }
    }


}
/* the optimization loop */
int main(int argc, char **argv) {
  cmaes_t evo; /* an CMA-ES type struct or "object" */
  double *arFunvals,  *xfinal, *const*pop;
  int i,j;
  int numberDipoles;
  int id;  //Rank
  int p;  //Number processors
  double elapsed_time;//Time from beginning.
  double bestValue;
  int lambda;
  int maxLambda;
  int * sendCnts; //For MPI_Alltoallv for arFunVals
  int * sdispls;  //For MPI_Alltoallv for arFunVals
  int * recvCnts; //For MPI_Alltoallv for arFunVals
  int * rdispls; //For MPI_Alltoallv for arFunVals
  int * sendCntsPop; //For MPI_Alltoallv for pop
  int * sdisplsPop; //For MPI_Alltoallv for pop
  int * recvCntsPop; //For MPI_Alltoallv for pop
  int * rdisplsPop; //For MPI_Alltoallv for pop
  int canTerminate;
  int canTerminateBuffer;

  //Start MPI
  MPI_Init(&argc, &argv);
  MPI_Barrier(MPI_COMM_WORLD);
  elapsed_time = -MPI_Wtime(); //Set initial time.

  MPI_Comm_rank(MPI_COMM_WORLD, &id); //Set id
  MPI_Comm_size(MPI_COMM_WORLD, &p); //set p



  for (i=0;i<32;i++)
  {
    observations[i]/=1000.0;
  }

  //Set number of dipoles, either first argument or default value of 2.
  numberDipoles=2; 
  if (argc>=2)
  {
    numberDipoles=atoi(argv[1]);
  }

  //Set lambda based on entry, default of 40
  maxLambda=40;
  if (argc>=3)
  {
    maxLambda=atoi(argv[2]);
  }

  if (id==0)
  {
    printf("Dipoles:%d MaxLambda:%d\n",numberDipoles,maxLambda);
  }

  //Allocate lambda pieces to each processor, based on the size of maxLambda and the number of processors.
  lambda = BLOCK_SIZE(id,p,maxLambda);

  printf("Id:%d Lambda:%d\n",id,lambda);

  //Setup send and receive buffers for function evaluations and populations that resulted in those evaluation.
  sendCnts = malloc(p*sizeof(int));
  sdispls = malloc(p*sizeof(int));
  recvCnts = malloc(p*sizeof(int));
  rdispls = malloc(p*sizeof(int));
  sendCntsPop = malloc(p*sizeof(int));
  sdisplsPop = malloc(p*sizeof(int));
  recvCntsPop = malloc(p*sizeof(int));
  rdisplsPop = malloc(p*sizeof(int));

  for (i=0;i<p;i++)
  {

    sendCnts[i]=lambda;//Same for all others
    sdispls[i] = BLOCK_LOW(id,p,maxLambda);//Same for all others
    recvCnts[i] = BLOCK_SIZE(i,p,maxLambda);//Depends on which we receive from.
    rdispls[i] = BLOCK_LOW(i,p,maxLambda);

    sendCntsPop[i]=lambda*((numberDipoles*6+2));//Same for all others
    sdisplsPop[i] = BLOCK_LOW(id,p,maxLambda)*(numberDipoles*6+2);//Same for all others
    recvCntsPop[i] = BLOCK_SIZE(i,p,maxLambda)*(numberDipoles*6+2);//Depends on which we receive from.
    rdisplsPop[i] = BLOCK_LOW(i,p,maxLambda)*(numberDipoles*6+2);

  }

  for (i=0;i<p;i++)
  {

    printf("Id: %d recvCnts[%d]=%d\n",id,i,recvCnts[i]);
    printf("Id: %d rdispls[%d]=%d\n",id,i,rdispls[i]);

    printf("Id: %d recvCntsPop[%d]=%d\n",id,i,recvCntsPop[i]);
    printf("Id: %d rdisplsPop[%d]=%d\n",id,i,rdisplsPop[i]);

  }
  





  /* Initialize everything into the struct evo, 0 means default */
  //arFunvals = cmaes_init(&evo, 0, NULL, NULL, 0, 0, "initials.par"); 

//  printf("0\n");
  
  //The maxLambda parameter has been added so all of them will have enough space to store the results
  arFunvals = reinit(&evo, maxLambda, numberDipoles);

  //outputCMAES_t(evo,1);

//  printf("1\n");

  resetSignals(&evo, numberDipoles);  /* write header and initial values */

  //Reset the seed value based on processor (so they don't all come out the same!
  evo.sp.seed=evo.sp.seed*(id+1)/p;
  printf("proc: %d seed: %d\n",id,evo.sp.seed);


  //outputCMAES_t(evo,0);

//  printf("2\n");

//  printf("%s\n", cmaes_SayHello(&evo));
//  i=40;

//  for (i=32;i<40;i*=2)
//  { 

//    arFunvals = reinit(&evo, i);
    //outputCMAES_t(evo);


  evo.sp.lambda=lambda;
  canTerminate = (0==1);
  /* Iterate until stop criterion holds */
  while(!canTerminate)
    { 
      /* generate lambda new search points, sample population */
      pop = cmaes_SamplePopulation(&evo); /* do not change content of pop */

      /* Here you may resample each solution point pop[i] until it
	 becomes feasible, e.g. for box constraints (variable
	 boundaries). function is_feasible(...) needs to be
	 user-defined.  
	 Assumptions: the feasible domain is convex, the optimum is
	 not on (or very close to) the domain boundary, initialX is
	 feasible and initialStandardDeviations are sufficiently small
	 to prevent quasi-infinite looping.
      */
      /*for (i = 0; i < lambda; ++i) 
      {
          cmaes_ReSampleSingle(&evo, i); 
      }*/
      for (i = 0; i < lambda; ++i) 
      {
	   while (!is_feasible(evo.rgrgx[i],(int) cmaes_Get(&evo, "dim"))) 
	   {
             cmaes_ReSampleSingle(&evo, i); 
           }
      }

      for (i=0;i<lambda;i++)
      {
         for(j=0;j<(6*numberDipoles)+2;j++)
         {
	   evo.rgrgx[BLOCK_LOW(id,p,maxLambda)+i][j]=evo.rgrgx[i][j];
         }
      }
 
      /* evaluate the new search points using fitfun from above */ 
      for (i = BLOCK_LOW(id,p,maxLambda); i <= BLOCK_HIGH(id,p,maxLambda); ++i) {
	arFunvals[i] = fitfun(evo.rgrgx[i], (int) cmaes_Get(&evo, "dim"));
        //printf("ID:%d, arFunvals[%d]=%lf\n",id,i,arFunvals[i]);
      }

      



      //Now communicate the arFunvals around
      MPI_Alltoallv(arFunvals,sendCnts,sdispls,MPI_DOUBLE,arFunvals,recvCnts,rdispls,MPI_DOUBLE,MPI_COMM_WORLD);


      //Now communicate the populations being looked at around
      MPI_Alltoallv(&evo.rgrgx[0][0],sendCntsPop,sdisplsPop,MPI_DOUBLE,&evo.rgrgx[0][0],recvCntsPop,rdisplsPop,MPI_DOUBLE,MPI_COMM_WORLD);


      /* update the search distribution used for cmaes_SampleDistribution() */
      cmaes_UpdateDistribution(&evo, arFunvals);  


      //Test for any that can terminate.
      canTerminate = cmaes_TestForTermination(&evo);
      if (canTerminate)
      {
	printf("id:%d can terminate for reason:%s\n",id,cmaes_TestForTermination(&evo));
      }
      MPI_Allreduce(&canTerminate,&canTerminateBuffer,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);//Get the max, if any are >0, then someone has terminated.
      canTerminate = canTerminateBuffer;//Reset so the loop will exit.

      /* read instructions for printing output or changing termination conditions */ 
//      cmaes_ReadSignals(&evo, "signals.par");   
//      fflush(stdout); /* useful in MinGW */
    }
//  printf("Stop:\n%s\n",  cmaes_TestForTermination(&evo)); /* print termination reason */

//  cmaes_WriteToFile(&evo, "all", "allcmaes.dat");         /* write final results */


  elapsed_time += MPI_Wtime();



  /* get best estimator for the optimum, xmean */
  xfinal = cmaes_GetNew(&evo, "xmean"); /* "xbestever" might be used as well */
  bestValue = fitfun(xfinal, (int) cmaes_Get(&evo, "dim"));
  printf("Proccesor:%d has last mean of:%lf elapsedTime:%lf\n",id,bestValue,elapsed_time);
  for (i=0;i<6*numberDipoles;i++)
  {
    printf("(%d:%d:%lf)\n",id,i,xfinal[i]);
  }

//  cmaes_exit(&evo); /* release memory */ 
  /* do something with final solution and finally release memory */
  free(xfinal); 
  free(sendCnts);
  free(sdispls);
  free(recvCnts);
  free(rdispls);
  free(sendCntsPop);
  free(sdisplsPop);
  free(recvCntsPop);
  free(rdisplsPop);

  MPI_Finalize();

//}

  return 0;
}
Example #6
0
/* the optimization loop */
int main(int argn, char **args) {
  cmaes_t evo; /* an CMA-ES type struct or "object" */
  boundary_transformation_t boundaries;
  double *arFunvals, *x_in_bounds, *const*pop;
  double lowerBounds[] = {1.0, DBL_MAX / -1e2}; /* last number is recycled for all remaining coordinates */
  double upperBounds[] = {3, 2e22};
  int nb_bounds = 1; /* numbers used from lower and upperBounds */
  unsigned long dimension;
  int i; 

  /* initialize boundaries, be sure that initialSigma is smaller than upper minus lower bound */
  boundary_transformation_init(&boundaries, lowerBounds, upperBounds, nb_bounds);
  /* Initialize everything into the struct evo, 0 means default */
  arFunvals = cmaes_init(&evo, 0, NULL, NULL, 0, 0, "cmaes_initials.par");
  dimension = (unsigned long)cmaes_Get(&evo, "dimension");

  printf("%s\n", cmaes_SayHello(&evo));

  x_in_bounds = cmaes_NewDouble(dimension); /* calloc another vector */
  cmaes_ReadSignals(&evo, "cmaes_signals.par");  /* write header and initial values */

  /* Iterate until stop criterion holds */
  while(!cmaes_TestForTermination(&evo))
    { 
      /* generate lambda new search points, sample population */
      pop = cmaes_SamplePopulation(&evo); /* do not change content of pop */

      /* transform into bounds and evaluate the new search points */
      for (i = 0; i < cmaes_Get(&evo, "lambda"); ++i) {
        boundary_transformation(&boundaries, pop[i], x_in_bounds, dimension);
        /* this loop can be omitted if is_feasible is invariably true */
        while(!is_feasible(x_in_bounds, dimension)) { /* is_feasible needs to be user-defined, in case, and can change/repair x */
            cmaes_ReSampleSingle(&evo, i); 
            boundary_transformation(&boundaries, pop[i], x_in_bounds, dimension);
        }
        arFunvals[i] = fitfun(x_in_bounds, dimension); /* evaluate */
      }

      /* update the search distribution used for cmaes_SampleDistribution() */
      cmaes_UpdateDistribution(&evo, arFunvals);  /* assumes that pop[i] has not been modified */

      /* read instructions for printing output or changing termination conditions */ 
      cmaes_ReadSignals(&evo, "cmaes_signals.par");
      fflush(stdout); /* useful in MinGW */
    }
  printf("Stop:\n%s\n",  cmaes_TestForTermination(&evo)); /* print termination reason */
  cmaes_WriteToFile(&evo, "all", "allcmaes.dat");         /* write final results */

  /* get best estimator for the optimum, xmean */
  boundary_transformation(&boundaries,
		  (double const *) cmaes_GetPtr(&evo, "xmean"), /* "xbestever" might be used as well */
		  x_in_bounds, dimension);

  /* do something with final solution x_in_bounds */

  /* ... */

  /* and finally release memory */
  cmaes_exit(&evo); /* release memory */
  boundary_transformation_exit(&boundaries); /* release memory */
  free(x_in_bounds);

  return 0;
}
Example #7
0
path_searcht::resultt path_searcht::operator()(
  const goto_functionst &goto_functions)
{
  locst locs(ns);
  var_mapt var_map(ns);
  
  locs.build(goto_functions);

  // this is the container for the history-forest  
  path_symex_historyt history;
  
  queue.push_back(initial_state(var_map, locs, history));
  
  // set up the statistics
  number_of_dropped_states=0;
  number_of_paths=0;
  number_of_VCCs=0;
  number_of_steps=0;
  number_of_feasible_paths=0;
  number_of_infeasible_paths=0;
  number_of_VCCs_after_simplification=0;
  number_of_failed_properties=0;
  number_of_locs=locs.size();

  // stop the time
  start_time=current_time();
  
  initialize_property_map(goto_functions);
  
  while(!queue.empty())
  {
    number_of_steps++;
  
    // Pick a state from the queue,
    // according to some heuristic.
    // The state moves to the head of the queue.
    pick_state();
    
    // move into temporary queue
    queuet tmp_queue;
    tmp_queue.splice(
      tmp_queue.begin(), queue, queue.begin(), ++queue.begin());
    
    try
    {
      statet &state=tmp_queue.front();
      
      // record we have seen it
      loc_data[state.get_pc().loc_number].visited=true;

      debug() << "Loc: #" << state.get_pc().loc_number
              << ", queue: " << queue.size()
              << ", depth: " << state.get_depth();
      for(const auto & s : queue)
        debug() << ' ' << s.get_depth();
        
      debug() << eom;
    
      if(drop_state(state))
      {
        number_of_dropped_states++;
        number_of_paths++;
        continue;
      }
      
      if(!state.is_executable())
      {
        number_of_paths++;
        continue;
      }

      if(eager_infeasibility &&
         state.last_was_branch() &&
         !is_feasible(state))
      {
        number_of_infeasible_paths++;
        number_of_paths++;
        continue;
      }
      
      if(number_of_steps%1000==0)
      {
        status() << "Queue " << queue.size()
                 << " thread " << state.get_current_thread()
                 << '/' << state.threads.size()
                 << " PC " << state.pc() << messaget::eom;
      }

      // an error, possibly?
      if(state.get_instruction()->is_assert())
      {
        if(show_vcc)
          do_show_vcc(state);
        else
        {
          check_assertion(state);
          
          // all assertions failed?
          if(number_of_failed_properties==property_map.size())
            break;
        }
      }

      // execute
      path_symex(state, tmp_queue);
      
      // put at head of main queue
      queue.splice(queue.begin(), tmp_queue);
    }
    catch(const std::string &e)
    {
      error() << e << eom;
      number_of_dropped_states++;
    }
    catch(const char *e)
    {
      error() << e << eom;
      number_of_dropped_states++;
    }
    catch(int)
    {
      number_of_dropped_states++;
    }
  }
  
  report_statistics();
  
  return number_of_failed_properties==0?SAFE:UNSAFE;
}
Example #8
0
// Main algorithm.
void MOGA::compute()
{
	if ( num_bits_ == 0 ) return;

	double p;

	// Build initial population.
	initialization();

	// Do generations.
	for ( int i = 0; i < num_generations_; ++i )
	{
		while ( (int)population_.size() < 2 * num_individuals_ )
		{
			// Select a pair of individuals.
			std::pair<int, int> s( selection() );

			p = (double)std::rand() / (double)RAND_MAX;
			if ( p <= Pc_ )
			{
				// Cross them.
				std::pair<individual, individual> children(
					crossover( population_[s.first], population_[s.second] ) );

				p = (double)std::rand() / (double)RAND_MAX;
				if ( p <= Pm_ )
				{
					// Mutate children.
					mutation( children.first );
					mutation( children.second );
				}

				// Repair children.
				repair( children.first );
				repair( children.second );

				population_.push_back( children.first );
				population_.push_back( children.second );
			}
			else
			{
				population_.push_back( population_[s.first] );
				population_.push_back( population_[s.second] );
			}
		}

		// Keep the best individuals.
		elitism();
		print();
	}

	// LOCAL SEARCH
	solutions_.clear();
	if ( Argument::local_search )
	{
		LocalSearch local( data_, cust_, fac_ );
		local.pipe_fp_ = pipe_fp_;

		for ( unsigned int i = 0; i < population_.size(); ++i )
		{
			local.search( population_[i] );
			solutions_.merge( local.solutions_ );
		}
	}

	// FINISHED - KEEP BEST VALUES

	// Keep only "first rank" solutions.
	for ( unsigned int i = 0; i < population_.size(); ++i )
	{
#if STRICT_CHECK
		if ( population_[i].rank == 1 && is_feasible( population_[i] ) && population_[i].is_feasible() )
#else
		if ( population_[i].rank == 1 && population_[i].is_feasible() )
#endif
		{
#if STRICT_CHECK
			// Check objective
			is_valid( population_[i] );
#endif

			Solution sol( getNbObjective() );
			for ( int k = 0; k < getNbObjective(); ++k )
			{
				sol.setObj( k, population_[i].obj[k] );
			}
			solutions_.push_back( sol );
		}
	}
}
int placement_problem::get_cost() const{
    int ret = x_flow.get_cost() + y_flow.get_cost();
    if(is_feasible())
        assert(get_solution_cost(get_positions()) == ret);
    return ret;
}
Example #10
0
bool placement_problem::operator<(placement_problem const & o) const{
    if(is_feasible() and o.is_feasible()) return get_cost() < o.get_cost();
    else return (not is_feasible()) and o.is_feasible(); // Unfeasible first
}