Пример #1
0
void DataPoint::lowpassFilter(std::vector<DataPoint>& output, std::vector<DataPoint>& frame, unsigned maxNumRows, unsigned numRowBins)
{
	// Sanity check
	if (frame.empty())
	{
		return;
	}

	// No binning can occur, so copy
	if (numRowBins >= maxNumRows)
	{
		output.insert(output.end(), frame.begin(), frame.end());
		return;
	}

	// Sort by image row
	std::sort(frame.begin(), frame.end(), SortRecordByRow);

	unsigned binSize = maxNumRows / numRowBins;

	// Holds the current contents of the bin
	std::vector<DataPoint> bin;
	unsigned nextBinY = frame.front().pixel.y + binSize;

	// unsigned bin = frame.front().pixel.y / numRowBins;
	for (size_t iFr = 0; iFr < frame.size(); iFr++)
	{
		DataPoint& record = frame[iFr];

		if (record.pixel.y < nextBinY)
		{
			bin.push_back(record);
		}
		else
		{
			// Average the bin results and add it to the output
			if (!bin.empty())
			{
				DataPoint out;
				computeAverage(bin, out);

				output.push_back(out);
				bin.clear();
			}

			nextBinY = record.pixel.y + binSize;
			bin.push_back(record);
		}
	}

	// Process any results still left in the bin
	if (!bin.empty())
	{
		DataPoint out;
		computeAverage(bin, out);

		output.push_back(out);
		bin.clear();
	}
}
size_t AveragingAllocationStrategy::operator()(const size_t curBufferSize,
                                               const size_t increaseAmt)
{
   // The amount of memory to allocate is the larger of the requested size and
   // the average size computed from previous allocations.
   const size_t alloc_size(maxValue(curBufferSize + increaseAmt,
                                    computeAverage()));

   // Record the current amount allocated for future computations of the
   // average allocation amount. We accomplish this by first populating
   // mAllocSizes until its size equals mWindowSize. After that, we just
   // assign to the entry identified by mIndex.
   if ( mAllocSizes.size() < mWindowSize )
   {
      mAllocSizes.push_back(alloc_size);
   }
   else
   {
      mAllocSizes[mIndex] = alloc_size;
   }

   mIndex = (mIndex + 1) % mWindowSize;

   return alloc_size;
}
Пример #3
0
void Refiner::Refine(int count, BaseLB::LDStats* stats, 
		     int* cur_p, int* new_p)
{
  //  CkPrintf("[%d] Refiner strategy\n",CkMyPe());

  P = count;
  numComputes = stats->n_objs;
  computes = new computeInfo[numComputes];
  processors = new processorInfo[count];

  create(count, stats, cur_p);

  int i;
  for (i=0; i<numComputes; i++)
    assign((computeInfo *) &(computes[i]),
           (processorInfo *) &(processors[computes[i].oldProcessor]));

  removeComputes();

  computeAverage();

  if (_lb_args.debug()>2)  {
    CkPrintf("Old PE load (bg load): ");
    for (i=0; i<count; i++) CkPrintf("%d:%f(%f) ", i, processors[i].load, processors[i].backgroundLoad);
    CkPrintf("\n");
  }

  // Perform multi refine but reset it to the original state before changing the
  // refinement load balancing threshold.
  multirefine(true);

  int nmoves = 0;
  for (int pe=0; pe < P; pe++) {
    Iterator nextCompute;
    nextCompute.id = 0;
    computeInfo *c = (computeInfo *)
      processors[pe].computeSet->iterator((Iterator *)&nextCompute);
    while(c) {
      new_p[c->Id] = c->processor;
      if (new_p[c->Id] != cur_p[c->Id]) nmoves++;
//      if (c->oldProcessor != c->processor)
//      CkPrintf("Refiner::Refine: from %d to %d\n", c->oldProcessor, c->processor);
      nextCompute.id++;
      c = (computeInfo *) processors[pe].computeSet->
	             next((Iterator *)&nextCompute);
    }
  }
  if (_lb_args.debug()>2)  {
    CkPrintf("New PE load: ");
    for (i=0; i<count; i++) CkPrintf("%f ", processors[i].load);
    CkPrintf("\n");
  }
  if (_lb_args.debug()>1) 
    CkPrintf("Refiner: moving %d obejcts. \n", nmoves);
  delete [] computes;
  delete [] processors;
}
Пример #4
0
int RefinerTemp::multirefine()
{
  computeAverage();
  double avg = averageLoad;
  int maxPe=-1;
 // double max = computeMax();
  double max = computeMax(&maxPe);

  //const double overloadStep = 0.01;
  const double overloadStep = 0.01;
  const double overloadStart = 1.001;
//  double dCurOverload = max / avg;
  double dCurOverload = max /(totalInst*procFreqNew[maxPe]/sumFreqs); 
                                                                               
  int minOverload = 0;
  int maxOverload = (int)((dCurOverload - overloadStart)/overloadStep + 1);
  double dMinOverload = minOverload * overloadStep + overloadStart;
  double dMaxOverload = maxOverload * overloadStep + overloadStart;
  int curOverload;
  int refineDone = 0;
//CmiPrintf("maxPe=%d max=%f myAvg=%f dMinOverload: %f dMaxOverload: %f\n",maxPe,max,(totalInst*procFreqNew[maxPe]/sumFreqs), dMinOverload, dMaxOverload);

  if (_lb_args.debug()>=1)
    CmiPrintf("dMinOverload: %f dMaxOverload: %f\n", dMinOverload, dMaxOverload);
                                                                                
  overLoad = dMinOverload;
  if (refine())
    refineDone = 1;
  else {
    overLoad = dMaxOverload;
    if (!refine()) {
      CmiPrintf("ERROR: Could not refine at max overload\n");
      refineDone = 1;
    }
  }
                                                                                
  // Scan up, until we find a refine that works
  while (!refineDone) {
    if (maxOverload - minOverload <= 1)
      refineDone = 1;
    else {
      curOverload = (maxOverload + minOverload ) / 2;
                                                                                
      overLoad = curOverload * overloadStep + overloadStart;
      if (_lb_args.debug()>=1)
      CmiPrintf("Testing curOverload %d = %f [min,max]= %d, %d\n", curOverload, overLoad, minOverload, maxOverload);
      if (refine())
        maxOverload = curOverload;
      else
        minOverload = curOverload;
    }
  }
  return 1;
}
int main(){
    int n1, n2, n3;
    printf("Please enter a number: ");
    scanf("%d", &n1);
    getchar();
    printf("Please enter a number: ");
    scanf("%d", &n2);
    getchar();
    printf("Please enter a number: ");
    scanf("%d", &n3);
    getchar();
    printf("The average of %d, %d, and %d is %d\n", n1, n2, n3, computeAverage(n1, n2, n3));
    return 0;
}
Пример #6
0
void
  Cylinder::merge(std::vector<Polygon::Ptr>& poly_vec)
  {
    assignID(poly_vec);
    //if(this->id==0) std::cout << "merge_weight before: " << this->merge_weight_ << "," << merged << std::endl;
    Polygon::Ptr p_average = Polygon::Ptr(new Cylinder);
    computeAverage(poly_vec, p_average);
    mergeUnion(poly_vec, p_average);
    std::cout << "c_merged (r, hmax, hmin, sym_axis): " << r_ << "," << h_max_ << "," << h_min_ << "," <<  sym_axis_ << std::endl;
    for(unsigned int i=0; i<contours_[0].size(); i++)
    {
      std::cout << contours_[0][i](0) << "," << contours_[0][i](1) << std::endl;
    }
    assignWeight();
    //if(this->id==0) std::cout << "merge_weight after: " << this->merge_weight_ << "," << merged  << std::endl;
  }
Пример #7
0
GifByteType GifTranscoder::computeNewColorIndex(GifFileType* gifIn,
                                                int transparentColorIndex,
                                                ColorARGB* renderBuffer,
                                                int x,
                                                int y) {
    ColorMapObject* colorMap = getColorMap(gifIn);

    // Compute the average color of 4 adjacent pixels from the input image.
    ColorARGB c1 = *getPixel(renderBuffer, gifIn->SWidth, x * 2, y * 2);
    ColorARGB c2 = *getPixel(renderBuffer, gifIn->SWidth, x * 2 + 1, y * 2);
    ColorARGB c3 = *getPixel(renderBuffer, gifIn->SWidth, x * 2, y * 2 + 1);
    ColorARGB c4 = *getPixel(renderBuffer, gifIn->SWidth, x * 2 + 1, y * 2 + 1);
    ColorARGB avgColor = computeAverage(c1, c2, c3, c4);

    // Search the color map for the best match.
    return findBestColor(colorMap, transparentColorIndex, avgColor);
}
/******************************************************************************
 Within this function, doMovingAverage(), this is where we would take in the 
the width value and subtract it from the size of the vector of stocks. The 
reason for this is to get every five of ten value from the vector and add them
using the computeAverage() in the for loop. Once the computation is complete and
the answer returns to the variable "average", then the variable "decisionMetric"
, which is the last number in the window and divides it by the average of the 
vector. Finally, in the for loop a couple of statements are ran to decide if 
the decisionMetric is greater than tolerance + 1 then sell that bad boy, if the
the decisionMetric is less than the tolerance -1, then buy it or say nothing. 
Once that is determined increment the valueStart, starting postion in vector, by
one. 

Parameters:
   tolerance - percentage of rate of growth, given as a double
   width - size given of how many values are within the vector
   
Output: Formatted integers using the class Utils and if that set of days 
        was for sale, if they were bought or lefted alone.
   

****/
void MovingAverage::doMovingAverage(int width, double tolerance)
{
std::cout << "Entering doMovingAverage" << std::endl;
double average;
auto valueStart = 0;
double  decisionMetric = 0.0;
string tol = Utils::Format(decisionMetric,8,3);
std::cout << " Computing the width and tolerance " << width << " " << tolerance
     << std::endl;
  
 for(auto i = 0; i < theData.size() -width; ++i)
 {
    average = computeAverage(i,width);
    std::cout << Utils::Format(average,8,3);
    decisionMetric = theData[i + width - 1]/average;
    std::string DM = Utils::Format(decisionMetric,8,3);
    std::cout << DM;
   
    if(  decisionMetric > (1 + tolerance))
    {
       std::cout << " sell" << std::endl;
       ++valueStart;
    }
      else 
      {
         if(  decisionMetric < (1 - tolerance) )
         {
           std::cout << " buy " << std::endl;
           valueStart++;
         }
         else
         {
           std::cout << "\n";
         }
      }        
  }             
std::cout << "leaving doMovingAverage" << std::endl;        
        
}
Пример #9
0
void RefinerTemp::Refine(int count, BaseLB::LDStats* stats, 
		     int* cur_p, int* new_p)
{
#ifdef TEMP_LDB
  //  CkPrintf("[%d] RefinerTemp strategy\n",CkMyPe());

  P = count;
  numComputes = stats->n_objs;
  computes = new computeInfo[numComputes];
  processors = new processorInfo[count];

  create(count, stats, cur_p);

  int i;
  for (i=0; i<numComputes; i++)
	{
          int ind1 = computes[i].id.getID()[0];
        int ind2 = computes[i].id.getID()[1];
  if(ind1==0 && ind2==48) CkPrintf("----- assigning oldproc%d load:%f\n",computes[i].oldProcessor,computes[i].load);

    assign((computeInfo *) &(computes[i]),
           (processorInfo *) &(processors[computes[i].oldProcessor]));
	}
  removeComputes();

  computeAverage();

  if (_lb_args.debug()>2)  {
    CkPrintf("Old PE load (bg load): ");
    for (i=0; i<count; i++) CkPrintf("%d:%f(%f) ", i, processors[i].load, processors[i].backgroundLoad);
    CkPrintf("\n");
  }

  multirefine();

  int nmoves = 0;
  for (int pe=0; pe < P; pe++) {
    Iterator nextCompute;
    nextCompute.id = 0;
    computeInfo *c = (computeInfo *)
      processors[pe].computeSet->iterator((Iterator *)&nextCompute);
    while(c) {
      new_p[c->Id] = c->processor;
      if (new_p[c->Id] != cur_p[c->Id]) nmoves++;
//      if (c->oldProcessor != c->processor)
//      CkPrintf("RefinerTemp::Refine: from %d to %d\n", c->oldProcessor, c->processor);
      nextCompute.id++;
      c = (computeInfo *) processors[pe].computeSet->
	             next((Iterator *)&nextCompute);
    }
  }
  if (_lb_args.debug()>2)  {
    CkPrintf("New PE load: ");
    for (i=0; i<count; i++) CkPrintf("%f ", processors[i].load);
    CkPrintf("\n");
  }
  if (_lb_args.debug()>1) 
    CkPrintf("RefinerTemp: moving %d obejcts. \n", nmoves);
  delete [] computes;
  delete [] processors;
#endif
}
Пример #10
0
float GoalieSystem::leftPostBearing()
{
    return computeAverage(leftPostBearings);
}
Пример #11
0
double Refiner::computeAverageLoad() {
  computeAverage();
  return averageLoad;
}
Пример #12
0
float GoalieSystem::leftPostDistance()
{
    return computeAverage(leftPostDistances);
}
Пример #13
0
int Refiner::multirefine(bool reset)
{
  computeAverage();
  double avg = averageLoad;
  double max = computeMax();

  const double overloadStep = 0.01;
  const double overloadStart = overLoad;
  double dCurOverload = max / avg;
                                                                                
  int minOverload = 0;
  int maxOverload = (int)((dCurOverload - overloadStart)/overloadStep + 1);
  double dMinOverload = minOverload * overloadStep + overloadStart;
  double dMaxOverload = maxOverload * overloadStep + overloadStart;
  int curOverload;
  int refineDone = 0;
  if (_lb_args.debug()>=1)
    CmiPrintf("dMinOverload: %f dMaxOverload: %f\n", dMinOverload, dMaxOverload);
                                                                                
  overLoad = dMinOverload;
  if (refine())
    refineDone = 1;
  else {
    overLoad = dMaxOverload;
    if (!refine()) {
      CmiPrintf("ERROR: Could not refine at max overload\n");
      refineDone = 1;
    }
  }
                                                                                
  // Scan up, until we find a refine that works
  while (!refineDone) {
    if (maxOverload - minOverload <= 1)
      refineDone = 1;
    else {
      curOverload = (maxOverload + minOverload ) / 2;
                                                                                
      overLoad = curOverload * overloadStep + overloadStart;
      if (_lb_args.debug()>=1)
      CmiPrintf("Testing curOverload %d = %f [min,max]= %d, %d\n", curOverload, overLoad, minOverload, maxOverload);

      // Reset the processors datastructure to the original
      if (reset) {
        int i;
        for (i = 0; i < P; i++) {
          processors[i].computeLoad = 0;
          delete processors[i].computeSet;
          processors[i].computeSet = new Set();
        }
        for (i = 0; i < numComputes; i++)
          assign((computeInfo *) &(computes[i]),
              (processorInfo *) &(processors[computes[i].oldProcessor]));
      }

      if (refine())
        maxOverload = curOverload;
      else
        minOverload = curOverload;
    }
  }
  return 1;
}
Пример #14
0
float GoalieSystem::rightPostBearing()
{
    return computeAverage(rightPostBearings);
}
Пример #15
0
float GoalieSystem::rightPostDistance()
{
    return computeAverage(rightPostDistances);
}
Пример #16
0
float GoalieSystem::crossDistance()
{
    return computeAverage(crossDistances);
}
Пример #17
0
void TorusLB::strategy() {
  int index;
  // compute the average load by (compute load + background load) / numPesAvailable
  computeAverage();
  // two heaps of self and pair computes
  makeTwoHeaps();

  const int beginGroup = processors[0].Id;
  const int endGroup = beginGroup + P;
#define INGROUP(PROC) ((PROC) >= beginGroup && (PROC) < endGroup)

  computeInfo *c;
  processorInfo *p, *minp;
  Iterator nextP;
  overLoad = 1.2;

  for(int I=0; I<numComputes; I++) {

  c = (computeInfo *) computePairHeap->deleteMax();
  if ( ! c ) c = (computeInfo *) computeSelfHeap->deleteMax(); 

  if(c->processor != -1) continue; // go to the next compute
  if(!c) CkAbort("TorusLB: Compute Heap empty!\n");

  for(int j=0; j<6; j++) {
    bestPe[j] = 0;
    goodPe[j] = 0;
    badPe[j] = 0;
  }

  // Look at pes which have the compute's patches

  // HYBRID check if processor is in local group
#define SELECT_REALPE(X) if INGROUP((X)) { \
  selectPes(&processors[(X) - beginGroup], c); \
  }

  const int realPe1 = patches[c->patch1].processor;
  SELECT_REALPE(realPe1)

  const int realPe2 = patches[c->patch2].processor;
  if ( realPe2 != realPe1 ) {
    SELECT_REALPE(realPe2)
  }

  // Try the processors which have the patches' proxies
  p = (processorInfo *)(patches[c->patch1].proxiesOn.iterator((Iterator *)&nextP));
  while(p) {						// patch 1
    if INGROUP(p->Id) selectPes(p, c);
    p = (processorInfo *)(patches[c->patch1].proxiesOn.next((Iterator *)&nextP));
  } 

  p = (processorInfo *)(patches[c->patch2].proxiesOn.iterator((Iterator *)&nextP));
  while(p) {						// patch 2
    if INGROUP(p->Id) selectPes(p, c);
    p = (processorInfo *)(patches[c->patch2].proxiesOn.next((Iterator *)&nextP));
  }

  // see if we have found a processor to place the compute on
  p = 0;
  if((p = bestPe[5])
#if USE_TOPOMAP
  || (p = goodPe[5])
#endif
  || (p = bestPe[4])
#if USE_TOPOMAP
  || (p = goodPe[4])
#endif
  || (p = bestPe[3])
#if USE_TOPOMAP
  || (p = goodPe[3])
#endif
  || (p = bestPe[1])
#if USE_TOPOMAP
  || (p = goodPe[1])
#endif
  || (p = bestPe[2])
#if USE_TOPOMAP
  || (p = goodPe[2])
#endif
  || (p = bestPe[0])
#if USE_TOPOMAP
  || (p = goodPe[0])
#endif
  ) {
    assign(c, p);
    continue;
  }

    // Try all pes on the nodes of the home patches
    if ( CmiNumNodes() > 1 ) {  // else not useful
      double minLoad = overLoad * averageLoad;
      minp = 0;
      int realNode1 = CmiNodeOf(realPe1);
      int nodeSize = CmiNodeSize(realNode1);
      if ( nodeSize > 1 ) {  // else did it already
        int firstpe = CmiNodeFirst(realNode1);
        for ( int rpe = firstpe; rpe < firstpe+nodeSize; ++rpe ) {
          if INGROUP(rpe) {
            p = &processors[rpe - beginGroup];
            if ( p->available && ( p->load + c->load < minLoad ) ) {
              minLoad = p->load + c->load;
              minp = p;
            }
          }
        }
      }
      if ( realPe2 != realPe1 ) {
        int realNode2 = CmiNodeOf(realPe2);
        if ( realNode2 != realNode1 ) {  // else did it already
          nodeSize = CmiNodeSize(realNode2);
          if ( nodeSize > 1 ) {
            int firstpe = CmiNodeFirst(realNode2);
            for ( int rpe = firstpe; rpe < firstpe+nodeSize; ++rpe ) {
              if INGROUP(rpe) {
                p = &processors[rpe - beginGroup];
                if ( p->available && ( p->load + c->load < minLoad ) ) {
                  minLoad = p->load + c->load;
                  minp = p;
                }
              }
            }
          }
Пример #18
0
int main()
{
	//int trials_to_change_maze_states= 10000;
	int i;
	main_log_file= fopen("log.txt","w");

	Random* random= new State_of_Art_Random(time(NULL));
	
	//Reinforcement_Environment* env= new Mountain_Car(random);
	Reinforcement_Environment* env= new Function_Approximation(random,1000,false);
	//Reinforcement_Environment* env= new Single_Cart_Pole(random);
//Reinforcement_Environment* env= new Double_Cart_Pole(random);
	//Reinforcement_Environment* env= new Multiplexer(3,8,random);

	//Reinforcement_Agent* agent= new Dummy(env);
	Reinforcement_Agent* agent= new Unified_Neural_Model(random);
	
	setFeatures(env);

	//Self_Organizing_Neurons* b= (Self_Organizing_Neurons*)agent;

	//print max accumulated reward seen in N trials, the N trials is given by trial_frequency_to_print
	bool print_max_accum_reward_in_n_trials= true;
	int trial_frequency_to_print= 100;
	double max_accum_reward=0;
	bool was_initialized=false;	//tells if the max_accum_reward was initialized

	bool print_reward=false;
	bool print_step=false;
	bool print_average=false;
	//bool print_accumulated_reward=true;
	bool print_agent_information=false;

	//int trials=100000
	int trials=200000;		
	//int trials=200;		
	//int trials=500;		
	//int trials=100000;		
	
	int number_of_observation_vars;
	int number_of_action_vars;
	
	env->start(number_of_observation_vars, number_of_action_vars);
	agent->init(number_of_observation_vars, number_of_action_vars);
	
	//starting reward 
	double reward= env->step(NULL);		
	double step_counter=1;
		
	//agent->print();
		
	double last_rewards[100];
	int counter=0;
	double avg_rewards;

	
	for(i=env->trial;i<trials;)
	{
		double accum_reward=reward;
		//do one trial (multiple steps until the environment finish the trial or the trial reaches its MAX_STEPS)
		while(env->trial==i && step_counter <= env->MAX_STEPS)
		{

			agent->step(env->observation, reward);

			reward= env->step(agent->action);		
		
			accum_reward+= reward;
		
			if(print_reward)
			{
				last_rewards[counter%100]=reward;
				counter++;
				
				if(print_average)
				{
					avg_rewards= computeAverage(last_rewards, counter);
					printf("%d %f\n",i, avg_rewards);
				}
				else
				{
					printf("%d %f\n",i, reward);
				}

			}
		
			step_counter++;

		}

#ifdef TERMINATE_IF_MAX_STEPS_REACHED
		//end evolution when the MAX_STEPS is reached
		if(step_counter > env->MAX_STEPS)
		{
			i=trials;
		}
#endif
	
		//update the max_accum_reward and print		
		if(print_max_accum_reward_in_n_trials)
		{	
			if(was_initialized==false)
			{
				was_initialized=true;
				max_accum_reward= accum_reward;
			}
			else
			{
				if(max_accum_reward < accum_reward)
				{
					max_accum_reward= accum_reward;
				}
			}		
		
			if(i%trial_frequency_to_print==0)
			{	
				printf("%d %f\n",i, max_accum_reward);
		
				max_accum_reward=0;
				was_initialized=false;

			}
		}
	
		agent->endEpisode(reward);

			
		//if env->trial is the same as i, it means that the internal state of the environment has not changed
		//then it needs a restart to begin a new trial
		if(env->trial==i)
		{
			reward= env->restart();
		}
		else
		{
			reward= env->step(NULL);
		}
	
		//print the number of steps used in the last trial
		if(print_step)
		{
			last_rewards[counter%100]=step_counter;
			counter++;

			if(print_average)
			{
				avg_rewards= computeAverage(last_rewards, counter);
				printf("%d %f\n",i, avg_rewards);
			}
			else
			{
				printf("%d %f\n",i, step_counter);
			}
		}
		
		if(print_agent_information==true)
		{
			agent->print();
		}

		step_counter=1;

		i++;

	
	}

	agent->saveAgent("dna_best_individual");
	


	//printf("reward average %f\n",reward_sum/(double)trials);
	//printf("step average %f\n",step_sum/(double)trials);
	
	fclose(main_log_file);	

	return 0;
}
Пример #19
0
float GoalieSystem::crossBearing()
{
    return computeAverage(crossBearings);
}