📄 chrome.cxx
字号:
func=FindFunc(scratch,tree);#else func=FindFunc(scratch);#endif if (func<0) {#ifdef debugcout<<"LOAD_BADFUNC `"<<scratch<<"'"<<flush;#endif //debug rval=LOAD_BADFUNC; } else { SETNODE(buf[ip],func,vnum); ip++; rval=LOAD_OK; // get the arguments args=funclist[func]->argnum; while(args>0 && rval==LOAD_OK) {#ifdef MULTREE rval=SubLoad(istr,buf,tree);#else rval=SubLoad(istr,buf);#endif args--; }// if (rval == LOAD_TOOFEW)// ; // restore the token for the error message } } } } return rval;}//**************************************************************************#ifdef MULTREEint Chrome::FindFunc(char* funcname, int tree)// find a function index by name#elseint Chrome::FindFunc(char* funcname) // find a function index by name, or return -1#endif{ int rval=-1; int i; for (i=0;i<probl->funccount && rval<0;i++) if (strcmp(funcname,funclist[i]->name)==0)#ifdef MULTREE if (probl->funcbag[tree]->find(i) >= 0)#endif rval=i; return rval;}Chrome::~Chrome(){ delete[] expr; delete nfitness;}//**************************************************************************//// Generic Problem Functions /////////////////////////////////////Problem::Problem()// Set up the tables// You add the primitive functions in your subclass constructor{ int i; funclist = new Function*[FUNCARRAYSIZE]; for (i=0;i<NUM_TREES;i++) { funcbag[i] = new CSelector(EStraight,256); funcbag[i]->reset(); } varlist = new retval[CONSTARRAYSIZE]; constlist = new retval[CONSTARRAYSIZE]; funccount = 0; // set up constant table (not implemented) for (i=0;i<CONSTARRAYSIZE;i++) constlist[i]=i-(CONSTARRAYSIZE/2);}Problem::~Problem(){ int i; delete[] constlist; delete[] varlist; for (i=0;i<funccount;i++) delete funclist[i]; for (i=0;i<NUM_TREES;i++) delete funcbag[i]; delete[] funclist;}FitnessValue* Problem::GetFitnessObj(Chrome* chrome){ FitnessValue* fv = new FitnessValue; fv->fvalue=0; // fv has to be deleted by the Chrome Object return fv;}//CSelector* Problem::getfuncbag() // update the function selector and return its pointer//{// int i;// funcbag->reset();// for (i=0;i<funccount;i++)// funcbag->add(funclist[i]->weight/(2+funclist[i]->argnum),i);// return funcbag;//}void Problem::addtofuncbag(int tree, Function* f )//NB must be called in correct sequence, ie after AddF has funccount++{ funcbag[tree]->add(f->weight/(2+f->argnum),funccount-1);}float Problem::fitness(Chrome* chrome)// This is just a stub. You must add your own virtual fitness function{ cout <<"Problem::fitness (stub)\n";//debug float f=0; // clear variables if required // call the installed fitness function chrome->nfitness->fvalue = f; return f;}Chrome* Problem::Bestof(const PtrChrome list[], const int listsize, int* bestinlist, const int target ){ //WBL#ifdef PARETOassert (1==19); //should be using non-virtual function in problem class!#endif /*PARETO*/if ( bestinlist == NULL ) {int dummy; bestinlist = &dummy;}//discard*bestinlist = 0;Chrome * best = list[0];for (int i=1; i<listsize; i++){ if (list[i]->nfitness->IsBetter(best->nfitness)) { *bestinlist = i; best = list[i]; }}return best;}//end Problem::BestofChrome* Problem::Worstof(const PtrChrome list[], const int listsize, const int timenow, int* worstinlist, const int target ) //WBL{#ifdef PARETOassert (1==19); //should be using non-virtual function in problem class!#endif /*PARETO*/// Will select a target that is too old, even if more fit.*worstinlist = 0;for (int i=1; i<listsize; i++){ if (list[i]->params->params[pMaxAge] != 0 && (timenow - list[i]->birth) > list[i]->params->params[pMaxAge]) { *worstinlist = i; break; } if (list[*worstinlist]->nfitness->IsBetter(list[i]->nfitness)) { *worstinlist = i; }}return list[*worstinlist];////////////////////////////////////////////////////////////////////////// Nice Idea, but leads to even more dominance of population by best// WBL 17-Aug-94. Might be marginaly quicker?// if (target == BestMember) // target = winner; //avoid discarding best if can//// else //////////////////////////////////////////////////////////////////////}//end Problem::Worstof//**************************************************************************//// Pop Functions /////////////////////////////////////////////////Pop::Pop(Problem* prob,ChromeParams* par,UINT size, istream* fin)#ifdef MULTREE :num_crosses_cleared_at(-1)#endif// set up a population for a particular problem// Creates <size> new Chromes// evaluates the first Chrome. The rest will be evaluated in the first// Size-1 calls to generate{ UINT i; isAborted=FALSE; problem = prob; gencount = 0; start=time(NULL);#ifdef PARETO clear_rank();#else BestMember=0; BestFitness=NULL;#endif params=par; par->funccount = prob->funccount; if (par->params[pMaxExpr] > EXPRLEN) par->params[pMaxExpr]=EXPRLEN; if((par->params[pMaxDepth] !=0) && (par->params[pInitExpr] > par->params[pMaxDepth])) par->params[pInitExpr] = par->params[pMaxDepth]; popsize=size; pop = new Chrome*[size];#ifdef GENERATIONAL if(params->params[pGenerational]) newpop = new Chrome*[size];#endif int seeds_loaded = 0; if(params->params[pSeeds]==0) for (i=0;i<size;i++) pop[i]=prob->NewChrome(par,fin); else { do{int c=fin->get();if(c!='$'){cout<<char(c);};} while((fin->peek()!=EOF)&&(fin->peek()!='\n')); cout<<endl; for (i=0;i<size;i++) { //load all seeds in fin pop[i]=prob->NewChrome(par); int rval = pop[i]->Load(*fin, TRUE); if (rval != 0) { if(i==0) cout<<"Load error - "<<rval<<endl; else cout<<"Loaded "<<i<<" seeds"<<endl; break; } seeds_loaded = i+1; } for (;i<(size-params->params[pSeeds]);i++) pop[i]=prob->NewChrome(par); }//cout << "Created Pop, Now testing pop[0]\n"; // now eval 1 guy initeval=TRUE; nexteval=1; Fitness(pop[0]); InsertMember(0,pop[0],TRUE); for (;i<size;i++) { pop[i] = pop[i%seeds_loaded]->Copy(); if(rnd(100) < params->params[pMuteSeedWt]) { int prob,wheel; prob=rnd(params->params[pMuteNodeWt]+params->params[pMuteConstWt]+params->params[pMuteShrinkWt]+params->params[pMuteSubTreeWt]); wheel=params->params[pMuteNodeWt]; if (prob<wheel) pop[i]->Mutate(); else if (prob<(wheel += params->params[pMuteConstWt])) pop[i]->MutateC(); else if (prob<(wheel += params->params[pMuteShrinkWt])) pop[i]->MutateShrink(); else pop[i]->MutateSubTree(); } }}float Pop::Fitness(Chrome* chrome)// uses the problem to evalue the fitness of member X// performs setup on the Chrome// returns the fitness value{#ifdef TRACE if ( params->params[pTrace] & pTraceTest ) { cout << "\nTesting "; chrome->write(PRETTY_NONE, cout); cout << endl; }#endif //TRACE chrome->SetupEval();#ifdef TRACE retval rval = problem->fitness(chrome); if ( params->params[pTrace] & pTraceTest ) cout << " done\n"; return rval;#else return problem->fitness(chrome);#endif //TRACE}void Pop::InsertMember(int slot,Chrome* NewChrome,int nodelete)// uses the problem to evalue the fitness of member X// performs setup on the Chrome// updates the BestMember and returns the fitness value{#ifndef ORIGINAL_RANK NewChrome->nfitness->update_rank();#endif UINT endpop; NewChrome->birth=gencount;// if (!nodelete && pop[slot]->nfitness->IsBetter(NewChrome->nfitness) )// {// // Check NewChrome is not worse than existing//#ifdef TRACE// if ( params->params[pTrace] & pTraceDynamic )// { cout << endl;// cout << "Discarding new ";// NewChrome->write_trace(); // cout << "\nRather than " << slot; // pop[slot]->write_trace(); // cout << endl;// }//#endif// delete NewChrome;// }//end discard NewChrome (Nb parents credited with child anyway// else { Chrome* oldchrome = pop[slot]; if (!nodelete) {#ifdef GENERATIONAL if(params->params[pGenerational]) newpop[slot]=NewChrome; else#else // replace the chrome in this slot // remember to delete oldchrome later#endif pop[slot]=NewChrome; }// end discard old chrome in this slot#ifndef PARETO // Update Best Member if (BestFitness==NULL) { BestMember=slot; BestFitness=NewChrome->nfitness; } else if(NewChrome->nfitness->IsBetter(BestFitness)) {cout<<"Improved solution found "<<NewChrome->nfitness->fvalue <<" ("<<BestFitness->fvalue<<")" <<" in slot "<<slot<<" at "<<gencount<<endl; BestMember=slot; BestFitness=NewChrome->nfitness; } else if(slot==BestMember) { //if generational BestMember will always be less than slot endpop = (initeval? nexteval : popsize);//cout<<"Scanning whole pop"<<flush; problem->Bestof(pop,endpop,&BestMember);//cout<<" Updating BestFitness"<<endl; BestFitness=pop[BestMember]->nfitness; }#endif#ifdef TRACE if ( params->params[pTrace] & pTraceDynamic ) { cout << "\nInserting " << slot << " "; NewChrome->write_trace(cout); NewChrome->write(PRETTY_NONE, cout); cout << endl; }#endif //TRACE#ifdef GENERATIONAL if((!nodelete) && (!params->params[pGenerational]))#else if (!nodelete)#endif {#ifdef TRACE if ( params->params[pTrace] & pTraceDynamic ) { cout << endl; cout << "Deleting " << slot; oldchrome->write_trace(); }#endif delete oldchrome; }// end discard old chrome in this slot }//end if add NewChrome to pop}Pop::Pop(Problem* prob,ChromeParams* par)#ifdef MULTREE :num_crosses_cleared_at(-1)#endif// set up just the core of a population;; let a subclass allocate the members{ isAborted=FALSE; problem = prob; gencount = 0; params=par; popsize=0; pop=NULL;#ifndef PARETO BestMember=-1; BestFitness=prob->GetFitnessObj(); // allocates FitnessValue object on heap BestFitness->fvalue=1-MAXFLOAT;#endif}Pop::~Pop(){ int i; for (i=0;i<popsize;i++) delete pop[i]; delete[] pop;#ifdef GENERATIONAL delete[] newpop; //when called, population should be in pop only #endif}#ifndef GENERATIONAL#ifndef PARETOChrome* Pop::best()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -