//void fullBirthStageTest() {
TEST(fullBirthStageTest,fullBirthStageTest_OK){
    int numSubpopulations = 100;    //***changed numSubpopulations to 100***
    vector<double> meanCommunityCultureValues(numSubpopulations);
    vector<vector<Agent> > NP(numSubpopulations);
    vector<vector<Agent> > P(numSubpopulations);


	/*Birth Parameters*/

	int minPopsize = 10; /*Maximum popsize when no adaptive knowledge*/
	double fecundityCurvature = 10;
	double growthRateR = 0.04*20; //should vary between 0.005 and 0.04 multiplied by generation length
	double geneticMutationRate = 0.001;
	int brainMutationValue = 1;

	/*Learning Parameters*/
	double adaptKnowDeviation = 0.1;
	double lossyLearningValue = .9; //0 = Complete loss, 1 = No loss
	double obliqueLearningDeviation = 0.5;
	double learningBiasDeviation = 0.5;
	double indivLearningDeviation = 0.5;
	double indivLearningMean = 0.5;

	/*Migration Parameters*/
	double migrationRate = 0.1;

	/*Selection Parameters*/
	double maxBrainCost = 20;
	double deathRateLambda = 1.0;

	/*Initial values*/
	int initBrain = 1;
	double initAdaptKnowledge = 0.0;
	double initIndivLearning = 1.0; //0 = complete social learner, 1 = complete individual learner
	double initObliqueLearning = 0.0;
	double initLearningBias = 0.0;
	double initPopSize = 10;

    initializePopulation(numSubpopulations, initPopSize, initBrain,
			initIndivLearning, initObliqueLearning, initLearningBias,initAdaptKnowledge, P);

    birthStage(numSubpopulations, P, meanCommunityCultureValues,
				growthRateR, minPopsize, fecundityCurvature, geneticMutationRate,
				brainMutationValue, indivLearningDeviation, obliqueLearningDeviation,
				learningBiasDeviation, lossyLearningValue, adaptKnowDeviation,
				indivLearningMean, NP);

ASSERT_FALSE(NP.empty());
ASSERT_EQ(NP.size(), P.size());
ASSERT_TRUE(meanCommunityCultureValues.size() == numSubpopulations);



}
void EvolutionaryAlgorithm::run()
{
	initializePopulation();
	bool goal = false;
	for (int generation = 0; (generation < numberOfGenerations) && !goal; generation++)
	{
		setDeaths();
		int newDeaths = getNumberOfDeaths();
		int newChildren = numChildren + newDeaths;
		for (int childNumber = 0; childNumber < newChildren; childNumber++)
		{
			Individual child(selectRandomParent(), selectRandomParent(), numberOfGenes);

			if ((rand() % 1000) < (mutationRate * 1000))
			{
				child.mutateIndividual(typesOfCoins);
			}
			child.evaluateIndividual(targetValue);
			currentPopulation.push_back(child);
		}

		sort(currentPopulation.begin(),  currentPopulation.end());
		selectSurvivors();
		currentPopulation.clear();
		currentPopulation = survivors;
		survivors.clear();
		sort(currentPopulation.begin(),  currentPopulation.end());
		print(generation, newDeaths);
		if (generation % 10 == 0)
		{
			cout << endl;
			system("PAUSE");
			cout << endl;
		}
		if(currentPopulation[0].getFitnessLevel() == 0)
		{
			goal = true;
			cout << endl << "GOAL REACHED\n";
			system("PAUSE");
			cout << endl;
			return ;
		}
	}
}
Beispiel #3
0
/*
 * The call to wb_robot_step is mandatory for the function
 * supervisor_node_was_found to be able to work correctly.
 */
static void reset(void)
{
	int i;
	for(i=0; i<POP_SIZE; i++) fitness[i]=-1;
	srand(time(0));
	pF1= fopen("initPop.txt","w+");
	//pF2= fopen("real2IntGenome.txt","w+");
	//pF3= fopen("encodedPop.txt","w+");
	// Initiate the emitter used to send genomes to the experiment
	emitter = wb_robot_get_device("emittersupervisor");

	// Initiate the receiver used to receive fitness
	receiver = wb_robot_get_device("receiversupervisor");
	wb_receiver_enable(receiver, TIME_STEP);

	// Create a supervised node for the robot
	robot = wb_supervisor_node_get_from_def("EPUCK");
	assert(robot!=NULL);
	pattern=wb_supervisor_node_get_from_def("FLOOR");
	pattern_rotation = wb_supervisor_node_get_field(pattern,"rotation");
	assert(pattern!=NULL);
	assert(pattern_rotation!=NULL);


	trans_field = wb_supervisor_node_get_field(robot,"translation");
	rot_field = wb_supervisor_node_get_field(robot,"rotation");
	ctrl_field= wb_supervisor_node_get_field(robot,"controller");

	wb_robot_step(0);
	wb_robot_step(0); //this is magic

	// set the robot controller to nn
	const char *controller_name = "drive2";
	wb_supervisor_field_set_sf_string(ctrl_field,controller_name);

	//check whether robot was found
	if (wb_supervisor_node_get_type(robot) == WB_NODE_NO_NODE)
		puts("Error: node EPUCK not found!!!");

	if(EVOLVING) {
		//Open log files
		f1= fopen ("../../data/fitness.txt", "wt");
		f2= fopen ("../../data/genomes.txt", "wt");
		//pR= fopen("savePop.txt","w+");

		//initial weights randomly
		initializePopulation();
		//rtoi(); //real to int conversion before encoding
		popEncoder();


		//puts("NEW EVOLUTION");
		//puts("GENERATION 0");

		// send genomes to experiment
		resetRobotPosition();
		wb_emitter_send(emitter, (void *)pop_bin[evaluated_inds], GENOME_LENGTH*sizeof(_Bool));
		//instead save binary genomes to a file
		//puts("Genes sent.");
	}
	else {
		// testing best individual
		// Read best genome from bestgenome.txt and initialize weights.
		f3= fopen ("../../data/bestgenome.txt", "rt");
		fscanf(f3,"%d %d", &generation, &evaluated_inds);

		//TODO either read binary genome or make sure it is decoded prior to storage
		for(i=0;i<GENOME_LENGTH;i++) fscanf(f3,"%d ",&pop_bin[0][i]);

		//printf("TESTING INDIVIDUAL %d, GENERATION %d\n", evaluated_inds, generation);

		// send genomes to experiment
		resetRobotPosition();
		// wb_emitter_send(emitter, (void *)pop[0], NB_GENES*sizeof(double));
	}
	return;
}
// test that agents with high learning bias pick smarter agents to learn from
TEST(learningStageTest, learningBiasAffects) {

 int numSubpopulations = 100;
    vector<double> meanCommunityCultureValues(numSubpopulations);
    vector<vector<Agent> > NP(numSubpopulations);
    vector<vector<Agent> > P(numSubpopulations);

	/*Birth Parameters*/
	int minPopsize = 10; /*Maximum popsize when no adaptive knowledge*/
	double fecundityCurvature = 10;
	double growthRateR = 0.04*20; //should vary between 0.005 and 0.04 multiplied by generation length
	double geneticMutationRate = 0.0;


	/*Learning Parameters*/
	double adaptKnowDeviation = 0.5;
	double lossyLearningValue = 1; //0 = Complete loss, 1 = No loss
	double obliqueLearningDeviation = 0;
	double learningBiasDeviation = 0;
	double indivLearningDeviation = 0;
	double brainMutationDeviation = 0;
	double indivLearningMean = 1;

	/*Migration Parameters*/
	double migrationRate = 0.1;

	/*Selection Parameters*/
	double maxBrainCost = 20;
	double deathRateLambda = 1.0;

	/*Initial values*/
	double initBrain = 400;
	double initAdaptKnowledge = 200;
	double initIndivLearning = 0.0; //0 = complete social learner, 1 = complete individual learner
	double initObliqueLearning = 1;
	double initLearningBias = 0.0;
	double initPopSize = 50;

initializePopulation(numSubpopulations, initPopSize, initBrain,
			initIndivLearning, initObliqueLearning, initLearningBias,
			initAdaptKnowledge, P);

birthStage(numSubpopulations, P, meanCommunityCultureValues,
				growthRateR, minPopsize, fecundityCurvature, geneticMutationRate,
				brainMutationDeviation, indivLearningDeviation, obliqueLearningDeviation,
				learningBiasDeviation, lossyLearningValue, adaptKnowDeviation,
				indivLearningMean, NP);

learningStage(numSubpopulations, NP, P, meanCommunityCultureValues,
              lossyLearningValue, adaptKnowDeviation,indivLearningMean);

double NPcultureValueLOW = 0;

for (int p = 0; p < numSubpopulations; p++) {
		for (int a = 0; a < NP[p].size(); a++) {

NPcultureValueLOW = NP[p][a].getCulture() + NPcultureValueLOW;
            }
    }



// now test for larger LB to see affects

int numSubpopulations1 = 100;
    vector<double> meanCommunityCultureValues1(numSubpopulations);
    vector<vector<Agent> > NP1(numSubpopulations);
    vector<vector<Agent> > P1(numSubpopulations);

    /*Birth Parameters*/
	int minPopsize1 = 10; /*Maximum popsize when no adaptive knowledge*/
	double fecundityCurvature1 = 10;
	double growthRateR1 = 0.04*20; //should vary between 0.005 and 0.04 multiplied by generation length
	double geneticMutationRate1 = 0.0;

	/*Learning Parameters*/
	double adaptKnowDeviation1 = 0.5;
	double lossyLearningValue1 = 1; //0 = Complete loss, 1 = No loss
	double obliqueLearningDeviation1 = 0;
	double learningBiasDeviation1 = 0;
	double indivLearningDeviation1 = 0;
	double brainMutationDeviation1 = 0;
	double indivLearningMean1 = 1;

	/*Migration Parameters*/
	double migrationRate1 = 0.1;

	/*Selection Parameters*/
	double maxBrainCost1 = 20;
	double deathRateLambda1 = 1.0;

	/*Initial values*/
	double initBrain1 = 400;
	double initAdaptKnowledge1 = 200;
	double initIndivLearning1 = 0.0; //0 = complete social learner, 1 = complete individual learner
	double initObliqueLearning1 = 1;
	double initLearningBias1 = 1000.0;
	double initPopSize1 = 50;


initializePopulation(numSubpopulations1, initPopSize1, initBrain1,
			initIndivLearning1, initObliqueLearning1, initLearningBias1,
			initAdaptKnowledge1, P1);

birthStage(numSubpopulations1, P1, meanCommunityCultureValues1,
				growthRateR1, minPopsize1, fecundityCurvature1, geneticMutationRate1,
				brainMutationDeviation1, indivLearningDeviation1, obliqueLearningDeviation1,
				learningBiasDeviation1, lossyLearningValue1, adaptKnowDeviation1,
				indivLearningMean1, NP1);

learningStage(numSubpopulations1, NP1, P1, meanCommunityCultureValues1,
              lossyLearningValue1, adaptKnowDeviation1, indivLearningMean1);


double NPcultureValueHIGH = 0;

for (int p = 0; p < numSubpopulations1; p++) {
		for (int a = 0; a < NP1[p].size(); a++) {

NPcultureValueHIGH = NP1[p][a].getCulture() + NPcultureValueHIGH;
            }
    }

ASSERT_TRUE(NPcultureValueHIGH > NPcultureValueLOW);


}
TEST(learningStageTest, learningStageTest_OK) {

    int numSubpopulations = 100;
    vector<double> meanCommunityCultureValues(numSubpopulations);
    vector<vector<Agent> > NP(numSubpopulations);
    vector<vector<Agent> > P(numSubpopulations);

	/*Birth Parameters*/
	int minPopsize = 10; /*Maximum popsize when no adaptive knowledge*/
	double fecundityCurvature = 10;
	double growthRateR = 0.04*20; //should vary between 0.005 and 0.04 multiplied by generation length
	double geneticMutationRate = 0.001;

	/*Learning Parameters*/
	double adaptKnowDeviation = 0.1;
	double lossyLearningValue = .9; //0 = Complete loss, 1 = No loss
	double obliqueLearningDeviation = 0.5;
	double learningBiasDeviation = 0.5;
	double indivLearningDeviation = 0.5;
	double brainMutationDeviation = 0.5;
	double indivLearningMean = 0.5;

	/*Migration Parameters*/
	double migrationRate = 0.1;

	/*Selection Parameters*/
	double maxBrainCost = 20;
	double deathRateLambda = 1.0;

	/*Initial values*/
	double initBrain = 1;
	double initAdaptKnowledge = 0.0;
	double initIndivLearning = 1.0; //0 = complete social learner, 1 = complete individual learner
	double initObliqueLearning = 0.0;
	double initLearningBias = 5.0;
	double initPopSize = 10;

initializePopulation(numSubpopulations, initPopSize, initBrain,
			initIndivLearning, initObliqueLearning, initLearningBias,
			initAdaptKnowledge, P);

birthStage(numSubpopulations, P, meanCommunityCultureValues,
				growthRateR, minPopsize, fecundityCurvature, geneticMutationRate,
				brainMutationDeviation, indivLearningDeviation, obliqueLearningDeviation,
				learningBiasDeviation, lossyLearningValue, adaptKnowDeviation,
				indivLearningMean, NP);


vector<vector<Agent> > PopulationPreLearning(NP);

learningStage(numSubpopulations, NP, P, meanCommunityCultureValues,
              lossyLearningValue, adaptKnowDeviation,indivLearningMean);

vector<vector<Agent> > PopulationPostLearning(NP);

ASSERT_FALSE(NP.empty());
ASSERT_EQ(NP.size(), P.size());

//test that culture of agents are greater than/equal to original culture
for (int p = 0; p < numSubpopulations; p++) {
		for (int a = 0; a < NP[p].size(); a++) {

ASSERT_TRUE(PopulationPostLearning[p][a].getCulture() >= PopulationPreLearning[p][a].getCulture());
            }
    }

}
int main(int argc, char *argv[])
{
    int ch;
    char *progname = argv[0];

    // read in optional command line arguments
    while ((ch = getopt(argc, argv, "A:C:D:I:L:m:M:N:p:P:q:r:R:s:S:t:T:u:U:w:W:z:Z?")) != -1) {
        switch (ch) {
            case 'A':
                DURATION_ALLOPATRY = atoi(optarg);
                break;
            case 'C':
                CUTOFF = strtod(optarg, (char**)NULL);
                break;
            case 'D':
                DETERMINISTIC = atoi(optarg);
                break;
            case 'I':
                INITIAL_CONDITION = atoi(optarg);
                break;
            case 'L':
                nSITES_PER_WINDOW = atoi(optarg);
                break;
            case 'm':
                MIGRATION_RATE = strtod(optarg, (char **)NULL);
                break;
            case 'M':
                MODEL_TYPE = atoi(optarg);
                break;
            case 'N':
                TOTAL_N = atoi(optarg);
                break;
            case 'p':
                PROB_MUT_BENEFICIAL = strtod(optarg, (char **)NULL);
                break;
            case 'P':
                PROB_MUT_BG = strtod(optarg, (char **)NULL);
                break;
            case 'q':
                PROB_MUT_DIVERGENT = strtod(optarg, (char **)NULL);
                break;
            case 'Q':
                HIGH_RECOMB_PROB_PER_KB = strtod(optarg, (char **)NULL);
                break;
            case 'r':
                LOW_RECOMB_PROB_PER_KB = strtod(optarg, (char **)NULL);
                break;
            case 'R':
                nGENOMIC_REGIONS = atoi(optarg);
                break;
            case 's':
                MEAN_S_BENEFICIAL = strtod(optarg, (char **)NULL);
                break;
            case 'S':
                MEAN_S_BG = strtod(optarg, (char **)NULL);
                break;
            case 't':
                MEAN_S_DIVERGENT = strtod(optarg, (char **)NULL);
                break;
            case 'T':
                TOTAL_GENERATIONS = atoi(optarg);
                break;
            case 'u':
                MU_LOW = strtod(optarg, (char **)NULL);
                break;
            case 'U':
                MU_HIGH = strtod(optarg, (char **)NULL);
                break;
            case 'w':
                WINDOW_SIZE_BASES = atoi(optarg);
                break;
            case 'W':
                nWINDOWS_PER_REGION = atoi(optarg);
                break;
            case 'z':
                MONITOR_PROGRESS = atoi(optarg);
                break;
            case 'Z':
                useShortTestValuesOfParameters();
                break;
            case '?':
            default:
                usage(progname);
                exit(-1);
        }
    }
    
    int *demeIndexes;
    demeIndexes = (int *) malloc( (sizeof(int) * TOTAL_N * nDEMES));
    
    // set up
    RNGsetup();
    initializePopulation();
    openDataRecordingFiles();
    
    
    
    // main operations
    for ( t = 1; t <= TOTAL_GENERATIONS; t++ ) {
        
        if ( t > DURATION_ALLOPATRY )
            migration( demeIndexes );
        
        reproduction( demeIndexes );
        
        calculateMetricsAndStats();
        
        if ( MONITOR_PROGRESS ) {
            if ( t % MONITOR_PROGRESS == 0 )
                fprintf(stdout, "%li\n", t);
        }
    }
    
    
    finalPrints();
    
    // free blocks from malloc
    free(genomeMap);
    free(genotypes);
    free(isVariableSite);
    free(fixedAllele);
    free(alleleFrequenciesByDeme);
    free(alleleSelectionCoeffs);
    free(demeLocations);
    free(demeIndexes);
    free(regionFlags);
    free(windowFlags);
    free(regionMembership);
    free(windowMembership);
    free(mutationRateClass);
    free(alleleFrequencies);
    
    // close files
    fclose(mutationLog);
    fclose(alleleFrequenciesOverTime);
    fclose(fixationLog);
    fclose(piOverTime);
    fclose(DaOverTime);
    fclose(DxyOverTime);
    fclose(variableLociOverTime);
    
    return 0;
}
Beispiel #7
0
void run(char* func_name, int iRun)
{
	iter=0;
	iter_each=0;
	cnArch=0;

	char objsal[256];
	char varsal[256];
	char timesal[256];
	strcpy(testInstance,func_name);

	double start_time,end_time;
	double duration;

	sprintf(objsal,"results/FUN_%s_%d_%d",testInstance,nDim,iRun);
	sprintf(varsal,"results/VAR_%s_%d_%d",testInstance,nDim,iRun);
	sprintf(timesal,"results/TIME_%s_%d",testInstance,nDim);

	if(mpi_rank==0)
		start_time=clock();

	initializeProblem();
	initializePopulation();
// 	showPopulation();
	initializeIndex();
	if(mpi_color)
		evaluatePopInitial();
	MPI_Barrier(MPI_COMM_WORLD);
	if(master_flag)
		collection_initial();
	if(!mpi_color&&mpi_rank_master==mpi_rank_master_archive)
		refineRepertory_generateArchive();
	MPI_Barrier(MPI_COMM_WORLD);
	if(master_flag)
		SynchronizeArchive();
	SynchronizeArchive_one();
// 	refineRepertory_generateArchive_SDE();
// 	showArchive();
// 	showLimits();
	if(mpi_color)
	{
		update_xBest_initial();
		update_xBest_archive();
	}
	MPI_Barrier(MPI_COMM_WORLD);
	iter=nPop*nObj;

// 	for(int i=0;i<mpi_size;i++)
// 	{
// 		if(i==0&&mpi_rank==0)
// 			showArchive();
// 		if(i!=0&&mpi_rank==i)
// 		{
// 			showGlobalBest();
// 			showPopulation();
// 		}
// 		MPI_Barrier(MPI_COMM_WORLD);
// 	}

	while(iter<maxIteration)
	{
		iter_each=0;
		nRep=0;
		if(mpi_color)
		{
			update_objective();
			permIndexes();
		}
		else
		{
			update_archive();
			perm_archIndex();
		}
		MPI_Barrier(MPI_COMM_WORLD);
// 		showGlobalBest();
		if(master_flag)
		{
			collect2master_archive();
			if(mpi_rank_master==mpi_rank_master_archive)
				refineRepertory_generateArchive();
			SynchronizeArchive();
		}
		SynchronizeArchive_one();
		if(mpi_color)
			update_xBest_archive();
// 		showArchive();
		MPI_Barrier(MPI_COMM_WORLD);
		update_iteration();
	}

	if(mpi_rank==0)
	{
		end_time=clock();
		duration=(end_time-start_time)/CLOCKS_PER_SEC;
	}

	if(mpi_rank==0)
	{
		fpttime=fopen(timesal,"a");
		fprintf(fpttime, "%e\n", duration);

		get_nonDominateSize();

		fptobj=fopen(objsal,"w");
		save_obj(fptobj);

		fptvar=fopen(varsal,"w");
		save_var(fptvar);

		fclose(fpttime);
		fclose(fptobj);
		fclose(fptvar);
	}
}
Beispiel #8
0
void run(int iRun)
{
	double t_ini, t_fin;
	double secs;

	char evalsal[50];//={"results/Evaluations_"};
	char timesal[50];//={"results/Time_"};
	char sizesal[50];//={"results/Size_"};
	char funsal[50];//={"results/FUN_"};
	char varsal[50];//={"results/VAR_"};
	int evaluations;

	numRest = 0;
	cycle = 0;
	gen = 0;

	sprintf(evalsal,"results/Evaluations_%s_%d",problemInstance,D);
	sprintf(timesal,"results/Time_%s_%d",problemInstance,D);
	sprintf(sizesal,"results/Size_%s_%d",problemInstance,D);
	sprintf(funsal,"results/FUN_%s_%d_%d",problemInstance,D,iRun);
	sprintf(varsal,"results/VAR_%s_%d_%d",problemInstance,D,iRun);

	if(mpi_rank==0)
		t_ini=clock();

	randomize();    
	initializeProblem(problemInstance);    
	initializePopulation();
	synchronize_x_sub_all();
	evaluateSpeciesInitial();

	int i;
	while(cycle<Cycles){
		cycle++;
// 		if(mpi_rank==0)
// 			printf("Cycle:\t%d\n",cycle);

		gen = 0;
		while(gen<Gmax){
			gen++;
			ED_rand_1_bin();
			//species parallel, results differ from original
			evaluatePopulation();
			addSolution();
			selection();
			synchronize_x_sub_all();
		}
	}

	evaluations = cycle * Gmax * numSpecies * NP;

	generateSolutions();	

	if(mpi_rank==0)
	{
		fptx = fopen(funsal,"w");     

		exportNonDominatedPopulationObjetivesValues(finalFitness,sizeSol,fptx);    
		fptv = fopen(varsal,"w");
		exportNonDominatedPopulationSolutionValues(finalSolutions,sizeSol,fptv);

		fptu = fopen(evalsal,"a");
		fprintf(fptu, "%d\n",evaluations);

		fpts = fopen(sizesal,"a");
		fprintf(fpts, "%d\n",sizeSolND);

		if(mpi_rank==0)
			t_fin=clock();

		secs = (t_fin-t_ini)/CLOCKS_PER_SEC;

		fptt = fopen(timesal,"a");
		fprintf(fptt,"%.16g \n", secs);

		fclose(fptx);
		fclose(fptu);
		fclose(fptv);
		fclose(fptt);
		fclose(fpts);
	}
	MPI_Barrier(MPI_COMM_WORLD);
	return;
}