void Graph::insertMutEvents(nat genC, AddrArrayBackwardIter<Node,true> &mutBackIter, Node** nodeBufferNowGen, Chromosome &chrom, Randomness &rng) { bool canGoBack = NOT mutBackIter.empty(); nat chromId = chrom.getId(); while(canGoBack && mutBackIter()->originGen == genC) { Node *node = mutBackIter(); nat indiNr = node->indiNr; node->ancId1 = nodeBufferNowGen[indiNr] ? nodeBufferNowGen[indiNr]->id : NO_NODE ; // determine the base // :TODO: this currently does not allow for a double mutation occuring in one line node->base = chrom.mutateSite(rng, node->loc); #ifdef DEBUG_HOOKUP cout << "MUT: [" << *node << "]" << "\t===>" << (nodeBufferNowGen[indiNr] ? nodeBufferNowGen[indiNr]->id : 0) << endl; #endif nodeBufferNowGen[indiNr] = node; canGoBack = mutBackIter.back(); } }
Simulation::Simulation(InfoFile &info, ProgramOptions &theProgOpt, ThreadPool &_tp) : progOpt(theProgOpt) , numGen(progOpt.getNumberOfGenerations()) , tp(_tp) { // create chromosomes Randomness &rng = tp[0].getRNG(); vector<seqLen_t> lengths = progOpt.get<vector<seqLen_t> >("length"); nat idC = 0; nat numPop = 1; // TODO pops for(auto& length : lengths) { FitnessFunction fFun(progOpt.get<vector<string>>("selCoef")); Chromosome* chromo = new Chromosome(length, theProgOpt.hasOption("neutral"), fFun, idC++, numPop); chromo->init(rng); chromosomes.push_back(chromo); } // create parameters of populations vector<nat> popSizes = progOpt.get<vector<nat> >("popSize"); assert(popSizes.size() == 1 ); popParams.push_back( PopulationParams(0, numGen, popSizes[0], progOpt)); fractionalSimulation = new FractionalSimulation(tp,info, progOpt, numGen, chromosomes, popParams); }
Chromosome* Chromosome::MultiplePointCrossoverWithChromosome(Chromosome* Mutator) { //srand( (unsigned)time(0) ); srand should have been called already Chromosome* ret = new Chromosome(10); // NEED NUM HERE for (int i = 0; i < NUM_EVALNODES; i++) { //In single point crossover, we select a random point //Before the random point, take from A, take rest from B int random_integer1 = (rand() %10); //32 bit integer int random_integer2 = (rand() %10); while (random_integer1 == random_integer2) random_integer2 = (rand() % 10); int mask = 1; //if (random_integer1 > random_integer2) { for (int j = 0 ; j < abs(random_integer1-random_integer2); j++) { mask = mask<<1; mask |= 1; } int nextShift = ((random_integer2 > random_integer1) ? random_integer1 : random_integer2); mask = mask << nextShift; } int newWeighting = (Weightings[i]&mask) | (Mutator->GetWeighting(i)& ~mask); ret->SetWeighting(i, newWeighting); } return ret; }
Chromosome* Chromosome::ArithmeticCrossoverWithChromosome(Chromosome* Mutator) { //srand( (unsigned)time(0) ); srand should have been called already bool bAnd = (rand() &1); //0 doesn't really matter, updating weights anyway Chromosome* ret = new Chromosome(0); if (bAnd) { for (int i = 0; i < NUM_EVALNODES; i++) { int newWeighting = (Weightings[i] & Mutator->GetWeighting(i)); ret->SetWeighting(i, newWeighting); } } else { for (int i = 0; i < NUM_EVALNODES; i++) { int newWeighting = (Weightings[i] | Mutator->GetWeighting(i)); ret->SetWeighting(i, newWeighting); } } return ret; }
int GenomeMaps::report_mapped_region(Chromosome const &chr, int chr_start, int chr_end, int num_matches) { reported_mapped_regions++ ; //fprintf(stdout, "mapped_region:\tchr=%s\tstart=%i\tend=%i\tmatches=%i\n", CHR_DESC[chr], chr_start, chr_end, num_matches) ; //assert(chr_start>=0 && chr_start<CHR_LENGTH[chr]) ; //assert(chr_end>=0 && chr_end<CHR_LENGTH[chr]) ; if (!(chr_start>=0 && (size_t)chr_start<=chr.length())) { if (_config.VERBOSE>0) fprintf(stdout, "report_mapped_region: start out of bounds\n") ; if (chr_start<0) chr_start = 0 ; else chr_start = chr.length() ; } if (!(chr_end>=0 && (size_t)chr_end<=chr.length())) { if (_config.VERBOSE>0) fprintf(stdout, "report_mapped_region: end out of bounds\n") ; if (chr_end<0) chr_end = 0 ; else chr_end = chr.length() ; } for (int i=chr_start; i<chr_end; i++) if ((CHR_MAP(chr,i) & MASK_MAPPED_REGION) ==0 ) { covered_mapped_region_positions++ ; CHR_MAP_set(chr, i, CHR_MAP(chr,i) + MASK_MAPPED_REGION) ; } return 0 ; }
/// todo: create a function that return the pop/chromosome size for brievty void Popu::mutate(int pos){ /// given an offspring we mutate it at a certain rate and create the new population int pos1=0,pos2=3;//size=offspring.elements.size(); QTime t;int rd=3; Chromosome mutant; ///NOTE: As we kept the 2 best parents as are (ellitisme) we start from 2 for (int i=0;i<2;i++){ if (i==0) mutant=parentOne; else mutant=parentTwo; for (int j=0;j<chromoSize;j++){ rd=qrand()%chromoSize; //qDebug()<<rd; ///DFFIXME : make it dependant on a variable value Mut_prob the probability should be small if (rd >chromoSize-(chromoSize/5)) { //qDebug()<<"creating a mutant"; pos1=qrand()%chromoSize; //qsrand(QTime::msec ()); pos2=qrand()%chromoSize; //qDebug()<<pos2<<pos1; //mutant.elements.swap(pos1,pos2); swapVals(mutant.elements,pos1,pos2); } ///qDebug()<<mutant.elements<<"route"<< mutant.routeLength; } mutant.setRoutelength(); ///qDebug()<<"creating a mutant at "<<pos+i<<"routes"<< mutant.routeLength; newGen.replace(pos+i,mutant); //qDebug()<<newGen.size(); } }
void Sorting::sort(std::vector<Chromosome>& pop) { std::vector<Chromosome> sorted; while (pop.size() != 0) { double bestFitness = -100000; Chromosome bestChromosome; int bestChromomeIndex = -1; for (size_t i = 0; i < pop.size(); i++) { if (pop.at(i).getFitness() > bestFitness) { bestChromosome = pop.at(i); bestFitness = bestChromosome.getFitness(); bestChromomeIndex = i; } } sorted.push_back(bestChromosome); pop.erase(pop.begin() + bestChromomeIndex); } for (size_t i = 0; i < sorted.size(); i++) { pop.push_back(sorted.at(i)); } }
void Popu::mutate(int pos){ int pos1=0,pos2=3;//size=offspring.elements.size(); //QTime t; int rd=3; Chromosome mutant; for (int i=0;i<2;i++){ if (i==0) mutant=parentOne; else mutant=parentTwo; for (int j=0;j<chromoSize;j++){ ///@todo make it dependant on a variable value Mut_prob the probability should be small rd=qrand()%chromoSize; if (rd >chromoSize-(chromoSize/5)) { //qDebug()<<"creating a mutant"; pos1=qrand()%chromoSize; //qsrand(QTime::msec ()); pos2=qrand()%chromoSize; //qDebug()<<pos2<<pos1; swapVals(mutant.elements,pos1,pos2); } //qDebug()<<mutant.elements<<"route"<< mutant.routeLength; } mutant.calcRouteLength(); //qDebug()<<"creating a mutant at "<<pos+i<<"routes"<< mutant.routeLength; ///@NOTE: As we kept the 2 best parents as are (ellitisme) and i>0 at while loop end we keep the elite //newGen.replace(pos+i,mutant); newGen.replace(pos,mutant); //qDebug()<<newGen.size(); } }
QPFWPVector Popu::init(QPFWPVector points,bool randomtartupPop){ int i=0; chromoSize=points.size(); qDebug()<<"Creating initial Rpop"; ///create a population of @see popSize chromosome. The chromosome elements are taken randomly from parent @see points while (i<popSize){ Chromosome member; member.setElements(points,randomtartupPop); content.append(member); //fixme: need to be computed only once totalRoute=member.routeLength; i++; } qDebug()<<"Created an initial Random pop with route:"<<totalRoute; sortContent(); /// copy the created population into newGen newGen=content; /// Keep creating new genrations until @see Max_iter for (curGen=0;curGen<Max_iter;curGen++){ createNewGen(); } return content[0].elements; }
void DSMGA2::backMixingE(Chromosome& source, list<int>& mask, Chromosome& des) { cout <<"_bme"; Chromosome trial(ell); trial = des; for (list<int>::iterator it = mask.begin(); it != mask.end(); ++it) trial.setVal(*it, source.getVal(*it)); if (trial.getFitness() > des.getFitness()) { pHash.erase(des.getKey()); pHash[trial.getKey()] = trial.getFitness(); EQ = false; //des.getIndex()++; des = trial; return; } if (trial.getFitness() >= des.getFitness()) { pHash.erase(des.getKey()); pHash[trial.getKey()] = trial.getFitness(); des = trial; return; } }
int Dilemma::compare(const void *x, const void *y){ const Chromosome xx = *(Chromosome*)x; const Chromosome yy = *(Chromosome*)y; if(xx.getFitness() < yy.getFitness()) return 1; if(xx.getFitness() > yy.getFitness()) return -1; return 0; }
bool Chromosome::operator < (const Chromosome& another)const { if(this->TestCaseCount < another.getCount()) return true; else if(this->TestCaseCount > another.getCount()) return false; else return((this->fitness)< another.getFitness()); }
size_t DSMGA2::findSize(Chromosome& ch, list<int>& mask, Chromosome& ch2) const { cout <<"_findsize2"; size_t size = 0; for (list<int>::iterator it = mask.begin(); it != mask.end(); ++it) { if (ch.getVal(*it) == ch2.getVal(*it)) break; ++size; } return size; }
void crossover(Chromosome& chromosome1, Chromosome& chromosome2) { float randomVal = randomRange(0.0f, 1.0f); if (randomVal < CROSSOVER_RATE) { int count = std::min(chromosome1.getGeneCount(), chromosome2.getGeneCount()); int start = randomRange(0, count - 1); for (int i = start; i < count; ++i) { geneSwap(chromosome1[i], chromosome2[i]); } } }
Chromosome Chromosome::combination(Chromosome &mate){ Chromosome newChromosome = Chromosome(_genes.substr(0)); for (size_t i = 0; i < CHROMOSOME_LENGTH; i++) { if (eventHappenedWithProbability(CROSSOVER_CHANCE)){ int crossoverLength = binomialRandomAroundTarget(CROSSOVER_AVERAGE_LENGTH); newChromosome.addCrossover(mate, i, crossoverLength); } } return newChromosome; }
int GenomeMaps::report_repetitive_seed(Chromosome const &chr, int chr_start, int count) { //fprintf(stdout, "repetitive_seed:\tchr=%s\tpos=%i\tcount=%i\n", CHR_DESC[chr], chr_start, count) ; if (count<Config::REPORT_REPETITIVE_SEED_COUNT) return 0 ; if (!(chr_start>=0 && (size_t)chr_start<=chr.length())) { if (_config.VERBOSE>0) fprintf(stdout, "report_mapped_region: start out of bounds\n") ; if (chr_start<0) chr_start = 0 ; else chr_start = chr.length() ; } assert(chr_start>=0 && (size_t)chr_start<chr.length()) ; //fprintf(stdout, "repetitive_seed:\tchr=%s\tpos=%i\tcount=%i\n", CHR_DESC[chr], chr_start, count) ; reported_repetitive_seeds++ ; for (unsigned int i=chr_start; i<chr_start+_config.INDEX_DEPTH+REPORT_REPETITIVE_SEED_DEPTH_EXTRA && i<chr.length(); i++) if ((CHR_MAP(chr,i) & MASK_REPETITIVE_SEED) == 0) { covered_repetitive_seed_positions++ ; CHR_MAP_set(chr,i, CHR_MAP(chr,i) + MASK_REPETITIVE_SEED) ; } do_reporting() ; if (count<Config::REPORT_REPETITIVE_SEED_COUNT_MANY1) return 0 ; for (unsigned int i=chr_start; i<chr_start+_config.INDEX_DEPTH+REPORT_REPETITIVE_SEED_DEPTH_EXTRA && i<chr.length(); i++) if ((CHR_MAP(chr,i) & MASK_REPETITIVE_SEED_MANY1) == 0) { covered_repetitive_seed_positions_many1++ ; CHR_MAP_set(chr, i, CHR_MAP(chr,i) + MASK_REPETITIVE_SEED_MANY1) ; } if (count<Config::REPORT_REPETITIVE_SEED_COUNT_MANY2) return 0 ; for (unsigned int i=chr_start; i<chr_start+_config.INDEX_DEPTH+REPORT_REPETITIVE_SEED_DEPTH_EXTRA && i<chr.length(); i++) if ((CHR_MAP(chr,i) & MASK_REPETITIVE_SEED_MANY2) == 0) { covered_repetitive_seed_positions_many2++ ; CHR_MAP_set(chr, i, CHR_MAP(chr,i) + MASK_REPETITIVE_SEED_MANY2) ; } return 1 ; }
void mutate(Chromosome& chromosome1, Chromosome& chromosome2) { for (auto& gene : chromosome1.getGeneList()) { if (randomRange(0.0f, 1.0f) < MUTATION_RATE) { gene.randomize(); } } for (auto& gene : chromosome2.getGeneList()) { if (randomRange(0.0f, 1.0f) < MUTATION_RATE) { gene.randomize(); } } }
void Initialize() { for (int i = 0; i < population_size; i++) { //Initializing each member of the population Chromosome* dna = new Chromosome(); dna->num_genes = 18; dna->Initialize(); dna->SetTarget(target); population.push_back(dna); } }
void EA<T>::randomInitialization() { Chromosome<T>* c; for (unsigned int i = 0; i < population_size; i++) { c = new Chromosome<T>(encoding, lower_boundary, upper_boundary); std::vector<T> values; for (unsigned int j = 0; j < Chromosome_size; j++) { T value = (T)(std::generate_canonical<double, std::numeric_limits<double>::digits>(generator) * (upper_boundary - lower_boundary) + lower_boundary); values.push_back(value); } c->setChromosome(values); population.push_back(c); } }
// Generate a completely new chromosome Chromosome GeneticOperator::RandomChromosome(void) { boost::random::uniform_int_distribution<> dist(1, 4); int randomNrGene = dist(randomGen); Chromosome c; std::vector<BWAPI::UnitType> buildSequence; for(int i=0; i<=CHROMOSOME_LENGTH; i++) { State s(buildSequence); while(randomNrGene != 4) // 4 = build gene { bool found = false; switch(randomNrGene) { case 1: { std::tr1::shared_ptr<AttackGene> gene = StarcraftRules::getValidAttackGene(s); s.addGene(gene); } break; case 2: { std::tr1::shared_ptr<CombatGene> gene = StarcraftRules::getValidCombatGene(s, found); if (found == true) s.addGene(gene); } break; case 3: { std::tr1::shared_ptr<ResearchGene> gene = StarcraftRules::getValidResearchGene(s, found); if (found == true) s.addGene(gene); } break; } randomNrGene = dist(randomGen); } s.addGene(StarcraftRules::getValidBuildGene(s)); c.addState(s); buildSequence = s.getBuildingSequence(); randomNrGene = dist(randomGen); } return c; }
Chromosome* crossover(Chromosome *partner) { Chromosome *child = new Chromosome(); child->num_genes = this->num_genes; child->Initialize(); child->SetTarget(this->target); int midpoint = int(RandomInt(0, num_genes)); for (int i = 0; i < num_genes; i++) { if (i > midpoint) child->genes[i] = genes[i]; else { if (partner != 0) child->genes[i] = partner->genes[i]; } } return child; }
size_t DSMGA2::findSize(Chromosome& ch, list<int>& mask) const { cout <<"_Findsize"; DLLA candidate(nCurrent); for (int i=0; i<nCurrent; ++i) candidate.insert(i); size_t size = 0; for (list<int>::iterator it = mask.begin(); it != mask.end(); ++it) { int allele = ch.getVal(*it); for (DLLA::iterator it2 = candidate.begin(); it2 != candidate.end(); ++it2) { if (population[*it2].getVal(*it) == allele) candidate.erase(*it2); if (candidate.isEmpty()) break; } if (candidate.isEmpty()) break; ++size; } return size; }
// Select 1 parent and for every activated state the // parameters for existing combat or economy rules have // a 50% chance of being mutated. The mutation is within a // predefined boundary (between a minimum and maximum value). // For this genetic operator, we exclude build and research rules. Chromosome GeneticOperator::RuleBiasedMutation(const Chromosome& parent) { std::vector<State> childStates = parent.getStates(); for(size_t i=0;i<childStates.size();i++) { State& s = childStates.at(i); for (size_t j=0;j<s.getGenes().size(); j++){ const std::tr1::shared_ptr<Gene> g = s.getGenes().at(j); if(typeid(*g) != typeid(BuildGene) && typeid(*g) != typeid(ResearchGene)) { // Mutate gene boost::random::uniform_int_distribution<> dist(0, 1); int randomNr = dist(randomGen); if(randomNr) { if(typeid(*g) != typeid(AttackGene)) { // Mutate parameters of gene std::tr1::shared_ptr<AttackGene> gene = StarcraftRules::getValidAttackGene(s); s.replaceGeneAt(j, gene); } else if(typeid(*g) != typeid(CombatGene)) { // Mutate parameters of gene bool found; std::tr1::shared_ptr<CombatGene> gene = StarcraftRules::getValidCombatGene(s, found); if (found) s.replaceGeneAt(j, gene); } } } } } return Chromosome(childStates); }
QString LovdUploadFile::chromosomeToAccession(const Chromosome& chr) { QByteArray chr_str = chr.strNormalized(false); if (chr_str=="1") return "NC_000001.10"; else if (chr_str=="2") return "NC_000002.11"; else if (chr_str=="3") return "NC_000003.11"; else if (chr_str=="4") return "NC_000004.11"; else if (chr_str=="5") return "NC_000005.9"; else if (chr_str=="6") return "NC_000006.11"; else if (chr_str=="7") return "NC_000007.13"; else if (chr_str=="8") return "NC_000008.10"; else if (chr_str=="9") return "NC_000009.11"; else if (chr_str=="10") return "NC_000010.10"; else if (chr_str=="11") return "NC_000011.9"; else if (chr_str=="12") return "NC_000012.11"; else if (chr_str=="13") return "NC_000013.10"; else if (chr_str=="14") return "NC_000014.8"; else if (chr_str=="15") return "NC_000015.9"; else if (chr_str=="16") return "NC_000016.9"; else if (chr_str=="17") return "NC_000017.10"; else if (chr_str=="18") return "NC_000018.9"; else if (chr_str=="19") return "NC_000019.9"; else if (chr_str=="20") return "NC_000020.10"; else if (chr_str=="21") return "NC_000021.8"; else if (chr_str=="22") return "NC_000022.10"; else if (chr_str=="X") return "NC_000023.10"; else if (chr_str=="Y") return "NC_000024.9"; else if (chr_str=="M") return "NC_012920.1"; THROW(ProgrammingException, "Unknown chromosome '" + chr_str + "' in LovdUploadFile::create(...) method!"); }
void Graph::createSequencesInGraph(const Chromosome &chromo) { seqLen_t start = 0; seqLen_t end = chromo.getSeqLen(); for(Node *node : previousState) if(node) nodMan.markAncestrialMaterial(*node, start, end); for(Node *node : previousState) if(node) nodMan.determineCoalescentNodes(node); nodMan.initBvMeaning(); nodMan.computeOptimalRefed(); // a slight hack to initialize the dummy node nat numNeutMut = getBvMeaning().size(); NodeExtraInfo *info = nodMan.getInfo(0); info->bv = new BitSetSeq(numNeutMut); for(nat i = 0; i < previousState.size(); ++i) { Node *node = previousState[i]; #ifdef DEBUG_SEQUENCE_EXTRACTION cout << "starting extraction for sequence " << i << "\t" << previousState.size() << endl; #endif if(node) nodMan.createSequenceForNode(node); } }
void RunGA(){ int generations = 0; while(max_generation >= 0 && generations <= max_generation){ GAStep(); if(generations % 100 == 0){ std::cout << "Generacion: " << generations << "\n"; } if(generations % 1000 == 0){ Chromosome *best = SelectBest(); QImage image = DrawImage(best); image.save(QString("out/out_") + QString::number(generations) + ".png"); qDebug() << "Fitness: " << best->Fitness(); } generations++; } DrawSVG(SelectBest(), "Final.svg"); }
/* * Generate a population of random bits using a specific seed * Parameters: populationSize, chromosomeLength, seed value * Return: boolean */ bool Population::generate(size_t populationSize, size_t chromosomeLength, string seedValue) { seed_seq seed(seedValue.begin(), seedValue.end()); //Use the seed value instead of random_device mt19937 gen(seed); bernoulli_distribution dist; //Bernoulli distribution of type bool for(size_t i = 0; i < populationSize; i++){ Chromosome chromosome; chromosome.reserve(chromosomeLength); for(size_t j = 0; j<chromosomeLength; j++){ chromosome.push_back(dist(gen)); ///generate a random bool } population.push_back(chromosome); } return true; }
/* * Generate a population of random bits using a random seed * Parameters: populationSize, chromosomeLength * Return: boolean */ bool Population::generate(size_t populationSize, size_t chromosomeLength) { random_device rd; mt19937 gen(rd()); bernoulli_distribution dist; //Bernoulli distribution of type bool for (size_t i = 0; i < populationSize; i++) { Chromosome chromosome; chromosome.reserve(chromosomeLength); for (size_t j = 0; j < chromosomeLength; j++) { chromosome.push_back(dist(gen)); ///generate a random bool } population.push_back(chromosome); } return true; }
std::pair<Chromosome, Breeder::BreedStats> Breeder::breed(const Chromosome& mum, const Chromosome& dad, uint32_t crossOverPerMillion) { BreedStats stats; stats.crossOvers = 0; std::random_device rd; std::uniform_int_distribution<> randomMillion(0, 999999); std::uniform_int_distribution<> mumOrDad(0, 1); bool startWithMum = mumOrDad(rd) == 0; const Gene* currentGene = startWithMum ? &mum.gene() : &dad.gene(); const Gene* otherGene = startWithMum ? &dad.gene() : &mum.gene(); Gene resultingGene; resultingGene.resize(currentGene->size()); for(uint32_t i = 0; i < resultingGene.size(); i++) { resultingGene[i] = (*currentGene)[i]; if(crossOverPerMillion > randomMillion(rd)) { std::swap(currentGene, otherGene); ++stats.crossOvers; } } return {Chromosome(mum.maxCistronIds(), mum.informationDensity(), mum.startSequence(), mum.stopSequence(), resultingGene), stats}; }
void Chromosome_Length_test::testBuildChromosome() { unsigned int nDim = 3; unsigned int aPrecision = 6; std::vector<double> domain; for(unsigned i=0; i<2*nDim; ++i) { domain.push_back(2*i+i); } Chromosome_Length chrom_length(aPrecision, nDim, domain); chrom_length.buildChromosome(); Chromosome chrom = chrom_length.getChromosome(); std:: cout<< "the total length of the chromosome = "<< chrom.size()<< std::endl; }