本文整理汇总了C++中GAPopulation类的典型用法代码示例。如果您正苦于以下问题:C++ GAPopulation类的具体用法?C++ GAPopulation怎么用?C++ GAPopulation使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GAPopulation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1:
/// This is the default population initializer. It simply calls the initializer
/// for each member of the population. Then we touch the population to tell it
/// that it needs to update stats and/or sort (but we don't actually force
/// either one to occur.
/// The population object takes care of setting/unsetting the status flags.
void
GAPopulation::DefaultInitializer(GAPopulation & p)
{
for(int i = 0; i < p.size(); i++)
{
p.individual(i).initialize();
}
}
示例2:
// This is an implementation of the sigma truncation scaling method descibed in
// goldberg p 124. If the scaled fitness is less than zero, we arbitrarily set
// it to zero (thus the truncation part of 'sigma truncation').
void
GASigmaTruncationScaling::evaluate(const GAPopulation & p) {
for(int i=0; i<p.size(); i++){
double f = (double)(p.individual(i).score()) - (double)(p.ave());
f += (double)c * (double)(p.dev());
if(f < 0) f = 0.0;
p.individual(i).fitness((float)f); // might lose information here!
}
}
示例3: RecvPopulation
// This assumes that the original population contains at least one individual
// from which to grow. If it does not, the data in the buffer will be ignored.
int
RecvPopulation(GAPopulation& pop) {
int status = 0;
int psize = 0;
status = pvm_upkint(&psize, 1, 1);
pop.size(psize);
for(int i=0; i<pop.size() && status>=0; i++)
status = UnpackIndividual(pop.individual(i));
return status;
}
示例4: SendPopulation
// This should eventually use a genome member function rather than an external.
// When we pack/unpack a population we also stuff its statistics.
int
SendPopulation(int toid, const GAPopulation& pop) {
int status = 0;
int psize = pop.size();
status = pvm_initsend(PvmDataDefault);
status = pvm_pkint(&psize, 1, 1);
for(int i=0; i<pop.size() && status>=0; i++)
status = PackIndividual(pop.individual(i));
status = pvm_send(toid, MSG_INCOMING_POPULATION);
return status;
}
示例5: initGA
void Evolver::initGA(float pMutation, int popSize, GABoolean elitist) {
GAPopulation pop;
for (; popSize > 0; --popSize) {
try {
Composition *c = new Composition();
SampleBank::getInstance().initComposition(*c);
pop.add(c);
} catch (std::bad_alloc & e) {
throw std::runtime_error("couldn't alloc new composition");
}
}
initGA(pMutation, elitist, 0, pop);
}
示例6: GAErr
// This is an implementation of the most basic form of power scaling, where the
// fitness is a function of the objective score raised to some power. Negative
// objective scores are not allowed. If we get one, we post an error and set
// all of the fitness scores to zero.
void
GAPowerLawScaling::evaluate(const GAPopulation & p) {
for(int i=0; i<p.size(); i++){
double f = p.individual(i).score();
if(f < 0.0){
GAErr(GA_LOC, className(), "evaluate", gaErrPowerNegFitness);
for(int ii=0; ii<p.size(); ii++)
p.individual(ii).fitness(0.0);
return;
}
f = pow(f,(double)k);
p.individual(i).fitness((float)f); // might lose information here!
}
}
示例7: stats
GAGeneticAlgorithm::GAGeneticAlgorithm(const GAPopulation& p) :
stats(), params() {
pop = new GAPopulation(p);
pop->geneticAlgorithm(*this);
ud = nullptr;
cf = GAGeneticAlgorithm::DEFAULT_TERMINATOR;
d_seed = gaDefSeed;
params.add(gaNseed, gaSNseed, GAParameter::INT, &d_seed);
minmax = gaDefMiniMaxi;
params.add(gaNminimaxi, gaSNminimaxi, GAParameter::INT, &minmax);
ngen = gaDefNumGen;
params.add(gaNnGenerations, gaSNnGenerations, GAParameter::INT, &ngen);
nconv = gaDefNConv; stats.nConvergence(nconv);
params.add(gaNnConvergence, gaSNnConvergence, GAParameter::INT, &nconv);
pconv = gaDefPConv;
params.add(gaNpConvergence, gaSNpConvergence, GAParameter::FLOAT, &pconv);
pcross = gaDefPCross;
params.add(gaNpCrossover, gaSNpCrossover, GAParameter::FLOAT, &pcross);
pmut = gaDefPMut;
params.add(gaNpMutation, gaSNpMutation, GAParameter::FLOAT, &pmut);
int psize = pop->size();
params.add(gaNpopulationSize, gaSNpopulationSize, GAParameter::INT, &psize);
stats.scoreFrequency(gaDefScoreFrequency1);
params.add(gaNscoreFrequency, gaSNscoreFrequency,
GAParameter::INT, &gaDefScoreFrequency1);
stats.flushFrequency(gaDefFlushFrequency);
params.add(gaNflushFrequency, gaSNflushFrequency,
GAParameter::INT, &gaDefFlushFrequency);
stats.recordDiversity(gaDefDivFlag);
params.add(gaNrecordDiversity, gaSNrecordDiversity,
GAParameter::INT, &gaDefDivFlag);
stats.scoreFilename(gaDefScoreFilename);
params.add(gaNscoreFilename, gaSNscoreFilename,
GAParameter::STRING, gaDefScoreFilename);
stats.selectScores(gaDefSelectScores);
params.add(gaNselectScores, gaSNselectScores,
GAParameter::INT, &gaDefSelectScores);
stats.nBestGenomes(p.individual(0), gaDefNumBestGenomes);
params.add(gaNnBestGenomes, gaSNnBestGenomes,
GAParameter::INT, &gaDefNumBestGenomes);
scross = p.individual(0).sexual();
across = p.individual(0).asexual();
}
示例8:
// Set the score info to the appropriate values. Update the score count.
void
GAStatistics::setScore(const GAPopulation& pop){
aveCur = pop.ave();
maxCur = pop.max();
minCur = pop.min();
devCur = pop.dev();
divCur = ((dodiv == gaTrue) ? pop.div() : (float)-1.0);
if(Nscrs == 0) return;
gen[nscrs] = curgen;
aveScore[nscrs] = aveCur;
maxScore[nscrs] = maxCur;
minScore[nscrs] = minCur;
devScore[nscrs] = devCur;
divScore[nscrs] = divCur;
nscrs++;
}
示例9: GAGeneticAlgorithm
GADemeGA::GADemeGA(const GAPopulation& p) : GAGeneticAlgorithm(p) {
if(p.size() < 1) {
GAErr(GA_LOC, className(), "GADemeGA(GAPopulation&)", gaErrNoIndividuals);
pop = 0; nrepl = 0; tmppop = 0; pstats = 0;
}
else {
npop = gaDefNPop;
params.add(gaNnPopulations, gaSNnPopulations, GAParameter::INT, &npop);
nmig = gaDefNMig;
params.add(gaNnMigration, gaSNnMigration, GAParameter::INT, &nmig);
unsigned int nr = pop->size()/2;
nrepl = new int [npop];
deme = new GAPopulation* [npop];
pstats = new GAStatistics [npop];
tmppop = new GAPopulation(p.individual(0), nr);
for(unsigned int i=0; i<npop; i++) {
nrepl[i] = nr;
deme[i] = new GAPopulation(p);
}
}
}
示例10: main
int main(int argc, const char * argv[])
{
srand((unsigned)time(NULL));
printf("Running Genetic Algorithm...\n");
printf("Target Genes: %s\n", kTargetGenes.c_str());
printf("Population Size: %d\n", kPopulationSize);
printf("Elitism: %s\n", (kElitismEnabled ? "true" : "false"));
printf("Elitism Percentage: %d%%\n", kElitismPercentage);
printf("Mutation Probability: %d%%\n", kMutationProbability);
printf("Crossover Probability: %d%%\n\n", kCrossoverProbability);
GAPopulation population = GAPopulation(kPopulationSize, kTargetGenes);
population.elitismEnabled = kElitismEnabled;
population.tournamentSize = kTournamentSize;
population.elitismPercentage = PERCENTAGE(kElitismPercentage);
population.mutationProbability = PERCENTAGE(kMutationProbability);
population.crossoverProbability = PERCENTAGE(kCrossoverProbability);
population.selectionType = GAPopulationSelectionType::GAPopulationSelectionTypeTournament;
population.crossoverType = GAPopulationCrossoverType::GAPopulationCrossoverTypeOnePoint;
population.evolve();
return 0;
}
示例11: if
void
GALinearScaling::evaluate(const GAPopulation & p) {
// Here we calculate the slope and intercept using the multiplier and objective
// score ranges...
double pmin = p.min();
double pmax = p.max();
double pave = p.ave();
double delta, a, b;
if(pave == pmax){ // no scaling - population is all the same
a = 1.0;
b = 0.0;
}
else if(pmin > ((double)c * pave - pmax)/((double)c - 1.0)){
delta = pmax - pave;
a = ((double)c - 1.0) * pave / delta;
b = pave * (pmax - (double)c * pave) / delta;
}
else{ // stretch to make min be 0
delta = pave - pmin;
a = pave / delta;
b = -pmin * pave / delta;
}
// and now we calculate the scaled scaled values. Negative scores are not
// allowed with this kind of scaling, so check for negative values. If we get
// a negative value, dump an error message then set all of the scores to 0.
for(int i=0; i<p.size(); i++){
double f = p.individual(i).score();
if(f < 0.0){
GAErr(GA_LOC, className(), "evaluate", gaErrNegFitness);
for(int ii=0; ii<p.size(); ii++)
p.individual(ii).fitness(0.0);
return;
}
f = f * a + b;
if(f < 0) f = 0.0; // truncate if necessary (only due to roundoff error)
p.individual(i).fitness((float)f); // might lose information here!
}
}
示例12: PopulationEvaluator
// This population evaluator is the administrator for the parallelization.
// It looks around to see when slaves are available to evaluate a genome. As
// soon as a slave is available and a genome needs to be evaluated, this
// routine sends it off. When a slave is finished, it posts a message to
// say so and this routine gets the message and grabs the results from the
// slave that posted the message.
// An index of -1 means that the slave has no assignment. The first int in
// the stream of stuff is always the ID of the slave (0-nslaves) that is
// sending the information. After that it is either nothing (the slave just
// reported that it is ready for another genome) or it is a float (the score
// of the genome that was assigned to the slave).
void
PopulationEvaluator(GAPopulation& pop) {
PVMDataPtr data = (PVMDataPtr)pop.userData();
int* index = new int [data->nreq];
int done = 0, outstanding = 0, next = 0;
int bufid, status, bytes, msgtag, tid, who;
while(!done) {
// If we have a genome that needs to be evaluated and one of the slaves is
// ready to evaluate it, send the genome to the slave.
if(next < pop.size() && (bufid=pvm_nrecv(-1, MSG_READY)) != 0) {
if(bufid > 0) {
pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
status = SendGenomeData(pop.individual(next), tid);
if(status >= 0) {
if((who = id2idx(tid, *data)) >= 0) {
index[who] = next; next++;
outstanding++;
}
else {
cerr << "PopEval: bogus tid mapping: " << tid << "\n";
}
}
else {
cerr << "PopEval: error sending data to: " << tid;
cerr << " error code is: " << status << "\n";
}
}
else {
cerr << "PopEval: error from pvm_nrecv: " << bufid << "\n";
}
}
// If we have any genomes waiting for their evaluation and any slaves have
// posted a message stating that they have a finished score ready for us, get
// the score from the slave and stuff it into the appropriate genome.
if(outstanding > 0 && (bufid=pvm_nrecv(-1, MSG_GENOME_SCORE)) != 0) {
if(bufid > 0) {
pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
if((who = id2idx(tid, *data)) >= 0) {
if(index[who] >= 0) {
status = RecvGenomeScore(pop.individual(index[who]));
if(status >= 0) {
index[who] = -1;
outstanding--;
}
else {
cerr << "PopEval: error receiving score from: " << tid;
cerr << " error code is: " << status << "\n";
}
}
else {
cerr << "PopEval: index conflict from tid " << tid << "\n";
}
}
else {
cerr << "PopEval: bogus tid mapping: " << tid << "\n";
}
}
else {
cerr << "PopEval: error from pvm_nrecv: " << bufid << "\n";
}
}
if(next == pop.size() && outstanding == 0) done = 1;
if(next > pop.size()) {
cerr << "bogus value for next: " << next;
cerr << " popsize is: " << pop.size() << "\n";
}
}
delete [] index;
}
示例13: PopulationInitializer
// The population initializer invokes the genomes' initializers just like the
// standard population initializer, but here we farm out the genomes to the
// slaves before invoking the initialization. Farm out the genomes and give
// the slaves the initialize command rather than the evaluate command.
void
PopulationInitializer(GAPopulation& pop) {
PVMDataPtr data = (PVMDataPtr)pop.userData();
int* index = new int [data->nreq];
int done = 0, outstanding = 0, next = 0;
int bufid, status, bytes, msgtag, tid, who;
while(!done) {
// If we have a genome that needs to be initialized and one of the slaves is
// available, then ask the slave to configure a genome and send us back the
// configured, initialized genome.
if(next < pop.size() && (bufid=pvm_nrecv(-1, MSG_READY)) != 0) {
if(bufid > 0) {
status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
status = SendGenomeInitialize(pop.individual(next), tid);
if(status >= 0) {
if((who = id2idx(tid, *data)) >= 0) {
index[who] = next; next++;
outstanding++;
}
else {
cerr << "PopInit: bogus tid mapping: " << tid << "\n";
}
}
else {
cerr << "PopInit: error sending initialize command to: " << tid;
cerr << " genome " << next << " will be inited by next slave\n";
cerr << " error code is: " << status << "\n";
}
}
else {
cerr << "PopInit: error from pvm_nrecv: " << bufid << "\n";
}
}
// If we have requests for initialization outstanding and a slave has posted
// a message stating that it will provide genome data, then get the data from
// the slave and stuff it into the appropriate genome in the population.
if(outstanding > 0 && (bufid=pvm_nrecv(-1, MSG_GENOME_DATA)) != 0) {
if(bufid > 0) {
status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
if((who = id2idx(tid, *data)) >= 0) {
if(index[who] >= 0) {
status = RecvGenomeData(pop.individual(index[who]));
if(status >= 0) {
index[who] = -1;
outstanding--;
}
else {
cerr << "PopInit: error receiving data from: " << tid;
cerr << " error code is: " << status << "\n";
}
}
else {
cerr << "PopInit: index conflict from tid " << tid << "\n";
}
}
else {
cerr << "PopInit: bogus tid mapping: " << tid << "\n";
}
}
else {
cerr << "PopInit: error from pvm_nrecv: " << bufid << "\n";
}
}
if(next == pop.size() && outstanding == 0) done = 1;
if(next > pop.size()) {
cerr << "bogus value for next: " << next;
cerr << " popsize is: " << pop.size() << "\n";
}
}
delete [] index;
}
示例14: memset
// Reset the GA's statistics based on the population. To do this right you
// should initialize the population before you pass it to this routine. If you
// don't, the stats will be based on a non-initialized population.
void
GAStatistics::reset(const GAPopulation & pop){
curgen = 0;
numsel = numcro = nummut = numrep = numeval = numpeval = 0;
memset(gen, 0, Nscrs*sizeof(int));
memset(aveScore, 0, Nscrs*sizeof(float));
memset(maxScore, 0, Nscrs*sizeof(float));
memset(minScore, 0, Nscrs*sizeof(float));
memset(devScore, 0, Nscrs*sizeof(float));
memset(divScore, 0, Nscrs*sizeof(float));
nscrs = 0;
setScore(pop);
if(Nscrs > 0) flushScores();
memset(cscore, 0, Nconv*sizeof(float));
nconv = 0; // should set to -1 then call setConv
cscore[0] =
((pop.order() == GAPopulation::HIGH_IS_BEST) ? pop.max() : pop.min());
// cscore[0] = pop.max();
// setConvergence(maxScore[0]);
updateBestIndividual(pop, gaTrue);
aveCur = aveInit = pop.ave();
maxCur = maxInit = maxever = pop.max();
minCur = minInit = minever = pop.min();
devCur = devInit = pop.dev();
divCur = divInit = ((dodiv == gaTrue) ? pop.div() : (float)-1.0);
on = pop.ave();
offmax = pop.max();
offmin = pop.min();
numpeval = pop.nevals();
for(int i=0; i<pop.size(); i++)
numeval += pop.individual(i).nevals();
}
示例15: setConvergence
// Use this method to update the statistics to account for the current
// population. This routine increments the generation counter and assumes that
// the population that gets passed is the current population.
// If we are supposed to flush the scores, then we dump them to the specified
// file. If no flushing frequency has been specified then we don't record.
void
GAStatistics::update(const GAPopulation & pop){
++curgen; // must do this first so no divide-by-zero
if(scoreFreq > 0 && (curgen % scoreFreq == 0)) setScore(pop);
if(Nscrs > 0 && nscrs >= Nscrs) flushScores();
maxever = (pop.max() > maxever) ? pop.max() : maxever;
minever = (pop.min() < minever) ? pop.min() : minever;
float tmpval;
tmpval = (on*(curgen-1) + pop.ave()) / curgen;
on = tmpval;
tmpval = (offmax*(curgen-1) + pop.max()) / curgen;
offmax = tmpval;
tmpval = (offmin*(curgen-1) + pop.min()) / curgen;
offmin = tmpval;
setConvergence((pop.order() == GAPopulation::HIGH_IS_BEST) ?
pop.max() : pop.min());
updateBestIndividual(pop);
numpeval = pop.nevals();
}