Example #1
0
 void 
   advertdirectory_cpi_impl::sync_set_attribute (saga::impl::void_t & ret, 
                                                 std::string    key, 
                                                 std::string    val)
 {
     instance_data data (this);
     saga::url advert_url;
     advert_url = data->location_.clone();
     saga::url url_path         = advert_url.get_path();
     std::string last           = get_last(advert_url);
     std::string pidstring      = get_parent_id_of_entry(*client_, advert_url);
     std::string node_id_string = get_node_id(*client_, last, pidstring);
     std::vector<Mutation> mutations;
     mutations.push_back(Mutation());
     mutations.back().column = "metakey:" + key;
     mutations.back().value = val;
     client_->mutateRow("metadata", last + "-" + node_id_string, mutations);
     //client_->put("metadata", last + "-" + node_id_string, "metakey:" + key, val);
     mutations.clear();
     mutations.push_back(Mutation());
     mutations.back().column = "entry:node_id";
     mutations.back().value = node_id_string;
     client_->mutateRow("metadata", last + "-" + node_id_string, mutations);
     //client_->put("metadata", last + "-" + node_id_string, "entry:node_id" , node_id_string);
     //SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented);
 }
Example #2
0
Error_Info HBAgent:: Put(GatherDoc const & gd){
	Error_Info errInfo;
    	vector<Mutation> mutations;
	{
    	mutations.push_back(Mutation());
    	mutations.back().column = columnfamily+":md5";
    	mutations.back().value  = gd.md5;
	}
	{
    	mutations.push_back(Mutation());
    	mutations.back().column = columnfamily+":ss";
    	mutations.back().value  = gd.snapshot;
	}
	{
    	mutations.push_back(Mutation());
    	mutations.back().column = columnfamily+":appid";
    	mutations.back().value  = gd.new_appid|gd.old_appid;
	}
	map<string,string> amap;
	int tryTimes=5;
	while(tryTimes--){
		try{
			string rowkey=ict::wde::gbasedata::reverseUrl(gd.url);
			
    			c->mutateRow(collection,rowkey,mutations,amap); 
			errInfo.code=0;
			errInfo.description="Insert an Snapshot Successfully!";
			return errInfo;
		}catch(IOError e){
			errInfo.code=HB_IO_HBASE;
			errInfo.description="HBase Service cannot accept this document: "+gd.url;
			cout<<errInfo.description<<endl;
			return errInfo;
		}catch(IllegalArgument e){
			errInfo.code=HB_INVAID_ARGS;
			errInfo.description="Illegal Argument: "+gd.url;
			cout<<errInfo.description<<endl;
			return errInfo;
		}
		catch(TException e){
			cout<<e.what()<<endl;
			errInfo=conn();
			if(errInfo.code!=0){
				cout<<errInfo.description<<endl;
				return errInfo;
			}
		}
	}
	errInfo.code=HB_IO_HBASE;
	errInfo.description="Could not write doc to HBase";
	return errInfo;	
}
Example #3
0
static void
writeRowFunc(std::string t, char rowbuf[ROW_SIZE], char colbuf[COLUMN_SIZE], char valbuf[VALUE_SIZE], HbaseClient client, HPacket *hpacket)
{
    std::vector<Mutation> mutations;
	std::string row(rowbuf);
	std::string column(colbuf);
	std::string value(valbuf);
	const std::map<Text, Text>  dummyAttributes; // see HBASE-6806 HBASE-4658
	int i = 1;

    mutations.clear();
    mutations.push_back(Mutation());
	mutations.back().column = "entry:" + column;
	// mutations.back().column = column;
	mutations.back().value = value;
    //mutations.back().column = "entry:num";
    // mutations.back().value = boost::lexical_cast<std::string>(i);
    // mutations.push_back(Mutation());
    // mutations.back().column = "entry:sqr";
    // mutations.back().value = boost::lexical_cast<std::string>(i*i);
    // std::cout << "row:" << row << "column:" << column << "value:" << value << std::endl;
    client.mutateRow(t, row, mutations, dummyAttributes);
	// mutateRowTsは、最新を上書きせずに更新
    // client.mutateRowTs(t, row, mutations, 1, dummyAttributes); // shouldn't override latest
}
Example #4
0
///////////////////////////////  INTERFACE  ////////////////////////////////
void GeneticClass::Interface(){
	lc = 10000;             
	int algorithmIteration = 30;
	float crossoverRatio = 0.9;
	int mutationIteration = 1000;

	int score = 0, parent1, parent2;

	DrawingPopulation();
	Rating();
	cout << "Rodzice: " << bestScoreInAll << endl;
	checksRepeatsInSet();

	////////////// SELEKCJA I KRZYZOWANIE I MUTACJA///////////////////////////////
	for (int z = 0; z<algorithmIteration; z++){
		int P = -1;		                            // licznik nowej populacji
		vector<bool> crossed(lc,false);
		int crossoverIterations = (lc - 2) * crossoverRatio;
		#pragma omp parallel for
		for (P = -1; P < crossoverIterations; P += 2)
		{
			parent1 = TournamentSelection(10);
			do
				parent2 = TournamentSelection(10);
			while (parent1 == parent2);
			crossed[parent1] = true;
			crossed[parent2] = true;
			Crossover(parent1, parent2, children[P + 1], children[P + 2]);
		}

		for (int i = 0 ; i < lc; i++) {					//Dopisuje do children osobniki ktore nie braly udzialu w krzyzowaniu
			if (crossoverIterations != lc) {
				if (crossed[i] == false) {
					children[crossoverIterations++] = chromosom[i];
				}
			}
			else {
				break;
			}
		}

		chromosom.swap(children);						
		
		for (int i = 0; i<mutationIteration; i++){
			int target = TournamentSelection(100);
			Mutation(chromosom[target]);			//	przy zakomentowanym krzyzowaniu wpisalem tu chromosom zamiast children 
		}

		checksRepeatsInSet();
	
		score = Rating();
		cout << "Populacja_" << z << " = " << score << endl;
	}
	showBest();
}
Example #5
0
void MainWindow::EvolutionaryLoop()
{
    m_GenerationNumber++;

    for(int i = 0; i < ui->sbChildren->value(); i++)
    {
        float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

        //80 percent of the time we do a crossover.
        if (r < 0.8)
        {
            int father_index = rand() % population.size();
            int mother_index = rand() % population.size();
            CrossOver(population.at(father_index), population.at(mother_index));
            ComputeFitness(population.back());
        }
        // we clone the rest of the time (10%)
        else
        {
            int clone_index = rand() % population.size();
            population.push_back(population.at(clone_index));
        }

        Mutation(population.at(i));
    }

    MakeFights();

    fs = GetPhenotypeStatsInAGeneration();
    int best_index = fs.bestFitnessIndex;

    if (population.at(best_index)->GetFitness() <= ui->dsbFitnessThreshold->value()
            && population.at(best_index)->IsValid() == true)
    {
        timer->stop();
        statusLabel->setText(QString("Found best phenotype (number %2) at generation %0 with a fitness of %1")
                             .arg(fs.noOfGeneration)
                             .arg(population.at(best_index)->GetFitness())
                             .arg(best_index));
        //statusProgressBar->setValue(statusProgressBar->maximum());
    }

    //population.at(best_index)->Mutate();
    ComputeFitness(population.at(best_index));
    int row = AddRow(population.at(best_index));
    bool green = population.at(best_index)->IsValid();
    SetRowColor(row, green);
    PopulatePlot(ui->tableWidget, fs);
    ShowPhenotype(population.at(best_index));

    ui->lGeneration->setText(QString("Generation %0").arg(m_GenerationNumber));
}
Example #6
0
void GeneManager::newGene(int growthSeg,int growthTurns,int maturedDuration,int decayTurns,int maxExpressedTraits, int decaySeed,int maturedSeed,
        int prob_in_exp, int prob_in_unexp, int prob_exp_exp, int prob_exp_unexp,
        int prob_mutation, int m_growthSeg,int m_growthTurns, int m_maturedDuration, int m_decayTurns,
        int m_maxExpressedTraits, int m_decaySeed, int m_maturedSeed)
{
    _genes.push_back(new Gene(
                _genes.size(),
                SeedAttribute(growthSeg,growthTurns,maturedDuration,decayTurns,maxExpressedTraits,decaySeed,maturedSeed), // Attribute contribution
                Probability(prob_in_exp), // Prob inherited if expressed
                Probability(prob_in_unexp),  // Prob inherited if unexpressed
                Probability(prob_exp_exp),  // Prob expressed if expressed
                Probability(prob_exp_unexp),  // Prob expressed if unexpressed
                Mutation(Probability(prob_mutation),SeedAttribute(m_growthSeg,m_growthTurns,m_maturedDuration,m_decayTurns,m_maxExpressedTraits,m_decaySeed,m_maturedSeed)) // Mutation possibility
                ));
}
Example #7
0
void
Algorithm<T>::Init(int pCountOfIndividuals, 
									 int pCountOfChromosomes,
						       const std::vector<T>& pAllPossibleIndividuals,
						       TaskDefinition<T>* pTask)
{
	if (!m_isInitialized) {
		assert (pAllPossibleIndividuals.size() != 0);
		assert (m_countOfIndividuals <= pAllPossibleIndividuals.size());
		m_countOfIndividuals = pCountOfIndividuals;
		m_countOfChromosomes = pCountOfChromosomes;
		m_allPossibleIndividuals = pAllPossibleIndividuals;
        m_task = pTask;
		
		// 1. Randomly initialize population.
		RandomInitPopulation();

		while (true) {
			// 2. Calculate fitness values.
			CalculateObjectiveFunction();

			// 3. Calculate fitness value. 
			CalculateFitnessValue();

			// 4. Calculate fitness probability.
			CalculateFitnessProbability();

			// 5. Calculate cumulative probability.
			CalculateCumulativeProbability();

			// 6. Selection
			Selection();

			// 7. Extract Parents
			ExtractParents();

			// 8. Crossover
			Crossover();

			// 9. Mutation
			Mutation();

		}
		m_isInitialized = true;
	} else {
		std::cout << "Algorithm is already initialized." << std::endl;
	}
}
Example #8
0
void GeneticAlgorithm(){

    int maxIter = 100;
    int i,j,k;
    int group[GROUP_SIZE][COUNT_FUNC];
    int oldParameter[COUNT_FUNC];
    int maxIndex;
    double sum,max,min,tmp;
    int count_record = 0;
    char output[300];

    /*初始族群*/
    InitGroup(group);



    for ( i = 0 ; i < maxIter ; i++){
        Eliminate(group);
        Crossover(group);
        Mutation(group);

        sum = 0;
        max = -1;
        min = 20;
        maxIndex = 0;
        #pragma omp parallel for
        for ( j = 0 ; j < GROUP_SIZE ; j++){
            tmp= Evalue( group[j]);

            if ( tmp > 10){
                fout = fopen("parameter.txt", "a");
                sprintf(output,"Parameter = ");
                for ( k = 0 ; k < COUNT_FUNC ; k++){
                    sprintf(output,"%s %5d",output, group[j][k]);
                }
                sprintf(output,"%s, Score = %lf\n",output,tmp);
                fprintf(fout,"%s",output);
                fclose(fout);
            }

            sum += tmp;

            if ( tmp > max ){
                max= tmp;
                maxIndex = j;
            }
            if ( tmp < min )
                min = tmp;
        }
        if ( i % 10 == 0)
            Record(group);
        printf("Level(%d) = %.2lf, %.2lf, %.2lf\n", i,max,sum/GROUP_SIZE,min);
        if ( max >= 10.5 && PlayGame(group[maxIndex]) >= 10.9)
            break;
    }

    printf("==Result==\n");
    for ( i = 0 ; i < COUNT_FUNC ; i++){
        printf(", %d", group[maxIndex][i]);
    }
    putchar('\n');

}
int main(int argc , char *argv[]){
	/* Variable */
	char filename[64];
	int my_rank;
	double startTime=0.0 , totalTime=0.0;
	int max_generation,switching_num;
	float crossover_rate,mutation_rate;
	int **Local_population;
	//int *pop_weight = malloc(max_pop*sizeof(int));
	int i,j,k;
	/* Initialize MPI */
	MPI_Init(&argc,&argv);
	/* Set MPI  */
	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
	MPI_Comm_size(MPI_COMM_WORLD,&comm_sz);
	/* Start time (rank = 0)*/
	if(my_rank == 0){
		startTime = MPI_Wtime();
		/* Read from the file */
	}
	/* Read from the parameter file */
   	 char *para_file = argv[1];
   	 FILE *fpara = fopen(para_file,"r");
   	 /* Format : max generation , Crossover rate , Mutation rate , Switching number => for every process !*/
   	 fscanf(fpara , "%d %f %f %d %d %s" , &max_generation , &crossover_rate , &mutation_rate , &switching_num ,&max_pop , filename);
   	 int *pop_weight = malloc(max_pop*sizeof(int));
   	 FILE *fp = fopen(filename , "r");
   	 //printf("Max : %d ; cross rate : %f ; mutation rate : %f ; switching_num : %d \n", max_generation , crossover_rate , mutation_rate , switching_num);
	/* Read in the size of matrix => Get "city number" */
	city_number = (filename[strlen(filename)-7] - 48) + 10*(filename[strlen(filename)-8]-48);
    	path_cost = allocate_dimension(city_number,city_number);
    	/* Read in the matrix */
    	for(i=0;i<city_number;i++){
        	for(j=0;j<city_number;j++){
        		fscanf(fp , "%5d" , &path_cost[i][j]);
        	}
   	}
   	// Initialize
   	for(i = 0 ; i < comm_sz ; i++){
   		if(my_rank == i){
	   	 /* Build Population , taking sample from a line of data , number 20~50 sequences (define on the top)*/ 
	   	Local_population = random_population_generation(i,max_pop,city_number);
	   	 /* Setting Every  Weight of each sequence of array*/
	   	weight_calculation(Local_population,pop_weight);
		}
   	 }
	// check result => OK ; check every population is different => OK
	// check for every weight of population sequence => OK
   	 if(my_rank == 0){
   	 	for(j=0;j<max_pop;j++){
   	 		for(k=0;k<city_number;k++){
   	 			printf("%d " , Local_population[j][k]);
   	 		}
   	 		printf("\n");
   	 	}
   	}
   	//int **sendswitching = allocate_dimension(switching_num , city_number);
	//int **recvswitching = allocate_dimension(switching_num , city_number);
   	 /* Get the generation count */
   	for(i = 0 ; i < max_generation ; i++){
   		/* Recompute the pop_weight */
   	 	weight_calculation(Local_population,pop_weight);
	   	// Calculate "Crossover"
	   	Crossover(Local_population,pop_weight,crossover_rate);
		// Calculate "Mutation"
		Mutation(Local_population,mutation_rate);
		// Calculate "switching_num" and add to population
		// Select the "max_pop" number and make it to next generation population
		// MPI_SEND , MPI_RECV
		Switch_Select(my_rank,Local_population,switching_num);
   	 }
   	 if(my_rank == 0){
   	 	printf("\n");
   	 	for(j=0;j<max_pop;j++){
   	 		for(k=0;k<city_number;k++){
   	 			printf("%d " , Local_population[j][k]);
   	 		}
   	 		printf("\n");
   	 	}
   	 }
   	 // Choosing the best result of each process
   	 //if(my_rank == 0){
   	 weight_calculation(Local_population,pop_weight); 
   	 int minimal = 20000 , result;
   	 for(i = 0; i < max_pop ; i++){
   	 	if(minimal > pop_weight[i]){
 			minimal = pop_weight[i];
 	 		result = i;
   		}
   	 }
   	printf("My rank %d The Best answer is %d\n",my_rank, minimal);
   	printf("\n");
   	
   	int *compare = malloc(city_number*sizeof(int));
   	 // And choosing the best result among every process's best result , ALL Send to my_rank = 0
   	 if(my_rank != 0){
   	 	MPI_Send(Local_population[result] , city_number , MPI_INT , 0 , my_rank , MPI_COMM_WORLD);
   	 }
   	 if(my_rank == 0){
   	 	for(i = 1;i<comm_sz;i++){
   	 		MPI_Recv(compare,city_number , MPI_INT , i , i , MPI_COMM_WORLD,MPI_STATUS_IGNORE);
   	 		int weight=0;
   	 		for(j = 0; j <city_number-1 ; j++){
   	 			weight += path_cost[compare[j]][compare[j+1]];
   	 		}
   	 		if(minimal > weight){
   	 			minimal = weight;
   	 		}
   	 	}
   	 	printf("The Best answer among process is %d\n",minimal);
   	 }
   	 
   	 /* End time (rank = 0) */
   	 if(my_rank == 0){
   	 	totalTime = MPI_Wtime() - startTime;
   	 	printf("Total Time is %f \n" , totalTime);
   	 }
   	 /* Terminate MPI */
   	MPI_Finalize();
    	return 0;
}
Example #10
0
void CMPGA::NextGen() {
   ++m_unCurrentGeneration;
   Selection();
   Crossover();
   Mutation();
}
int main()
{
	int icount = 0;  //指示
	int gencount = 0;
	int tim;   //指示TIME
	int res = 0;  //指示RESPONSE
	
	FILE *fp;
	fp = fopen("TimeSequence.txt","r+t");
	while(res < RESPONSE)
	{
		for(gencount = 0; gencount < GENENUM; gencount++)
		{
			for (tim = 0; tim < TIME; tim++)
		    {
				fscanf(fp, "%lf", &data[res][gencount][tim]);
		    }
		}
		res = res + 1;
	}
	fclose(fp);

	int flag = 0;
	srand((unsigned)time(NULL));  

	grpGA grp;
	pgrpGA pgrp = &grp;
	grp.generationCount = 0;
	grp.generationMax = 5000;  //遗传算法迭代次数
	grp.probCross = 0.9;     
	grp.probMutat = 0.1;    
	grp.size = SIZEGROUP;  //种群大小

	genGA ind[SIZEGROUP];
	pgenGA pind[SIZEGROUP];

	for(icount = 0; icount < SIZEGROUP; icount++)
	{
		pind[icount] = &ind[icount];
	}
	
	int u = 0;
	for(u = 0; u < GENENUM; u++)
	{
		printf("%d node learn\n", u);
		FILE *fp1;
		fp1 = fopen("Individuals.txt","r+t");
		icount = 0;
		while(icount < SIZEGROUP)
		{
			for (gencount = 0; gencount < GENENUM; gencount++)
			{
				fscanf(fp1, "%d", &populationMirror[icount][gencount]);
			}
			icount = icount + 1;
		}
		fclose(fp1);

		genExpect = 0;
		for(res = 0; res < RESPONSE; res++)
		{
			for(gencount = 0; gencount < GENENUM; gencount++)
			{
				genWigh[res][gencount] = 0;
			}
		}

		for(gencount = 0; gencount < GENENUM; gencount++)
		{
			genTest[gencount] = 0;
			genWighMean[gencount] = 0;
			elite[gencount] = 0;
			eliteWeight[gencount] = 0;
		}
	    
		eliteFitness = 0;

		do
		{
			Initial(pind);

			ErrorCmp(pind, data, populationMirror, genTest, genWigh, genWighMean, genExpect, &u);
			Fitness(pind);
			Optimal(pind, elite, &eliteFitness, populationMirror, genWighMean, eliteWeight);
			
			flag = Termination(pgrp);
			if(flag)
			{
				break;
			}

			BinaryTourment(pind, pgrp, populationMirror);
			Crossover(pind, pgrp, populationMirror);  
			Mutation(pind, pgrp, populationMirror); 
		
		}while(1);

		ResultOutput(pind, elite, pgrp, eliteWeight);
	}
	
	return 0;
}