Ejemplo n.º 1
0
void StarSystem::GenerateContents()
{
	int numPlanets = 1 + iRand(5);
	for(int curPlanetNum = 0; curPlanetNum < numPlanets; ++curPlanetNum)
	{
		//create random planet type
		if(fRand() < 0.001)
		{
			// 0.01%
			mContents.push_back(new Planet(this, HabitableObject::PLANET_TERRAN));
		}
		else if(fRand() < 0.199)
		{
			// 19.9%
			mContents.push_back(new Planet(this, HabitableObject::PLANET_ICE));
		}
		else if(fRand() < 0.2)
		{
			// 20%
			mContents.push_back(new Planet(this, HabitableObject::PLANET_GASGIANT));
		}
		else
		{
			// 60%
			mContents.push_back(new Planet(this, HabitableObject::PLANET_DEAD));
		}

		GameManager::GetSingleton().AddHabitableObject((Planet*)mContents.back());
		GameManager::AddSettletPlanet((Planet*)mContents.back());
	}
	//create the star
	mContents.push_back(new Star(this));
	//
	mGeneratedContents = true;
}
Ejemplo n.º 2
0
void generateFreq_Amp(int nComp,double *freq,double *amp,double fMax,double A){
	for(int i=0;i<nComp;i++){
		freq[i] = fRand(0,fMax);
		amp[i] = fRand(0,A);
		printf("\nFREQ[%d] = %lf AMP[%d] = %lf",i,freq[i],i,amp[i]);
	}
	return;
}
Ejemplo n.º 3
0
//************************************
// Method:    decisionRule
// FullName:  CAntColonySystem::decisionRule
// Access:    virtual private 
// Returns:   void
// Qualifier:
// Parameter: size_t k
// Parameter: size_t step
// Parameter: uniform_real<double> & rndSelTrsh
// Parameter: uniform_real<double> & choiceE
//************************************
void CAntColonySystem::decisionRule(size_t k, size_t step, uniform_real<double> &rndSelTrsh, uniform_real<double> &choiceE)
{
     //roulette wheel selection  
	size_t c = m_Ants[k].getCity(step-1); 
	double sum_prob =0;
 
		for (size_t i=0; i<m_noNodes; i++) 
		{
			t_prob[i] = 0.0;
			m_strength[i] = 0; 	
			if (m_Ants[k].isCityVisited(i) == false )	
			{
				t_prob[i]= (*m_heuristicMatrix)[c][i];
				sum_prob +=t_prob[i];
			}
		}
		for (size_t z =0; z < m_noNodes; z++)
			m_strength[z+1] = t_prob[z] + m_strength[z];
		
		  std::tr1::mt19937 eng;
		//rndSelTrsh
	//	double x = rndSelTrsh(eng) * m_strength[m_noNodes];
		double x = fRand(0,1.0)  * m_strength[m_noNodes];
		
		int j = 0;
		while (!((m_strength[j] <= x) && (x <= m_strength[j+1])))
		  j++;
		
		size_t randomDecision =j;

		//find best neg
		double maxHeuristic = -1;
        int maxHeuristicIdx = -1;
        for(j = 0; j < m_noNodes; j++)
		{
			 double choice = (*m_heuristicMatrix)[c][j];
			 if(maxHeuristic < choice && !(m_Ants[k].isCityVisited(j))) //&& c!=j)
			 {
				maxHeuristic = choice;
				maxHeuristicIdx = j;
			}
        }
		x=fRand(0,1.0);//choiceE(eng);

        if(x < q0)  
		{
            m_Ants[k].setAntCity(step, maxHeuristicIdx);
            m_Ants[k].setCityVisited(maxHeuristicIdx);
        }
        else //if exploitation
		{
			//	std::cout << maxHeuristicIdx << ",";
            m_Ants[k].setAntCity(step, randomDecision);
            m_Ants[k].setCityVisited(randomDecision);
        }

}
Ejemplo n.º 4
0
void points::init_locations(void) {
	for (int i = 0; i < NUM; i++) {
		double x = fRand(0.0, 100.0);
		double y = fRand(0.0, 100.0);
		double z = fRand(0.0, 100.0);
		Points[i].set_locations(x, y, z);
		int hash_idx = (int)(floor(x / 10.0) + floor(y / 10.0) * 10 + floor(z / 10.0) * 100);
		(*Points_hash)[hash_idx].insert(i);
	}
}
Ejemplo n.º 5
0
StarSystem::StarSystem(StellarGroup* a_pParent, bool a_IsHomeSystem)
:	DisplayableObject(DisplayableObject::STARSYSTEM, a_pParent)
,	mIsNebula(false)
//,	mAsteroidBelt(*new AsteroidBelt())
{
	m_ImageName = "../media/system.png";
	m_BGImageName = "../media/starsystem_bg.png";
	//
	m_Name = GetRandomName(DisplayableObject::STARSYSTEM);
	if(a_IsHomeSystem)
	{
		//create the starting planet
		mContents.push_back(new Planet(this, HabitableObject::PLANET_TERRAN));
		GameManager::SetHomePlanet((Planet*)mContents.back());
		GameManager::AddSettletPlanet((Planet*)mContents.back());

		//create this system's planets
		GenerateContents();
		ShowContents(false);

		//we're at the center of the entire playable area
		mRelPosition.x = 0.5f;
		mRelPosition.y = 0.5f;
	}
	else
	{
		GenerateContents();

		//5% chance of being a nebula
		mIsNebula = iRand() > 95 ? true : false;
		
		mRelPosition.x = fRand();
		mRelPosition.y = fRand();

		/*
		//calculate a random position for this group in the stellar group
		//calculate random coords with an even distribution across the internal volume of a sphere
		float phi = fRand() * PI;
		float costheta = fRand() * 2 - 1;
		float u = fRand();

		float theta = acos( costheta );
		float R = 1.f;		//distribution radius - just use 0-1 for easy distribution across screen space
		float r = R * curt( u );

		//as we're treating everything as 2D for now, just drop the zPos
		mRelPosition.x = r * sin( theta) * cos( phi );
		mRelPosition.y = r * sin( theta) * sin( phi );
		//mRelPosition.z = r * cos( theta );
		*/
	}
}
Ejemplo n.º 6
0
void initGradient()
{
	for (int y = 0; y < array_height; ++y)
	{
		for (int x = 0; x < array_width; ++x)
		{
			double x_value = fRand(-1.0, 1.0);
			double y_value = fRand(-1.0, 1.0);
			Gradient[x][y] = Vector2(x_value, y_value);
			std::cout << Gradient[x][y].x << ", " << Gradient[x][y].y << "\n";
		}
	}
}
Ejemplo n.º 7
0
void Game::generateEnemy() {
	clock_t currentTime = clock();
	if (currentTime - lastGeneratedEnemy > enemyGenerationDiff) {
		lastGeneratedEnemy = currentTime;

		GLfloat x = fRand(leftDownCorner.x, rightDownCorner.x);
		auto position = F3dVector(x, 0, -depth);
		auto velocity = F3dVector(0.0, 0.0, fRand(0.02, 0.15));
		auto red = Color(0.05, 0.9, 0.05);

		Enemy* newEnemy = new Enemy(this, position, velocity, red, 100);
		enemies.push_back(shared_ptr<Enemy>(newEnemy));
	}
}
Ejemplo n.º 8
0
void initGradInfo(GradientInfo *gradInfo, ImageInfo *image)
{
	gradInfo->grid_cell_width = image->width / gradInfo->width;
	gradInfo->grid_cell_height = image->height / gradInfo->height;
	for (int y = 0; y < gradInfo->height + 1; ++y)
	{
		for (int x = 0; x < gradInfo->width + 1; ++x)
		{
			gradInfo->Gradient[x][y].x = fRand(-1.0, 1.0);
			gradInfo->Gradient[x][y].y = fRand(-1.0, 1.0);
			std::cout << "Vector " << x << ", " << y << ": " << gradInfo->Gradient[x][y].x << ", " << gradInfo->Gradient[x][y].y << "\n";
		}
	}
}
Ejemplo n.º 9
0
  void generateRandomBlock(geometry_msgs::Pose& block_pose)
  {
    // Position
    block_pose.position.x = fRand(0.1,0.55);
    block_pose.position.y = fRand(-0.28,0.28);
    block_pose.position.z = 0.02;

    // Orientation
    double angle = M_PI * fRand(0.1,1);
    Eigen::Quaterniond quat(Eigen::AngleAxis<double>(double(angle), Eigen::Vector3d::UnitZ()));
    block_pose.orientation.x = quat.x();
    block_pose.orientation.y = quat.y();
    block_pose.orientation.z = quat.z();
    block_pose.orientation.w = quat.w();
  }
Ejemplo n.º 10
0
bool InitDriveThread::setDiskId()
{
    mbr_table mbr;

    QFile f(_drive);
    f.open(f.ReadOnly);
    f.read((char *) &mbr, sizeof(mbr));
    f.close();

    if ( qFromLittleEndian<quint32>(mbr.diskid) == 0 )
    {
        emit statusUpdate(tr("Setting disk volume ID"));

        /* Set disk volume ID to random number from urandom */
        QFile fRand("/dev/urandom");
        fRand.open(f.ReadOnly);
        fRand.read((char *) mbr.diskid, sizeof(mbr.diskid));
        fRand.close();

        /* Make sure it isn't zero */
        if (qFromLittleEndian<quint32>(mbr.diskid) == 0)
            mbr.diskid[0] = 1;

        f.open(f.ReadWrite);
        f.write((char *) &mbr, sizeof(mbr));
        qDebug() << "Set disk volume ID to:" << QByteArray::number(qFromLittleEndian<quint32>(mbr.diskid), 16);
        f.close();
    }

    return true;
}
Ejemplo n.º 11
0
void CuriosityLoop::replicateUnrestrictPredictor(int chosen_act, int inputSize, int sensornumber){ 

	//cout << "REPLICATING AND UNRESTRICTING PREDICTOR\n"; 
	predictorWeights =  predictorWeights.map(random_minusone_to_one)*1.0;
	uPredictorWeights = predictorWeights;  

// 	uPredictorMask = predictorMask; 
        uPrediction = prediction;   
	
	uPInput = pInput; 
	uPOutput = pOutput; 
	
	//Unrestrict upInput now to it gets input from all motors (of the actor) and the sensors of the restricted model.  
	for(int i = 0; i < inputSize+1; i++){ 
			if(pInput.val(i,0) == 1)
				uPInput.val(i,0) = 1; //i.e. gets input from all motors. 
			if(i > sensornumber + 1){ //THIS SHOULD BE FROM THE MOTORS 	
				uPInput.val(i,0) = 1; //For now, the actor influences all motors. 
				//cout << "Making motor inputs to unrestricted predictor\n"; 
			}
	}

	//Set the motor weights to near zero. 
	   for(int i = 0; i < uPredictorWeights.getM(); i++){//Predicts output i.
		for(int j = 0; j < uPredictorWeights.getN(); j++){//Takes input j. 
				if(j > sensornumber +1){ 
					uPredictorWeights.val(i,j) = fRand(-0.01,0.01);		
				}	
			}
	   }
}; 
Ejemplo n.º 12
0
void Method::init_params(Problem &problem)
{

    if(!use_grid)
    {
        for(unsigned i=0;i<problem.params.size();++i)
        {
            if (randomize[i]) //Random init
            {
                problem.params[i] = fRand(rand_min[i], rand_max[i]);
            }
            else  // use random_min as start value
            {
                problem.params[i] = rand_min[i];
            }
        }
    }
    else
    {
        for(unsigned i=0;i<problem.params.size();++i)
        {
            problem.params[i] = step_size[i];
        }

    }
}
Ejemplo n.º 13
0
		void createParticles()
		{	
			particles = new SphParticle2d[cntAllParticles];
			for(int l=0,l2=0, i=0;i<cntAllParticles;i++,l2+=5)
			{
					particles[i].cr=fRand(0,1);
					particles[i].cg=fRand(0,1);
					particles[i].cb=fRand(0,1);
					particles[i].x = 50+l2;
					if(l2>100)
					{
						l2=0;
						l+=5;
					}
					particles[i].y=50+l;
			}
		}
Ejemplo n.º 14
0
void Scene::init(){
    srand(time(NULL));
        for(int i= 0 ; i < maxParts; i ++){
            // double x = fRand(-0.1, 0.1);
            // double y = fRand(0.5, 0.6);
            // double z = fRand(-1.1, -1.6);
            // double x = fRand(WIDTH/2 - 25,WIDTH/2 + 25);
            // double y = fRand(HEIGHT-175, HEIGHT-125);
            // double z = fRand(-30, -35);
            double x = fRand(WIDTH/2 - 25,WIDTH/2 + 25);
            double y = fRand(400, 450);
            double z = fRand(-80, -125);
            Vector3f pos(x, y, z);
            Particle *p = new Particle(MASS, pos, Vector3f(0, 0, 0));
            particles->push_back(p);
        }
}
Ejemplo n.º 15
0
void CuriosityLoop::replicateMutateActor(void){ 

   	offspringActorWeights = actorWeights; 

	//Mutate the offspring actor. 
	for(int i = 0; i < offspringActorWeights.getM(); i++){
	   for(int j = 0; j <offspringActorWeights.getN(); j++){
		if(fRand(0,1) < 0.05){ 
			offspringActorWeights.val(i,j) = offspringActorWeights.val(i,j) + fRand(-0.5,0.5); 
	
			if(offspringActorWeights.val(i,j) > 10)
				offspringActorWeights.val(i,j)  = 10; 
			else if(offspringActorWeights.val(i,j)  < -10)
				offspringActorWeights.val(i,j) = -10; 
		}
	   }
	}
}; 
Ejemplo n.º 16
0
void initializeArray2D(float *arr, int len, int seed) {
  int i;
  float randNum;
  srand(seed);
  for (i = 0; i < len * len; i++) {
    randNum = (float) fRand((double)(MINVAL),(double)(MAXVAL));
    arr[i] = randNum;
  }
}
Ejemplo n.º 17
0
void idle () {
	
	///*
	double theta = NO_HIT;
	if (bat1->checkCollisions(myball) ){
		theta = fRand(-M_PI/4, 0);
		if (myball->getdy()>0)theta+=M_PI/4;
	}
	else if ( bat2->checkCollisions(myball) ){
		theta = fRand(3*M_PI/4,M_PI);
		if(myball->getdy()<0)theta+=M_PI/4;
	}
	else if ( myball->checkWall() == 4 ) {
		theta = fRand(M_PI,6*M_PI/4);
		if(myball->getdx()>0)theta+=M_PI/2;
	}
	else if ( myball->checkWall() == 3 ) {
		theta = fRand(0,M_PI/2);
		if(myball->getdx()<0)theta+=M_PI/2;
	}
	//*/
	if(theta!=NO_HIT) myball->setSpeed(speed,theta);
	myball->move();
	
	if( keyarr['w'] && bat1->checkWall()!=4 )
		bat1->move(0,speed);
	else if(keyarr['s'] && bat1->checkWall()!=3 )
		bat1->move(0,-speed);
	if( keyarr['i'] && bat2->checkWall()!=4 )
		bat2->move(0,speed);
	else if( keyarr['k'] && bat2->checkWall()!=3 )
		bat2->move(0,-speed);
	
	if( keyarr['r'] ){ 
		myball->reset();
		myball->setSpeed(speed,rand()%2*M_PI);
	}	
	if( keyarr['q'] ) cleanup();
	
	glutPostRedisplay();
}
Ejemplo n.º 18
0
int init_vector_rand(vec_ptr v, long int len) {
  long int i;

  if (len > 0) {
    v->len = len;
    for (i = 0; i < len*len; i++)
      v->data[i] = (data_t)(fRand((double)(MINVAL),(double)(MAXVAL)));
    return 1;
  }
  else
  	return 0;
}
Ejemplo n.º 19
0
void transmit(const char *input,const char *output,double error){
	FILE *fin = fopen(input,"r");
	FILE *fout = fopen(output,"w");
	int sampleCount;
	fscanf(fin,"%d",&sampleCount);
	fprintf(fout,"%d\n",sampleCount);
	double t,amp;
	for(int i=0;i<sampleCount;i++){
		fscanf(fin,"%lf %lf",&t,&amp);
		if(rand()%2==1){
			// positive
			amp = amp + fRand(0,error);
		}else{
			// negative
			amp = amp - fRand(0,error);
		}
		fprintf(fout, "%lf %lf\n",t,amp);
	}
	fclose(fin);
	fclose(fout);
	return;
}
Ejemplo n.º 20
0
void BambooScene::onCreate()
{
    const OSize& frameSize = ODirector::director()->getVirtualSize();
    
    //sky
    sky = new OSprite(0, 0, frameSize.width, frameSize.height, "bsky.png", 0);
    addSprite(sky);
    
    particles = new OParticleBatch2D();
    
    particles->init(40, .9f , "cloud.png", 5,
                    [](OParticleBatch2D* batch, float deltaTime){
                        const OSize& frameSize = ODirector::director()->getVirtualSize();
                        vec2 posi = vec2(fRand(0, frameSize.width), fRand(0, frameSize.height));
                        batch->addParticle(posi, vec2(), OColorRGBA8(), 20);
                    },
                    [](OParticle2D& particle, float deltaTime){
                        particle.position += particle.velocity * deltaTime;
                        particle.color.setAlpha(particle.life);
    });
    getMainLayer2D()->particleEngine->addParticleBatch(particles);
    
}
Ejemplo n.º 21
0
void increasePointsToInDenseCells(BCellListHd denseCellsList,int limit)
{
	BCellListNode currBCellListNode = denseCellsList->first;
	BCell currBCell;
 	BCellListNode tempBCellListNode;
 	Data currData;
 	DataPoint currDataPoint;

 	int i =0;

 	srand((unsigned)time(NULL));

 	int counter=0;

 	double randCoords[DIMENSION];
 	
 	while(currBCellListNode!=NULL)
 	{	
		currBCell = currBCellListNode->bCellElem;

 		if(currBCell->cellDataList->count<=limit)
 		{
 			counter = limit - currBCell->cellDataList->count;

 			while(counter > 0)
 			{
 				for(i = 0; i<DIMENSION; i++)
	 			{
	 				randCoords[i] = fRand(currBCell->minOriginalBoundary[i], currBCell->maxOriginalBoundary[i]);
	 			}

	 			Data currData = (Data) malloc(sizeof(*currData));
	 			currData->iData = (DataPoint) malloc(DIMENSION *sizeof(dataPoint));
	 			for(i=0;i<DIMENSION;i++)
	 			{
	 				currData->iData[i] = randCoords[i];
	 			}

	 			insertPointintoBCell(currBCell,currData);
	 			counter--;
 			}

 		}

 		currBCellListNode = currBCellListNode->next;
 		counter = 0;

 	}

}
Ejemplo n.º 22
0
long Poison(double lambda)
	{
		/*long k = 0;
		double p = 1;
		double L;
		L = exp(-lambda2);
		while (p > L)
		{
			k++;
			double f = fRand();
			p = p*f;
		}
		return k-1;*/
		return (long) (ceil)(-1*(0.9/lambda)*log(fRand())+0.1/lambda);
	}
Ejemplo n.º 23
0
int main() {
    int i;
    int dimension = 100;
    double val;

    FILE *valueFile;
    valueFile = fopen("valuesSmall.txt", "w");
    if (valueFile == NULL) {
        fprintf(stdout, "LOG ERROR - Failed to open file. Exiting program");
        return 1;
    }

    srand((unsigned)time(NULL));

    for (i = 0; i < dimension * dimension; i++) {
        val = fRand(1, 2);
        fprintf(valueFile, "%.5lf ", val);
    }
}
Ejemplo n.º 24
0
void lookup_transforms(tf2::BufferCore& buffer, std::set<std::string> frame_ids) {
    std::string frame1 = "child";
    std::string frame2 = "parent";
    geometry_msgs::TransformStamped tfs;

    double num_lookups = 1e5;
    double tree_depth = 0.0;
    std::vector<std::string> set_vector(frame_ids.begin(), frame_ids.end());  // Want constant time element indexing
    size_t n_frames = set_vector.size();
    std::stringstream rs;
    rs << num_lookups << " random lookups - on " << n_frames << " total frames";
    log(rs.str().c_str());
    double start = now();
    for(size_t i = 0; i < num_lookups; i++) {
        frame1 = set_vector[true_random_index(n_frames)];
        frame2 = set_vector[true_random_index(n_frames)];
        ros::Time lookup_time(fRand(10.0, 20.0));
        try {
            tfs = buffer.lookupTransform(frame1, frame2, lookup_time);
            tree_depth += abs(tfs.transform.translation.x);
        } catch(const tf2::ConnectivityException& e) {
            log("CONNECTIVITY EXCEPTION");
        } catch(const tf2::ExtrapolationException& e) {
            log("EXTRAPOLATION EXCEPTION");
        } catch(const tf2::LookupException& e) {
            log("LOOKUP EXCEPTION");
        } catch (...) {
            log("SUPER BAD EXCEPTION");
        }
    }

    double end = now();
    double avg_depth = tree_depth / num_lookups;

    std::stringstream st;
    st << "Start time: " << start << "\nEnd time: " << end
       << "\n Diff: " << end - start << "\n Avg: " << (end-start)/num_lookups
       << "\n Avg tf tree depth:" << avg_depth;
    log(st.str().c_str());
}
Ejemplo n.º 25
0
void SAKeStart::startRegression(const QVariant &_projectaname,
                                   const QVariant &selection,
                                   const QVariant &elitist,
                                   const QVariant &populationSize,
                                   const QVariant &percentageCrossover,
                                   const QVariant &percentageMutation,
                                   const QVariant &numberProcessor,
                                   const QVariant &maxGeneration,
                                   const QVariant &fileurl,
                                   const QVariant &tipo,
                                   const QVariantList &matrxGamma1QML,
                                   const QVariantList &matrixGamma2QML,
                                   const QVariantList &matrixLinearQML,
                                   const QVariant &checkControlpoints,
                                   const QVariant &checkKernel,
                                   const QVariant &checkN,
                                   const QVariant &checkControlPointsWithN,
                                   const QVariant &textN,
                                   const QVariant &para1,
                                   const QVariant &para2,
                                   const QVariant &typeReplacement,
                                   const QVariant &typeProject)
{
    std::vector<std::vector<double> > matrixGamma1;
    int numberElementsTable = 12;
    QList <QVariant> tmpGamma1 = matrxGamma1QML[0].toList();
    for (int i = 1; i < tmpGamma1[0].toInt()+1; ++i) {
        QList <QVariant> tmpGammat1 = matrxGamma1QML[i].toList();
        std::vector<double> tmp;
        for (int j = 0; j < numberElementsTable; ++j) {
            //cout << tmpGammat1[j].toDouble() << " ";
            tmp.push_back(tmpGammat1[j].toDouble());
        }
        matrixGamma1.push_back(tmp);
        //cout << endl;
    }

    std::vector<std::vector<double> > matrixGamma2;
    QList <QVariant> tmpGamma2 = matrixGamma2QML[0].toList();
    for (int i = 1; i < tmpGamma2[0].toInt()+1; ++i) {
        QList <QVariant> tmpGammat2 = matrixGamma2QML[i].toList();
        std::vector<double> tmp;
        for (int j = 0; j < numberElementsTable; ++j) {
            //cout << tmpGammat2[j].toDouble() << " ";
            tmp.push_back(tmpGammat2[j].toDouble());
        }
        matrixGamma2.push_back(tmp);
        //cout << endl;
    }

    std::vector<std::vector<double> > matrixLinear;
    QList <QVariant> tmpGamma3 = matrixLinearQML[0].toList();
    for (int i = 1; i < tmpGamma3[0].toInt()+1; ++i) {
        QList <QVariant> tmpGammat3 = matrixLinearQML[i].toList();
        std::vector<double> tmp;
        for (int j = 0; j < numberElementsTable; ++j) {
            //cout << tmpGammat3[j].toDouble() << " ";
            tmp.push_back(tmpGammat3[j].toDouble());
        }
        matrixLinear.push_back(tmp);
        //cout << endl;
    }

    QString typeExecution="0";
    if(checkKernel.toBool()){
        typeExecution="1";
    }else
        if(checkN.toBool()){
            typeExecution="2";
        }
    if(tipo.toInt()==1 )
    {
        xmlManager->SaveXMLFileAlreadyExistRegressionProject(_projectaname.toString(),
                                                             selection.toString(),
                                                             para1.toString(),
                                                             para2.toString(),
                                                             populationSize.toString(),
                                                             percentageCrossover.toString(),
                                                             percentageMutation.toString(),
                                                             numberProcessor.toString(),
                                                             maxGeneration.toString(),
                                                             fileurl.toString(),
                                                             matrixGamma1,
                                                             matrixGamma2,
                                                             matrixLinear,
                                                             checkControlPointsWithN,
                                                             textN,
                                                             typeExecution,
                                                             typeReplacement.toString(),
                                                             elitist.toString());


    }else{
        xmlManager->SaveXMLFileRegressionProject(_projectaname.toString(),
                                                 selection.toString(),
                                                 para1.toString(),
                                                 para2.toString(),
                                                 populationSize.toString(),
                                                 percentageCrossover.toString(),
                                                 percentageMutation.toString(),
                                                 numberProcessor.toString(),
                                                 maxGeneration.toString(),
                                                 fileurl.toString(),
                                                 matrixGamma1,
                                                 matrixGamma2,
                                                 matrixLinear,
                                                 checkControlPointsWithN,
                                                 textN,
                                                 typeExecution,
                                                 typeReplacement.toString(),
                                                 elitist.toString());
    }

    QString sselction= selection.toString();
    int ielitist = elitist.toInt();
    int ipopulationSize = populationSize.toInt();
    int imaxGeneration = maxGeneration.toInt();
    double dpercentageCrossover = percentageCrossover.toDouble();
    double dpercentageMutation = percentageMutation.toDouble();
    int inumberProcessor = numberProcessor.toInt();
    QString sfileurl = fileurl.toString();
    bool checkControlPointsBool = checkControlpoints.toBool();
    bool checkKernelBool = checkKernel.toBool();
    bool checkNBool = checkN.toBool();
    bool checkControlPointsWithNBool = checkControlPointsWithN.toBool();
    int n = textN.toInt();

    //    qDebug() << "sselction : " << sselction ;
    //    qDebug() << "ielitist : " << ielitist   ;
    //    qDebug() << "ipopulationSize : " << ipopulationSize   ;
    //    qDebug() << "dpercentageCrossover : " << dpercentageCrossover   ;
    //    qDebug() << "dpercentageMutation : " << dpercentageMutation   ;
    //    qDebug() << "sselctiodpercentageWeightn : " << dpercentageWeight   ;
    //    qDebug() << "inumberProcessor : " << inumberProcessor   ;
    //    qDebug() << "inumberGamma : " << inumberGamma   ;
    //    qDebug() << "dpercentageGammaA : " << dpercentageGammaA   ;
    //    qDebug() << "dpercentageGammaB : " << dpercentageGammaB   ;
    //    qDebug() << "inumberLinear : " << inumberLinear   ;
    //    qDebug() << "dpercentageLinearA : " << dpercentageLinearA   ;
    //    qDebug() << "dpercentageLinearB : " << dpercentageLinearB   ;
    //    qDebug() << "imaxGeneration : " << imaxGeneration     ;
    //    qDebug() << "sfileurl : " << sfileurl     ;
    int idProject = threadsController.size();
    QObject *rootObject = engine->rootObjects().first();
    QObject *rectMain = rootObject->findChild<QObject*>("Rectanglemain");
    QVariant msg = "Regression - "+ _projectaname.toString();
    QVariant returnedValue;
    QMetaObject::invokeMethod(rectMain, "addTabRegression", Q_RETURN_ARG(QVariant, returnedValue), Q_ARG(QVariant, msg),Q_ARG(QVariant, threadsController.size()));
    //FINE

    //identifico i puntatori agli oggetti che in seguito dovrò aggiornare
    //INIZIO
    //    CustomPlotItem *qCustomPlotFitness = rootObject->findChild<CustomPlotItem*>(QString("customPlotFitness%1").arg(idProject));
    //    CustomPlotRegression *qCustomPlotRegression = rootObject->findChild<CustomPlotRegression*>( QString("customPlotRegression%1").arg(numberProject) );
    CustomPlotRegression *qCustomPlotRegression = rootObject->findChild<CustomPlotRegression*>( QString("customPlotRegression%1").arg(idProject) );
    QObject *gen = rootObject->findChild<QObject*>(QString("gen%1").arg(idProject));
    QObject *currentMaximumFitness = rootObject->findChild<QObject*>(QString("currentMaximumFitness%1").arg(idProject));
    QObject *absoluteMaximumFitness = rootObject->findChild<QObject*>(QString("absoluteMaximumFitness%1").arg(idProject));
    QObject *currentAverageFitness = rootObject->findChild<QObject*>(QString("currentAverageFitness%1").arg(idProject));
    QObject *absoluteAverageFitness = rootObject->findChild<QObject*>(QString("absoluteAverageFitness%1").arg(idProject));
    QObject *progressBar = rootObject->findChild<QObject*>(QString("progressBar%1").arg(idProject));
    progressBar->setProperty("maximumValue",100);
    progressBar->setProperty("minimumValue",0);
    qCustomPlotRegression->setNumber_of_function(matrixGamma1.size()+matrixGamma2.size()+matrixLinear.size());

    QObject *buttonStop = rootObject->findChild<QObject*>(QString("stop%1").arg(idProject));


    Update * update = new Update();
    UpdateProjects * updateprojects = new UpdateProjects(update);
    updateprojects->UpdateProjectsRegression(currentMaximumFitness,
                                             absoluteMaximumFitness,
                                             currentAverageFitness,
                                             absoluteAverageFitness,
                                             gen,
                                             progressBar);

    int dimension=matrixGamma1.size()+matrixGamma2.size()+matrixLinear.size();
    double * weight = new double[dimension];
    int count =0;
    for (int i = 0; i < matrixLinear.size(); ++i) {
        double tmp1=fRand(matrixLinear[i][4],matrixLinear[i][5]);
        weight[count] = tmp1;
        count++;
    }
    for (int i = 0; i < matrixGamma1.size(); ++i) {
        double tmp1=fRand(matrixGamma1[i][4],matrixGamma1[i][5]);
        weight[count] = tmp1;
        count++;
    }
    for (int i = 0; i <  matrixGamma2.size(); ++i) {
        double tmp1=fRand(matrixGamma2[i][4],matrixGamma2[i][5]);
        weight[count] = tmp1;
        count++;
    }

    int * functionType = new int[dimension];

    double * percantageGammaA;
    percantageGammaA= new double[dimension];
    double * percantageGammaB;
    percantageGammaB= new double[dimension];
    double * percantageLinearA;
    percantageLinearA= new double[dimension];
    double * percantageLinearB;
    percantageLinearB= new double[dimension];
    double * percantageW;
    percantageW= new double[dimension];
    double* translation= new double[dimension];

    count = 0;
    for (int i = 0; i < matrixLinear.size(); ++i) {
        functionType[count]=0;
        percantageLinearA[count]=matrixLinear[i][6];
        percantageLinearB[count]=matrixLinear[i][7];
        percantageW[count]=matrixLinear[i][8];
        translation[count] = matrixLinear[i][11];
        count++;
    }
    for (int i = 0; i < matrixGamma1.size(); ++i) {
        functionType[count]=1;
        percantageGammaA[count]=(matrixGamma1[i][6]);
        percantageGammaB[count]=(matrixGamma1[i][7]);
        percantageW[count]=(matrixGamma1[i][8]);
        translation[count] =matrixGamma1[i][11];
        count++;
    }
    for (int i =  0; i <  matrixGamma2.size(); ++i) {
        functionType[count]=2;
        percantageGammaA[count]=(matrixGamma2[i][6]);
        percantageGammaB[count]=(matrixGamma2[i][7]);
        percantageW[count]=matrixGamma2[i][8];
        translation[count] =matrixGamma2[i][11];
        count++;
    }

    Parameters *parameters = new Parameters[dimension];

    count = 0;
    for (int i = 0; i < matrixLinear.size(); ++i) {
        Parameters tmp;
        double tmp1=fRand(matrixLinear[i][0],matrixLinear[i][1]);
        //std::cout <<tmp1<< std::endl;
        tmp.addParameters(tmp1);
        double tmp2=fRand(matrixLinear[i][2],matrixLinear[i][3]);
        //std::cout <<tmp2<< std::endl;
        tmp.addParameters(tmp2);
        double tmp3=fRand(matrixLinear[i][9],matrixLinear[i][10]);
        //std::cout <<tmp3<< std::endl;
        tmp.addParameters(tmp3);
        parameters[count]=tmp;
        count++;
    }

    for (int i = 0; i < matrixGamma1.size(); ++i) {
        Parameters tmp;
        double tmp1=fRand(matrixGamma1[i][0],matrixGamma1[i][1]);
        //std::cout <<tmp1<< std::endl;
        tmp.addParameters(tmp1);
        double tmp2=fRand(matrixGamma1[i][2],matrixGamma1[i][3]);
        //std::cout <<tmp2<< std::endl;
        tmp.addParameters(tmp2);
        double tmp3=fRand(matrixGamma1[i][9],matrixGamma1[i][10]);
        //std::cout <<tmp3<< std::endl;
        tmp.addParameters(tmp3);
        parameters[count]=tmp;
        count++;

    }
    for (int i = 0; i < matrixGamma2.size(); ++i) {
        Parameters tmp;
        double tmp1=fRand(matrixGamma2[i][0],matrixGamma2[i][1]);
        //std::cout <<tmp1<< std::endl;
        tmp.addParameters(tmp1);
        double tmp2=fRand(matrixGamma2[i][2],matrixGamma2[i][3]);
        //std::cout <<tmp2<< std::endl;
        tmp.addParameters(tmp2);
        double tmp3=fRand(matrixGamma2[i][9],matrixGamma2[i][10]);
        //std::cout <<tmp3<< std::endl;
        tmp.addParameters(tmp3);
        parameters[count]=tmp;
        count++;

    }

    double *kernel;
    int size_kernel;
    double Delta_cr;
    QObject *errorHandler = rootObject->findChild<QObject*>("errorcsvHandler");
    int errorRain = HandlerCSV::loadCSVKernel(sfileurl,kernel,size_kernel,Delta_cr, errorHandler);
    //HandlerCSV::loadCSVKernel(sfileurl,kernel,size_kernel,Delta_cr,errorRain);
    RegressionController * regressionController= new RegressionController(
                _projectaname.toString(),
                percantageW,
                percantageLinearA,
                percantageLinearB,
                percantageGammaA,
                percantageGammaB,
                weight,
                dimension,
                functionType,
                dimension,
                parameters,
                dimension,
                size_kernel,
                kernel,
                ielitist,
                ipopulationSize,
                imaxGeneration,
                dpercentageCrossover,
                dpercentageMutation,
                inumberProcessor,
                translation,
                typeReplacement.toInt(),
                para1.toInt(),
                para2.toInt(),
                typeReplacement.toInt(),
                selection.toString()
                );

    std::vector< double> x;
    std::vector< double> y;

    ControlPoints * controlPoints = new ControlPoints();
    //TODO
    if(checkControlPointsBool)
    {
        controlPoints->calculateControlPoints(kernel,size_kernel);
        x = controlPoints->getX();
        y = controlPoints->getY();
    }else
        if(checkKernelBool){
            std::vector< double> tmp(kernel,kernel+size_kernel);
            y = tmp;
            for(int i=0; i< size_kernel; i++){
                x.push_back(i+1);
            }
        }else
            if(checkNBool){
                if( checkControlPointsWithNBool){
                    controlPoints->calculateControlPoints(kernel,size_kernel);
                    controlPoints->getSubdividePointsFromControlPoints(controlPoints->getX(),controlPoints->getY(),n,x,y);
                }else
                {
                    controlPoints->calculateControlPoints(kernel,size_kernel);
                    controlPoints->getSubdividePointsFromKernel(kernel,size_kernel,n,x,y);
                }

            }

    delete controlPoints;

    qCustomPlotRegression->setX(x);


    regressionController->setQCustomPlotRegression(qCustomPlotRegression);
    qCustomPlotRegression->setupQuadraticDemo(&y[0],y.size(),&x[0],x.size());
    regressionController->setX(x);
    regressionController->setY(y);

    regressionController->setProgressBar(progressBar);
    regressionController->setCurrentAverageFitness(currentAverageFitness);
    regressionController->setCurrentMaximumFitness(currentMaximumFitness);
    regressionController->setAbsoluteAverageFitness(absoluteAverageFitness);
    regressionController->setAbsoluteMaximumFitness(absoluteMaximumFitness);
    regressionController->setUpdate(update);
    //FINE
    QObject::connect(buttonStop, SIGNAL(clicked()),regressionController, SLOT( stopThread()));
    //eseguo l'algoritmo genetico e setto il segnale di stop

    regressionController->startThread();
    threadsController.push_back(regressionController);
}
Ejemplo n.º 26
0
/**
 * In this example we will perform a classical inverse dynamics on tree structured robot.
 * We will load the kinematic and dynamic parameters of the robot from an URDF file.
 */
int main(int argc, char** argv)
{
    if(argc != 2)
    {
        std::cerr << "tree_inverse_dynamics example usage: ./tree_inverse_dynamics robot.urdf" << std::endl;
        return EXIT_FAILURE;
    }

    std::string urdf_file_name = argv[1];

    //We are using the kdl_format_io library for loading the URDF file to a KDL::Tree object, but if
    //you use ROS you can  use the kdl_parser from the robot_model package (but please note that
    //there are some open issues  with the robot_model kdl_parser : https://github.com/ros/robot_model/pull/66 )
    KDL::Tree my_tree;
    bool urdf_loaded_correctly = iDynTree::treeFromUrdfFile(urdf_file_name.c_str(),my_tree);

    if( !urdf_loaded_correctly )
    {
        std::cerr << "Could not generate robot model and extract kdl tree" << std::endl;
        return EXIT_FAILURE;
    }

    //We will now create a tree inverse dynamics solver
    //This solver performs the classical inverse dynamics
    //so there is a link called floating base that is the one for
    //which the velocity and the acceleration is specified, and
    //where unknown external wrench is assumed applied.
    //The floating base is by default the base link of the URDF, but
    //can be changed with the changeBase method

    KDL::CoDyCo::TreeIdSolver_RNE rne_solver(my_tree);

    //The input variables are :
    // - Joint positions, velocities, accelerations.
    int n_dof = rne_solver.getUndirectedTree().getNrOfDOFs();
    KDL::JntArray q_j(n_dof), dq_j(n_dof), ddq_j(n_dof);

    // - Floating base velocity and (proper) acceleration.
    //   The proper acceleration is the sum of the classical and gravitational acceleration,
    //   i.e. the acceleration that you get reading the output of linear accelerometer.
    KDL::Twist v_base, a_base;

    // - External wrenches applied to the link. This wrenches are expressed in the local reference frame of the link.
    int n_links =  rne_solver.getUndirectedTree().getNrOfLinks();
    std::vector<KDL::Wrench> f_ext(n_links,KDL::Wrench::Zero());

    //The output variables are :
    // - Joint torques.
    KDL::JntArray torques(n_dof);

    // - The base residual wrench (mismatch between external wrenches in input and the model).
    KDL::Wrench f_base;

    //We populate the input variables with random data
    srand(0);
    for(int dof=0; dof < n_dof; dof++)
    {
        q_j(dof) = fRand(-10,10);
        dq_j(dof) = fRand(-10,10);
        ddq_j(dof) = fRand(-10,10);
    }

    //We fill also the linear part of the base velocity
    //but please note that the dynamics is indipendent from it (Galilean relativity)
    for(int i=0; i < 6; i++ )
    {
        v_base[i] = fRand(-10,10);
        a_base[i] = fRand(-10,10);
    }

    //For setting the input wrenches, we first get the index for the link for which we want to set the external wrench.
    //In this example we assume that we have measures for the input wrenches at the four end effectors (two hands, two legs)
    //We use the names defined in REP 120 ( http://www.ros.org/reps/rep-0120.html ) for end effector frames
    //but please change the names if you want to use a different set of links
    int r_gripper_id =  rne_solver.getUndirectedTree().getLink("r_gripper")->getLinkIndex();
    int l_gripper_id =  rne_solver.getUndirectedTree().getLink("l_gripper")->getLinkIndex();
    int r_sole_id =  rne_solver.getUndirectedTree().getLink("r_sole")->getLinkIndex();
    int l_sole_id =  rne_solver.getUndirectedTree().getLink("l_sole")->getLinkIndex();

    for(int i=0; i < 6; i++ )
    {
        f_ext[r_gripper_id][i] = fRand(-10,10);
        f_ext[l_gripper_id][i] = fRand(-10,10);
        f_ext[r_sole_id][i] = fRand(-10,10);
        f_ext[l_sole_id][i] = fRand(-10,10);
    }

    //Now that we have the input, we can compute the inverse dynamics
    int inverse_dynamics_status = rne_solver.CartToJnt(q_j,dq_j,ddq_j,v_base,a_base,f_ext,torques,f_base);

    if( inverse_dynamics_status != 0 )
    {
        std::cerr << "There was an error in the inverse dynamics computations" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "Torque computed successfully. " << std::endl;
    std::cout << "Computed torques : " << std::endl;
    for(int dof=0; dof < n_dof; dof++ )
    {
        std::cout << torques(dof) << " ";
    }
    std::cout << std::endl;

    return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
BCellListHd captureDenseCellsIncludingNeighbors(GHdrNd GridRTree1,BCellListHd cellsList,BCellListHd denseCellsList)
{
	BCellListNode currBCellListNode = denseCellsList->first;
	BCellListNode tempBCellListNode;
	BCell currBCell;
	CellData currCellData;
	int counter=0;
	int i;
	double randCoords[DIMENSION];

	BCellListHd nbhCellsList = initBCellListHd();
	
	while(currBCellListNode!=NULL)
	{
		Region cellRgn = createRegionofCell(currBCellListNode->bCellElem);
		cellRgn=getEpsExtendedRegion(cellRgn,CELLSIZE);
		BCellListHd cellNbhCells = GgetCellsInRegion(GridRTree1,cellRgn,NULL);

		tempBCellListNode = cellNbhCells->first;;

		while(tempBCellListNode!=NULL)
		{

			currBCell = tempBCellListNode->bCellElem;

			if(currBCell->cellDataList->count < 10000)
			{
				counter = abs(10000 - currBCell->cellDataList->count);

	 			while(counter > 0)
	 			{
	 				for(i = 0; i<DIMENSION; i++)
		 			{
		 				randCoords[i] = fRand(currBCell->minOriginalBoundary[i], currBCell->maxOriginalBoundary[i]);
		 			}

		 			Data currData = (Data) malloc(sizeof(*currData));
		 			currData->iData = (DataPoint) malloc(DIMENSION *sizeof(dataPoint));
		 			for(i=0;i<DIMENSION;i++)
		 			{
		 				currData->iData[i] = randCoords[i];
		 			}

		 			insertPointintoBCell(currBCell,currData);
		 			counter--;
	 			}



				// currCellData = currBCell->cellDataList->first;

				// while(currBCell->cellDataList->count > 20)
	 		// 	{
	 		// 		currCellData = currCellData->next;
	 		// 		currBCell->cellDataList->count--;
	 		// 	}

	 			//currBCell->cellDataList->first = currCellData;

			}
			//insertBCellIntoBCellList(tempBCellListNode->bCellElem,nbhCellsList);
			tempBCellListNode = tempBCellListNode->next;
		}

		currBCellListNode = currBCellListNode->next;
	}	

	return cellsList;

}
Ejemplo n.º 28
0
TEST ( Function1d_Test, RandomConstructorRange){
	double X0=fRand(-100,100);
	double X1=fRand(-100,100);
	Function1d fun(X0,X1);
	EXPECT_DOUBLE_EQ(fun.LimitsRange(), X1-X0);
}
Ejemplo n.º 29
0
void ScatteredLineBrush::BrushMove(const Point source, const Point target)
{
	ImpressionistDoc* pDoc = GetDocument();
	ImpressionistUI* dlg = pDoc->m_pUI;

	if (pDoc == NULL) {
		printf("LineBrush::BrushMove  document is NULL\n");
		return;
	}

	int size = pDoc->getSize();
	int angle = pDoc->getAngle();
	double opacity = pDoc->getOpac();
	int strokeDirChoice = dlg->m_StrokeDirChoice->value();

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	srand(time(0));
	glMatrixMode(GL_MODELVIEW);
	
	switch (strokeDirChoice){
	// Slider/Right mouse 
	case 0:
		// don't have to change size and angle value
		for (int i = 0; i < 4; i++){
			float length = fRand(1, size / 2)*2.5;
			float dist = fRand(-size*0.3, size*0.3)*2.5;
			float displacement = fRand(-size*0.75, size*0.75);
			float x1 = target.x + displacement;
			float y1 = target.y + dist;

			glPushMatrix();
				glTranslatef(x1, y1, 0.0);
				glRotatef(angle, 0.0, 0.0, 1.0);
				glTranslatef(-x1, -y1, 0.0);
				glBegin(GL_LINE_STRIP);
					SetColorOpac(Point(source.x + displacement, source.y + dist), opacity);
					glVertex2d(x1 - length*0.75, y1);
					glVertex2d(x1 + length*0.75, y1);
				glEnd();
			glPopMatrix();
		}
		break;

	// Gradient
	case 1:
		// change angle value according to 
		// the gradient at this point
		for (int i = 0; i < 4; i++){
			float length = fRand(1, size / 2)*2.5;
			float dist = fRand(-size*0.3, size*0.3)*2.5;
			float displacement = fRand(-size*0.75, size*0.75);
			float x1 = target.x + displacement;
			float y1 = target.y + dist;
			double Gx;
			double Gy;
			GLubyte color[3][3][3];
			double intensity[3][3];
			for (int i = -1; i < 2; i++){
				for (int j = -1; j < 2; j++){
					memcpy(color[i + 1][j + 1], pDoc->GetOriginalPixel(Point(source.x + displacement + i, source.y + dist + j)), 3);
					intensity[i + 1][j + 1] = 0.299*color[i + 1][j + 1][0] + 0.587*color[i + 1][j + 1][1] + 0.144*color[i + 1][j + 1][2];
				}
			}
			Gx = intensity[0][0] * (-1) + intensity[0][1] * (-2) + intensity[0][2] * (-1)\
				+ intensity[2][0] * (1) + intensity[2][1] * (2) + intensity[2][2] * (1);
			Gy = intensity[0][0] * (-1) + intensity[1][0] * (-2) + intensity[2][0] * (-1)\
				+ intensity[0][2] * (1) + intensity[1][2] * (2) + intensity[2][2] * (1);
			angle = -(int)(atan2(Gy, Gx)*57.32) % 360;

			glPushMatrix();
				glTranslatef(x1, y1, 0.0);
				glRotatef(angle, 0.0, 0.0, 1.0);
				glTranslatef(-x1, -y1, 0.0);
				glBegin(GL_LINE_STRIP);
					SetColorOpac(Point(source.x + displacement, source.y + dist), opacity);
					glVertex2d(x1 - length*0.75, y1);
					glVertex2d(x1 + length*0.75, y1);
				glEnd();
			glPopMatrix();
		}
		break;

	// Brush direction
	case 2:
		current.x = target.x;
		current.y = target.y;
		if (prev.x!=-1&&current.x!=-1&&(current.x != prev.x || current.y != prev.y)){
			int dx = current.x - prev.x;
			int dy = current.y - prev.y;
			angle = (int)(atan2(dy, dx)*57.32) % 360;

			
			
			for (int i = 0; i < 4; i++){
				float length = size;
				float dist = fRand(-size*0.3, size*0.3)*2.5;
				float displacement = fRand(-size*0.75, size*0.75);
				float x1 = target.x + displacement;
				float y1 = target.y + dist;

				glPushMatrix();
				glTranslatef(x1, y1, 0.0);
				glRotatef(angle, 0.0, 0.0, 1.0);
				glTranslatef(-x1, -y1, 0.0);
				glBegin(GL_LINE_STRIP);
				SetColorOpac(Point(source.x + displacement, source.y + dist), opacity);
				glVertex2d(x1 - length*0.75, y1);
				glVertex2d(x1 + length*0.75, y1);
				glEnd();
				glPopMatrix();
			}
		}
		prev.x = current.x;
		prev.y = current.y;
		break;

	default:
		break;

	}
	
}
Ejemplo n.º 30
0
int main(int argc, char const *argv[])
{
	char* s;
	std::srand(std::time(0)); //use current time as seed for random generator
	int r = rand() % 1000;
	for(int i = 0; i < r; i++)
	{
		rand();
	}
	if(argc < 3)
	{
		return 1;
	}
	
	int forestSize = strtol(argv[1], &s, 10);
	int iterations = strtol(argv[2], &s, 10);

	double SIDE = std::sqrt(forestSize);
	SIDE = fRand(std::sqrt(SIDE),std::sqrt(2)*SIDE);
	double R = 1;

	double begin, end;

	std::vector<int> empty;

	std::vector<Tree*> Forest;
	std::vector< std::vector<int> > neighbors(forestSize,empty);
	std::vector<double> metrics(forestSize,0.0);

	int num_threads;

	std::vector<int> systems_processed; // DEBUG
    std::vector<int> symbols_translated; // DEBUG

///// PARALLEL BLOCK
	begin = omp_get_wtime();
	#pragma omp parallel shared(Forest,neighbors,metrics,num_threads)
	{
		#pragma omp master
		{
			// INIT VARIABLES
			std::vector<Point> positions;

			num_threads = omp_get_num_threads();
			std::cout << "Running " << forestSize << " trees for " << iterations << " iterations on " << num_threads << " processors" << std::endl;
			
			for(int i = 0; i < forestSize; i++)
			{
				double x = fRand(0,SIDE);
				double y = fRand(0,SIDE);
				Point p = {x,y};
				Tree *T = new MonopodialTree();
				Forest.push_back(T);
				positions.push_back(p);
				for(int j = 0 ; j < i ; j++)
				{
					Point q = positions[j];
					if(pointDistance(p,q) < R)
					{
						neighbors[j].push_back(i);
						neighbors[i].push_back(j);
					}
				}
			}

			systems_processed = std::vector<int>(num_threads,0); //DEBUG
			symbols_translated = std::vector<int>(num_threads,0); //DEBUG
		}

		#pragma omp barrier

		int thread_num = omp_get_thread_num();
		// ITERATE
		for(int j = 0 ; j < iterations ; j++)
		{
			#pragma omp for schedule(dynamic)
			for(int i = 0; i < Forest.size() ; i++)
			{
				Forest[i]->next();
				double metric = Forest[i]->calculateMetric();
				metrics[i] = metric;
				systems_processed[thread_num]++; //DEBUG
				symbols_translated[thread_num] += Forest[i]->getState().size(); //DEBUG
			}

			#pragma omp for schedule(dynamic)
			for(int i = 0; i < Forest.size() ; i++)
			{
				Forest[i]->updateMetric(metrics,neighbors[i]);
			}
		}
	}
///// PARALLEL BLOCK
	end = omp_get_wtime();

	std::vector< std::vector<int> > connected_components = get_connected_components(neighbors);
	// print_forest(Forest, neighbors, metrics); // VERBOSE
	// print_connected_components( connected_components); // VERBOSE


	char buffer[80];

	FILE *f = fopen("Results_naive.txt", "a");
	if(f != NULL)
	{
	    fprintf(f, "%s\n", gettime(buffer));
	    fprintf(f,"%d threads\n",num_threads);
	    fprintf(f,"%d trees\n",forestSize);
	    fprintf(f,"%d iterations\n",iterations);
	    fprintf(f,"%lf %lf\n",SIDE,R);
	    for(int i = 0; i < connected_components.size(); i++)
	    {
	    	fprintf(f, "%d ", connected_components[i].size());
	    }
	    fprintf(f, "\n");
	    fprintf(f,"Proc   Systems   Symbols\n");//DEBUG
	    for(int i = 0; i < num_threads; i++)//DEBUG
	    {//DEBUG
	        fprintf(f,"  %02d  %03d  %03d\n",i,systems_processed[i],symbols_translated[i]);//DEBUG
	    }//DEBUG
	    fprintf(f,"Time : %f seconds\n", end-begin);
	    fprintf(f,"\n=====================\n");
	}

	for(int i = 0; i < Forest.size() ; i++)
	{
		delete Forest[i];
	}


	return 0;
}