DNA* initSultan5(int& m, int& n) { SmartArrayPtr<double> *diag, *sdiag, *kap; m = 5; n = 6; DNA* dna = new DNA(n, n - m); diag = dna->getDiag(); sdiag = dna->getSDiag(); kap = dna->getKap(); diag->alloc(m); sdiag->alloc(m); kap->alloc(m); for(int i = 0; i < 5; i ++) { (*diag)[i] = 0.; (*sdiag)[i] = 1.; } (*kap)[0] = 24.; (*kap)[1] = 27.; (*kap)[2] = 33.; (*kap)[3] = 37.; (*kap)[4] = 24.; return dna; }
// Making the next generation void Population::reproduction() { // Refill the population with children from the mating pool for( int i = 0; i < mPopulation.size(); i++ ) { // Sping the wheel of fortune to pick two parents int m = randInt( mMatingPool.size() ); int d = randInt( mMatingPool.size() ); // Pick two parents RocketRef mom = mMatingPool[m]; RocketRef dad = mMatingPool[d]; // Get their genes DNA *momgenes = mom->getDNA(); DNA *dadgenes = dad->getDNA(); // Mate their genes DNA *child = momgenes->crossover( dadgenes ); // Mutate their genes child->mutate( mMutationRate ); // Fill the new population with the new child Vec2f location = Vec2f( getWindowWidth() / 2.0, getWindowHeight() + 20.0 ); mPopulation[i].reset(); // get rid of the old rocket mPopulation[i] = std::make_shared<Rocket>( location, child, mTarget ); } mGenerations++; }
//-------------------------------------------------------------- void ofApp::draw() { if (!foundSolution) { for (int i = 0; i < ArrayCount(population); i++) { population[i].Fitness(); } vector<DNA> matingPool = vector<DNA>(); for (int i = 0; i < ArrayCount(population); i++) { int n = int(population[i].fitness * ArrayCount(population)); for (int k = 0; k < n; k++) { matingPool.push_back(population[i]); } } for (int i = 0; i < ArrayCount(population); i++) { int a = int(ofRandom(0, matingPool.size())); int b = int(ofRandom(0, matingPool.size())); DNA parentA = matingPool[a]; DNA parentB = matingPool[b]; DNA child = parentA.crossover(parentB); child.mutate(); population[i] = child; } } ofClear(ofColor::white); ofSetColor(ofColor::black); for (int i = 0; i < ArrayCount(population); i++) { //string str = population[i].genes; population[i].genes[ArrayCount(population[i].genes)] = '\0'; if (population[i].genes == target) { foundSolution = true; ofNoFill(); ofSetLineWidth(6); ofSetCurveResolution(200); ofCircle(ofPoint((int(i / POPULATION_PER_COLUMN) * Y_SPACING) + 100, ((i % POPULATION_PER_COLUMN) * X_SPACING) + BUFFER_SPACING), 120); } myFont.drawString(population[i].genes, (int(i / POPULATION_PER_COLUMN) * Y_SPACING) + BUFFER_SPACING, ((i % POPULATION_PER_COLUMN) * X_SPACING) + BUFFER_SPACING); } }
RNA DnaConfig::add_DNA_CrossTalk(DNA& dnaTotal) { DNA dnaCrossTalk; RNA rnaCrossTalk; //Cross Talk if (m_chkCrossTalk) { dnaCrossTalk.AddCell(CrsTlk , Pn4, m_CTFE); dnaCrossTalk.AddCell(CrsTlkD, Pn4, m_CTFE); dnaCrossTalk.AddCell(CrsTlkW, Pn4, m_CTFE); } if (dnaCrossTalk.Size()) { Ts->Trans(dnaCrossTalk, rnaCrossTalk); rnaCrossTalk.SortQuackMsr(); } showRNA(rnaCrossTalk); dnaTotal += dnaCrossTalk; return rnaCrossTalk; }
GenePool::GenePool(char* filename, int nseed, int nrlock, int simtype, int runs, int smult, int lmult) { seed = nseed; reactionlock = nrlock; //for (int i = 0;i < 30;i++) //{ DNA a;a.load(filename); dnavect.push_back(a); int addfit = 0; for (int aja = 0;aja < runs;aja++) { AIPlayer ai; KeyState ks; //Random ran; GameSpace gs(1, 0, 800, 0, 600, (seed-1) + aja, true, "test.lua", "shinku.lua"); while (gs.updateGameState(ks) == 1) { ks = ai.update(&gs, gs.thePlayer, dnavect[0], ks); } addfit += gs.thePlayer->getScore()*smult; addfit += gs.thePlayer->getLives()*lmult; } fitness.push_back(addfit / runs); return; }
DNA Chromosome::getDNAObj() const { DNA ret; list<DNA>::const_iterator iter = strands.cbegin(); while (iter != strands.cend()) { ret.setDNAInParts(iter->getDNA()); iter++; } return ret; }
DNA DNA::crossover(DNA partner){ DNA child = DNA(); // Picking a random “midpoint” in the genes array int midpoint = ofRandom(genes.size()); for (int i = 0; i < genes.size(); i++) { // Before midpoint copy genes from one parent, after midpoint copy genes from the other parent if (i>midpoint) child.addGene(genes[i]); else child.addGene(partner.genes[i]); } //Return the new child DNA return child; }
void DNA::DelCell(const DNA& compData) { if (compData.Size())//裡面這些不要修改,影響再次量測的資料擺放 { std::vector<Nucleotide>::const_iterator dnaItor = 0, compItor; std::vector<Nucleotide>::iterator rmBeginItor(End()); for (compItor = compData.Begin(); compItor != compData.End(); ++compItor) rmBeginItor = std::remove(Begin(), rmBeginItor, *compItor); nChain.erase(rmBeginItor, End()); } }
void Population::reproduce() { for (int i = 0; i < popSize; i++) { int a = ofRandom(matingPool.size()); int b = ofRandom(matingPool.size()); DNA partnerA = matingPool[a]; DNA partnerB = matingPool[b]; //Step 3a: Crossover DNA child = partnerA.crossover(partnerB); //Step 3b: Mutation child.mutate(mutationRate); //Note that we are overwriting the population with the new children. When draw() loops, we will perform all the same steps with the new population of children. population[i] = child; } }
//----------------------------------------------------------------- // Crossover DNA DNA::crossover(DNA partner) { // A new child DNA child; child.setup(geneSize); //int midpoint = int(ofRandom(genes.size())); // Pick a midpoint (NO RESPECT FOR GENE INTEGRITY) int midpoint = int(ofRandom(geneSize)); // Pick a midpoint (RESPECTING GENE INTEGRITY) // Half from one, half from the other for (int i = 0; i < genes.size(); i++) { if (i > midpoint) child.genes[i] = genes[i]; else child.genes[i] = partner.genes[i]; } return child; }
// Output the DNA void Parser::print(std::ostream& iStream, const DNA& iDNA) { for (unsigned int i = 0; i < iDNA.genes(); i++) { // Extract the gene unsigned char* tGene; unsigned int tSize; iDNA.extract_gene(i, tGene, tSize); // Print the block std::cout << "* Human-readable version of block " << i << std::endl; print_block(iStream, tGene, tSize); // Free the block free(tGene); } }
af::array Synthesizer::Impl::decodeAsArray(const DNA& dna) { af::array result = af::constant(0, resultSize(), f32); unsigned dnaBeginIndex = 0; unsigned resultBeginIndex = 0; for (unsigned ruleIndex = 0; ruleIndex < rules.size(); ruleIndex++) { auto rule = rules[ruleIndex]; unsigned ruleDnaSize = rule->dnaSize(); unsigned ruleResultSize = rule->resultSize(); unsigned dnaEndIndex = dnaBeginIndex + ruleDnaSize - 1; unsigned resultEndIndex = resultBeginIndex + ruleResultSize - 1; rule->decode(make_tuple( af::array(dna.array()(af::seq(dnaBeginIndex, dnaEndIndex))), std::ref(result), af::seq(resultBeginIndex, resultEndIndex), std::ref(states[ruleIndex]))); dnaBeginIndex += ruleDnaSize; resultBeginIndex += ruleResultSize; } result.eval(); return result; }
PermutationTest& PermutationTest::permute (const char* filename, const int niter, Random &ran) { if (dna == 0) { dna = new DNA; } dna->readFASTA (filename); return permute (dna, niter, ran); }
// Evaluate DNA void Parser::evaluate(const DNA& iDNA) { // Reset the quotum mInstructionCounter = 0; // Evaluate all blocks for (unsigned int i = 0; i < iDNA.genes(); i++) { // Extract the blocks unsigned char* tGene; unsigned int tSize; iDNA.extract_gene(i, tGene, tSize); // Evaluate the block evaluate_block(tGene, tSize); // Free the block free(tGene); } }
int main() { #ifndef ONLINE_JUDGE freopen("in_2945.txt","r",stdin); #endif four[0]=1; for(int i=1;i<=20;++i) { four[i]=four[i-1]*4; } while(scanf("%d%d\n",&n,&m)&&n) { dna.clear(); memset(cnt,0,sizeof(cnt)); for(int i=0;i<n;++i) { //scanf("%s\n",&buf); gets(buf); long long tmp=0; for(int j=0;j<m;++j) { tmp+=four[j]*GetW(buf[j]); } mit=dna.find(tmp); if(mit==dna.end()) { dna[tmp]=1; } else { dna[tmp]++; } } for(mit=dna.begin();mit!=dna.end();++mit) { cnt[mit->second]++; } for(int i=1;i<=n;++i) { printf("%d\n",cnt[i]); } } return 0; }
RNA DnaConfig::add_DNA_Gamma(DNA& dnaTotal) { DNA dnaGamma; RNA rnaGamma; //Gamma if (m_chkWGamma || m_chkDGamma) dnaGamma.AddCell(White, PnGamma, m_WGammaBegin, m_WGamma_End, m_WGamma_Avg ); if (m_chkRGamma) dnaGamma.AddCell(Red , PnGamma, m_RGammaBegin, m_RGamma_End, m_RGamma_Avg ); if (m_chkGGamma) dnaGamma.AddCell(Green, PnGamma, m_GGammaBegin, m_GGamma_End, m_GGamma_Avg ); if (m_chkBGamma) dnaGamma.AddCell(Blue , PnGamma, m_BGammaBegin, m_BGamma_End, m_BGamma_Avg ); if (dnaGamma.Size()) { Ts->Trans(dnaGamma, rnaGamma); rnaGamma.SortOrigMsr(); } dnaTotal += dnaGamma; return rnaGamma; }
void Population::reproduction() { for (int i = 0; i < (int)elements.size(); i++) { elements.at(i)->computeFitness(target); } vector<DNA *> pool = matingPool(); for (int i = 0; i < (int)elements.size(); i++) { DNA * partnerA = pool.at(randInt(pool.size())); DNA * partnerB = pool.at(randInt(pool.size())); DNA * child = partnerA->crossover(partnerB); child->mutate(mutationRate); elements.at(i) = child; } }
tsp_individual_multi::DNA tsp_individual_multi::translateToDnaPhenotypicOrdinal(const DNA trait){ DNA ordinal; DNA tmp; for(int i=0;i<trait.size();i++){ tmp.push_back(i); } ordinal.resize(trait.size()); for(int i=0;i<trait.size();i++){ ordinal[i] = tmp[trait[i]]; tmp.erase(tmp.begin() + trait[i]); } return ordinal; }
vector<DNA<false>> FrequentWords(const DNA<IsCyclic>& dnaString, int k) { //Initialize dictionary unordered_map<DNA<false>, int> counts{ }; size_t n{ dnaString.size() }; //Fill dictionary and count kmer frequencies int maxCount{ 1 }; for (size_t i = 0; i < n - k + 1; i++) { DNA<false> part{ dnaString.slice(i, k) }; auto it = counts.find(part); if (it == end(counts)) { counts[part] = 1; } else { it->second++; if (maxCount < it->second) maxCount = it->second; }; }; //Extract most frequent words vector<DNA<false>> most_frequent_words{ }; for (auto& p : counts) if (p.second == maxCount) most_frequent_words.push_back(p.first); return most_frequent_words; };
DNA* initSultan3(int& m, int& n) { SmartArrayPtr<double> *diag, *sdiag, *kap; m = 3; n = 4; DNA* dna = new DNA(n, n - m); diag = dna->getDiag(); sdiag = dna->getSDiag(); kap = dna->getKap(); diag->alloc(3); sdiag->alloc(3); kap->alloc(3); (*diag)[0] = 0.; (*diag)[1] = 0.; (*diag)[2] = 0.; (*sdiag)[0] = 1.; (*sdiag)[1] = 1.; (*kap)[0] = 6.; (*kap)[1] = 5.1; (*kap)[2] = 3.9; return dna; }
tsp_individual_multi::DNA tsp_individual_multi::translateToDnaPhenotypicTrait(const DNA ordinal){ DNA trait; DNA tmp; for(int i=0;i<ordinal.size();i++){ tmp.push_back(i); } for(int i=0;i<ordinal.size();i++){ for(int j=0;j<tmp.size();j++){ if(ordinal[i] == tmp[j]){ trait.push_back(j); tmp.erase(tmp.begin() + j); break; } } } return trait; }
PermutationTest& PermutationTest::permute (DNA *dna_in, const int niter, Random &ran) { dna = dna_in; int i, j, k, pos; /* Find out which sites are bi-allelic segregating */ /* (segregating for short) */ char state1, state2; vector<bool> segregating (dna->lseq); for (i = 0; i < dna->lseq; i++) { segregating[i] = false; state1 = (*dna) [0][i]; for (j = 1; j < dna->nseq; j++) if ( (*dna) [j][i] != state1) { state2 = (*dna) [j][i]; segregating[i] = true; j++; for (; j < dna->nseq; j++) if ( (*dna) [j][i] != state1 && (*dna) [j][i] != state2) { /* Tri-allelic segregating */ segregating[i] = false; break; } break; } } /* Count number of segregating sites */ int nseg = 0; for (i = 0; i < dna->lseq; i++) if (segregating[i]) { nseg++; } if (nseg == 0) { error ("No segregating sites found"); } /* Copy segregating sites to a new DNA object */ sdna.resize (dna->nseq, nseg); vector<double> d (nseg, 0.0); for (i = 0, pos = 0; i < dna->lseq; i++) if (segregating[i]) { for (j = 0; j < dna->nseq; j++) { sdna[j][pos] = (*dna) [j][i]; } d[pos] = (double) i; ++pos; } /* Calculate frequency statistics */ vector<double> F (sdna.lseq, 1.0); /* F is the marginal frequency of the dna[0][i] (A) allele at site i */ vector<double> four (4, 0.0); /* G[i][j] is the frequency of AB (G[i][j][0]), Ab (1), aB (2), ab (3) */ LowerTriangularMatrix< vector<double> > G (sdna.lseq, four); for (i = 0; i < sdna.lseq; i++) { state1 = sdna[0][i]; for (j = 1; j < sdna.nseq; j++) if (sdna[j][i] == state1) { F[i]++; } F[i] /= (double) sdna.nseq; } for (i = 0; i < sdna.lseq; i++) for (j = 0; j < i; j++) { state1 = sdna[0][i]; state2 = sdna[0][j]; for (k = 0; k < sdna.nseq; k++) { if (sdna[k][i] == state1 && sdna[k][j] == state2) { ++G[i][j][0]; } else if (sdna[k][i] == state1 && sdna[k][j] != state2) { ++G[i][j][1]; } else if (sdna[k][i] != state1 && sdna[k][j] == state2) { ++G[i][j][2]; } else if (sdna[k][i] != state1 && sdna[k][j] != state2) { ++G[i][j][3]; } else { warning ("Unexpected choice"); } } for (k = 0; k < 4; k++) { G[i][j][k] /= (double) sdna.nseq; } } /* Calculate LD statistics for pairs of sites */ LowerTriangularMatrix<double> A (nseg, 0.0); LowerTriangularMatrix<double> B (nseg, 0.0); LowerTriangularMatrix<double> C (nseg, 0.0); Matrix<double> D (nseg, nseg, 0.0); double temp; // ofstream out("__out.txt"); // char tab = '\t'; // out << "locusA" << tab << "locusB" << tab << "rsq" << tab << "Dprime" << tab << "G4" << "dist" << endl; for (i = 0; i < nseg; i++) { for (j = 0; j < i; j++) { temp = G[i][j][0] - F[i] * F[j]; A[i][j] = pow (temp, 2.0) / (F[i] * (1. - F[i]) * F[j] * (1. - F[j]) ); B[i][j] = (temp < 0.0) ? -temp / MIN (F[i] * F[j], (1. - F[i]) * (1. - F[j]) ) : temp / MIN (F[i] * (1. - F[j]), (1. - F[i]) * F[j]); C[i][j] = (G[i][j][0] > 0.0 && G[i][j][1] > 0.0 && G[i][j][2] > 0.0 && G[i][j][3] > 0.0) ? 1.0 : 0.0; D[i][j] = D[j][i] = d[i] - d[j]; // out << i << tab << j << tab << A[i][j] << tab << B[i][j] << tab << C[i][j] << tab << D[i][j] << endl; } } // out.close(); /* Calculate remaining statistics for correlation coefficients */ double Abar, Bbar, Cbar, Dbar; double Adev, Bdev, Cdev, Ddev; Abar = Bbar = Cbar = Dbar = Adev = Bdev = Cdev = Ddev = 0.0; double ctr = 0.0; for (i = 0; i < nseg; i++) for (j = 0; j < i; j++, ctr++) { Abar += A[i][j]; Bbar += B[i][j]; Cbar += C[i][j]; Dbar += D[i][j]; } Abar /= ctr; Bbar /= ctr; Cbar /= ctr; Dbar /= ctr; for (i = 0; i < nseg; i++) for (j = 0; j < i; j++) { Adev += pow (A[i][j] - Abar, 2.0); Bdev += pow (B[i][j] - Bbar, 2.0); Cdev += pow (C[i][j] - Cbar, 2.0); Ddev += pow (D[i][j] - Dbar, 2.0); } /* Perform the permutation tests */ double a, b, c, pa, pb, pc; double PA, PB, PC, dist; a = b = c = 0.0; for (j = 0; j < nseg; j++) for (k = 0; k < j; k++) { a += A[j][k] * D[j][k]; b += B[j][k] * D[j][k]; c += C[j][k] * D[j][k]; } double Aadd = ctr * Abar * Dbar; double Adiv = sqrt (Adev * Ddev); double Badd = ctr * Bbar * Dbar; double Bdiv = sqrt (Bdev * Ddev); double Cadd = ctr * Cbar * Dbar; double Cdiv = sqrt (Cdev * Ddev); a -= Aadd; a /= Adiv; b -= Badd; b /= Bdiv; c -= Cadd; c /= Cdiv; PA = PB = PC = 0.0; vector<int> order (sdna.lseq); vector<int> pool (sdna.lseq); for (i = 0; i < niter; i++) { for (j = 0; j < nseg; j++) { pool[j] = j; } for (j = nseg - 1; j >= 0; j--) { pos = ran.discrete (0, j); order[j] = pool[pos]; pool[pos] = pool[j]; } pa = pb = pc = 0.0; for (j = 0; j < nseg; j++) for (k = 0; k < j; k++) { dist = D[order[j]][order[k]]; pa += A[j][k] * dist; pb += B[j][k] * dist; pc += C[j][k] * dist; } pa -= Aadd; pa /= Adiv; pb -= Badd; pb /= Bdiv; pc -= Cadd; pc /= Cdiv; if (pa <= a) { ++PA; } if (pb <= b) { ++PB; } if (pc >= c) { ++PC; } } p[0] = (PA + 1.) / (double) (niter + 1); v[0] = a; p[1] = (PB + 1.) / (double) (niter + 1); v[1] = b; p[2] = (PC + 1.) / (double) (niter + 1); v[2] = c; if (coutput) { printResults(); } return *this; }
void Chromosome::addDNA(const DNA & dna) { strands.push_back(dna); entireDNA += dna.getDNA(); }
list<CalculatedOligo> OligoAnalisys::performAnalysis(DNA seq, DNA learningSeq, double n, int oligoLength) { list<CalculatedOligo> calOlig; map<string, kmerFreq> freq; map<string, kmerFreq>::iterator it; map<string, Prefix> matrix; CalculatedOligo olig; int S = seq.chain.size(); int learningSeqSize = 0; int T = 0; int L = 0; int seqTotalsize = 0; for (int i = 0; i < learningSeq.chain.size(); ++i) { learningSeqSize = learningSeqSize + learningSeq.chain[i].length(); } for (int i = 0; i < S; ++i) { L = L + (seq.chain[i].length() - oligoLength + 1); } T = 2 * L; for (int m = 0; m < S; ++m) { seq.addSeq(seq.chain[m].reverse_compliment()); } for (int k = 0; k < (2 * S); ++k) { seqTotalsize = seqTotalsize + seq.chain[k].length(); } cout << " L " << L << endl; cout << " T " << T << endl; cout << " learningSeqSize " << learningSeqSize << endl; cout << " seqTotalsize " << seqTotalsize << endl; freq = computeTotalFrequency(learningSeq, 3, learningSeqSize); matrix = buildTransitionTable(freq); freq = computeTotalFrequency(seq, 6, seqTotalsize); for (it = freq.begin(); it != freq.end(); ++it) { olig.setOlig(it->second.getOlig()); olig.setFreq(it->second.getFreq()); olig.setOccurrences(it->second.getOccurrences()); olig.setExpFreq(scoreSeqMarkov(it->second.getOlig(), 2, matrix)); olig.setExpOcc(olig.getExpFreq() * T); olig.setOccP( binomialPValue(T, olig.getExpFreq(), it->second.getOccurrences())); olig.setOccE( probOccBGreater(olig.getExpFreq(), T, it->second.getOccurrences())); olig.setOccSig(sigValue(olig.getOccE(), oligoLength)); calOlig.push_back(olig); /* cout << "Seq " << olig.getOlig().seq << " freq " << olig.getFreq() << " exp_freq " << olig.getExpFreq() << " occ " << olig.getOccurrences() << " exp_occ " << olig.getExpOcc() << " Binomial " << olig.getOccP() << " Occ_E " << olig.getOccE() << " sig " << olig.getOccSig() << endl; */ } calOlig.sort(compareOccSig); return calOlig; }
Chromosome::Chromosome(DNA dna) { entireDNA = dna.getDNA(); strands.push_back(dna); }
RNA DnaConfig::add_DNA_WRGBD(DNA& dnaTotal) { DNA dnaSortStable; RNA rnaSortStable; //修改的話,要同步修改 //中心點 if (m_chkWP1) dnaSortStable.AddCell(White, Pn1); if (m_chkRP1) dnaSortStable.AddCell(Red , Pn1); if (m_chkGP1) dnaSortStable.AddCell(Green, Pn1); if (m_chkBP1) dnaSortStable.AddCell(Blue , Pn1); if (m_chkDP1) dnaSortStable.AddCell(Dark , Pn1); //Nits if (m_chkNits) dnaSortStable.AddCell(Nits, Pn9, m_NitsLv, m_NitsDirect); //5點 if (m_chkWP5) dnaSortStable.AddCell(White, Pn5, m_W5FE); // if (m_chkRP5) dnaSortStable.AddCell(Red , Pn5, W5FE); // if (m_chkGP5) dnaSortStable.AddCell(Green, Pn5, W5FE); // if (m_chkBP5) dnaSortStable.AddCell(Blue , Pn5, W5FE); // if (m_chkDP5) dnaSortStable.AddCell(Dark , Pn5, W5FE); //9點 if (m_chkWP9) dnaSortStable.AddCell(White, Pn9, m_W9FE, m_W9EdgeType); // if (m_chkRP9) dnaSortStable.AddCell(Red , Pn9, W9FE, PA_FEover); // if (m_chkGP9) dnaSortStable.AddCell(Green, Pn9, W9FE, PA_FEover); // if (m_chkBP9) dnaSortStable.AddCell(Blue , Pn9, W9FE, PA_FEover); if (m_chkDP9) dnaSortStable.AddCell(Dark , Pn9, m_D9FE, m_D9EdgeType); //21點 // if (m_chkWP21) dnaSortStable.AddCell(White, Pn21, D21FE); // if (m_chkRP21) dnaSortStable.AddCell(Red , Pn21, D21FE); // if (m_chkGP21) dnaSortStable.AddCell(Green, Pn21, D21FE); // if (m_chkBP21) dnaSortStable.AddCell(Blue , Pn21, D21FE); if (m_chkDP21) dnaSortStable.AddCell(Dark , Pn21, m_D21FE); //13點 // if (m_chkWP13) dnaSortStable.AddCell(White, Pn13, D13FE); // if (m_chkRP13) dnaSortStable.AddCell(Red , Pn13, D13FE); // if (m_chkGP13) dnaSortStable.AddCell(Green, Pn13, D13FE); // if (m_chkBP13) dnaSortStable.AddCell(Blue , Pn13, D13FE); if (m_chkDP13) dnaSortStable.AddCell(Dark , Pn13, m_D13FE); //25點 // if (m_chkWP25) dnaSortStable.AddCell(White, Pn25, D25FE, D25RectSide); // if (m_chkRP25) dnaSortStable.AddCell(Red , Pn25, D25FE, D25RectSide); // if (m_chkGP25) dnaSortStable.AddCell(Green, Pn25, D25FE, D25RectSide); // if (m_chkBP25) dnaSortStable.AddCell(Blue , Pn25, D25FE, D25RectSide); if (m_chkDP25) dnaSortStable.AddCell(Dark , Pn25, m_D25FE, m_D25RectSide); //49點 if (m_chkWP49) dnaSortStable.AddCell(White, Pn49); // if (m_chkRP49) dnaSortStable.AddCell(Red , Pn49); // if (m_chkGP49) dnaSortStable.AddCell(Green, Pn49); // if (m_chkBP49) dnaSortStable.AddCell(Blue , Pn49); // if (m_chkDP49) dnaSortStable.AddCell(Dark , Pn49); if (dnaSortStable.Size()) { Ts->Trans(dnaSortStable, rnaSortStable); //排序 if (m_msrQuick) rnaSortStable.SortQuackMsr(); else rnaSortStable.SortOrigMsr(); } showRNA(rnaSortStable); dnaTotal += dnaSortStable; return rnaSortStable; }
main() { //STEP 0 //make my boxes //for i in 50, new Box() for (int i=0; i<BOXNUM; i++) { box[i]=new Box(); cout<<"Box "<<i<<": w="<<box[i]->weight<<", v="<<box[i]->value<<endl; } //verify by print all the boxes and weights //while our population is less than the initial population // dna[i]=new DNA() // only add it if the weight below 1000 while(population < INITIAL_POPULATION) { DNA* d = new DNA(); if(d->getWeight()<=1000) { dna[population]=d; population++; } } //for loop # of generations // figure out who the best is and print out its dna/weight/value // kill //bubble sort by value for(int i=0; i<population; i++) { for (int j=0; j<population-1; j++) { if(dna[j+1]->getValue() > dna[j]->getValue()) { DNA* temp = dna[j+1]; dna[j+1]=dna[j]; dna[j]=temp; } } } population=SURVIVORS; //set population = SURVIVORS cout << "DNA 0 has "<< dna[0]->getWeight() << " "<<dna[0]->getValue()<<endl; cout << "DNA 1 has "<< dna[1]->getWeight() << " "<<dna[1]->getValue()<<endl; // breed int breedingpopulation=population; //go through every possible pair for(int i=0; i<breedingpopulation; i++) { for(int mom=0; mom<breedingpopualtion; mom++) { if(mom==dad) //can't breed with self continue; DNA *baby = new DNA(); //copy over from dad for(int k=0; k<crossoverpoint; k++) //copy over from mom { baby->boxes[k]=dna[dad]->boxes[k]; } for(int k=crossoverpoint; k>BOXDNA; k++) //keep the baby { baby->boxes[k]=dna[mom]->boxes[k]; } if (baby->getweight()>1000) //1000 garbage collect the baby continue; dna[population++]=baby; cout << "daddy is " << dna[dad]->getValue() << ", mommy is " << dna[mom]->getValue << "baby is " << dna[population] << endl; } } // mutate int cloningpopulation = population; for(int i=0; i<cloningpopulation; i++) { if(rand()%100 < DOMUTATERATE) { DNA* mutant = new DNA(); for(int j=0; j<BOXNUM; j++) { mutant->boxes[j] = dna[i]->boxes[j] } cout << "Making a clone: parent: " << dna[i]->getValue() << " spawn: " >> mutant->getValue() << endl; for(int j=0; j<BOXNUM; j++) { if (rand()%100 < MUTATIONRATE) { mutant->boxes[j] = !mutant->boxes[j]; { } cout << "spawn: " << mutant->getValue() << endl; if(mutant->getWeight()<=1000) dna[population++]=mutant; } } }
//void GenePool::updatePool(double crossover, double mutationchance, double severity, int tourneysize, int gen) void GenePool::doPool(int maxsize, int deltype, int tourneysize, double crossover, double mutationchance, double severity, int numgens, double mutdev, double jostlechance, int simtype, int runs, int smult, int lmult) { int top = 1; DNA thedna; //set by mutate/breed for (int fill = 1;fill < maxsize;fill++) { dnavect.push_back(thedna); fitness.push_back(-1); } //printf("fitness[%d] = %d ; cycle = %d\n", num, fitness[num], gs.cycle); //if (fitness[num] < 0) {dnavect[num].save("bad.dna");} //delete if needed int tourney[tourneysize]; Random ran; for (int vvi = 0;vvi < numgens;vvi++) { //int selected[5]; //the index of tourney selected dudes //printf("ms1\n"); int sa = 0;int sb = 0; //the two selected to mate //pick best 'tourneysize' from the tourney //printf("ms2\n"); //select sample for tourney for (int ii = 0;ii < tourneysize; ii++) { tourney[ii] = ran.nextInt(top); } int highestfit = -1;int highestfitindex = 0; //printf("ms3\n"); for (int b = 0;b < tourneysize;b++) { if (fitness[tourney[b]] > highestfit) {highestfit = fitness[tourney[b]];highestfitindex = tourney[b];} } sa = highestfitindex; //printf("ms4\n"); for (int ii = 0;ii < tourneysize; ii++) { tourney[ii] = ran.nextInt(top); } highestfit = -1;highestfitindex = 0; //printf("ms5\n"); for (int b = 0;b < tourneysize;b++) { if (fitness[tourney[b]] > highestfit) {highestfit = fitness[tourney[b]];highestfitindex = tourney[b];} } sb = highestfitindex; //printf("ms6\n"); //breed and mutate x1 int inf1 = vvi;int inf2 = sa;int inf3 = fitness[sa];int inf4 = sb;int inf5 = fitness[sb]; thedna = this->dnavect[sa].mate(dnavect[sb], crossover, reactionlock); //printf("msvv\n"); double fmut = ran.nextGaussian()*mutdev+mutationchance; thedna.mutate(fmut, severity, reactionlock, jostlechance); //printf("ms7\n"); int putwhere = 0; if (top == maxsize) { if (deltype == 0) { int lowest = -1; int lowestindex = 0; for(int i = 0;i < top;i++) { if ((fitness[i] < lowest) || lowest == -1) {lowest = fitness[i]; lowestindex = i;} } //printf("ms8\n"); putwhere = lowestindex; dnavect[putwhere] = thedna; } if (deltype == 1) //random del { putwhere = ran.nextInt(top); dnavect[putwhere] = thedna; } if (deltype == 2) { for (int ii = 0;ii < tourneysize; ii++) { tourney[ii] = ran.nextInt(top); } int lowfit = -1;int lowfitindex = 0; for (int b = 0;b < tourneysize;b++) { if (fitness[tourney[b]] < lowfit || lowfit == -1) {lowfit = fitness[tourney[b]];lowfitindex = tourney[b];} } putwhere = lowfitindex; dnavect[putwhere] = thedna; } } else { putwhere = top;top++; dnavect[putwhere] = thedna; //dnavect.push_back(thedna); } //printf("ms9\n"); int inf6 = putwhere;int inf7=fitness[putwhere]; this->simulate(putwhere, simtype, runs, smult, lmult); printf("Creature: %d\n", inf1); printf("mate1: %d, mate1fit: %d, mate2: %d, mate2fit: %d\n",inf2, inf3, inf4, inf5); printf("Final Mutation Chance: %lf\n", fmut); printf("Fitness of this creature: %d\n", fitness[putwhere]); printf("Overwrite Number: %d, Overwrite Fitness: %d\n", inf6, inf7); printf("POOL INFO: Best: %d, Worst: %d, Mean: %g, StdDev: %g\n\n\n", this->bestFitness(top), this->worstFitness(top), this->meanFitness(top), this->standardDeviation(top)); //do milestone save here } }
int main(int argc, char **argv) { if (argc <= 1) { printf("Usage: %s infile\n", argv[0]); return 1; } FILE *fp = fopen(argv[1], "rb"); if (!fp) { printf("File loading failed %s\n", argv[1]); return 1; } fseek(fp, 0L, SEEK_END); int len = ftell(fp); fseek(fp, 0L, SEEK_SET); char *buf = new char[len+1]; fread(buf, len, 1, fp); fclose(fp); bool blender = !strncmp("BLENDER", buf, 6); bool bullet = !strncmp("BULLET", buf, 5); if (!blender && !bullet) { printf("Invalid header, compressed file ?\n"); delete []buf; return 1; } char *ver = buf+9; int version = atoi(ver); bool is64Bit = false; if (buf[7]=='-') is64Bit = true; int dnastart = -1; char *tbuf = buf; for (int i=0; i<len; ++i) { if (!strncmp("SDNA", tbuf, 4)) { dnastart = i; break; } ++tbuf; } if (dnastart != -1) { DNA *dna = new DNA; dna->parse(buf + dnastart); char specname[12], fname[12]; sprintf(specname, "%s", (bullet ? "Bullet" : "Blender")); sprintf(fname, "%s.h", (bullet ? "Bullet" : "Blender")); FILE *bfp= fopen(fname, "wb"); if (bfp) { printf("Writing %s header from file version %i...\n", specname, version); fprintf(bfp, "#ifndef _%s_h_\n", specname); fprintf(bfp, "#define _%s_h_\n", specname); fprintf(bfp, "// Generated from a %s(%i) file.\n\n", specname, version); if (blender) { fprintf(bfp, "#ifdef near\n"); fprintf(bfp, "#undef near\n"); fprintf(bfp, "#endif\n"); fprintf(bfp, "#ifdef far\n"); fprintf(bfp, "#undef far\n"); fprintf(bfp, "#endif\n"); fprintf(bfp, "#ifdef rad2\n"); fprintf(bfp, "#undef rad2\n"); fprintf(bfp, "#endif\n"); } fprintf(bfp, "\n\n"); fprintf(bfp, "namespace %s {\n", specname); #if ADD_DOXYGEN_COMMENTS fprintf(bfp, "/** \\addtogroup %s\n" "* @{\n" "*/\n\n", specname ); #endif dumpStructs(bfp, dna); #if ADD_DOXYGEN_COMMENTS fprintf(bfp, "/** @}*/\n"); #endif fprintf(bfp, "}\n"); fprintf(bfp, "#endif//_%s_h_\n", specname); fclose(bfp); } #if WRITE_DNA_FILE char name[32]; sprintf(name, "dna_%i_%s.cpp", version, (is64Bit ? "64" : "32")); bfp= fopen(name, "wb"); if (bfp) { printf("Writing %s bit DNA...\n", (is64Bit ? "64" : "32")); fprintf(bfp, "unsigned char DNAstr%s[]={\n ", (is64Bit ? "64" : "")); char *dnaStr = buf + dnastart; for (int d=0; d<len-dnastart; ++d) { unsigned char uch = (unsigned char)dnaStr[d]; fprintf(bfp, "0x%02X,", uch); if (d %24 == 23) fprintf(bfp, "\n "); } fprintf(bfp, "\n};\n"); fprintf(bfp, "int DNAlen%s=sizeof(DNAstr%s);\n", (is64Bit ? "64" : ""), (is64Bit ? "64" : "")); fclose(bfp); } #endif delete dna; } delete []buf; return 0; }
void DNA::AddCell(const DNA& _D) { nChain.insert(End(), _D.Begin(), _D.End()); }