📄 chrome.h
字号:
pZipCmd, // command to run compress on dumpfile outputPARAM_STR_COUNT }; // total number of string parameters#define pname_size 20#define pTraceStatic 1#define pTraceDynamic 2#define pTraceDStats 4#define pTracePareto 8#define pTracePStats 16#define pTraceTest 32#define pTraceDupStats 64class ChromeParams { // parameter set for initializing a chromepublic: enum {param_str_size = 512}; int params[PARAM_COUNT]; //Initialised in constructor char params_str[PARAM_STR_COUNT][param_str_size]; // ditto char pnames[PARAM_COUNT+PARAM_STR_COUNT][pname_size]; // ditto int varcount; int funccount; ChromeParams(); virtual ~ChromeParams(); virtual void Edit() {}; // Put your own edit code here void Save( ostream& out = cout); void Load( istream& in); void Load( char * s);};// Carrier for fitness values.// Feel free to subclass this if you want to track your fitness cases more closely (by adding data)// or minimize instead of maximize (by redefining IsBetter)// or combine multiple scoresclass FitnessValue {public: float fvalue; // Always provide this for reporting reasons virtual BOOL IsBetter(FitnessValue* fv) {return fvalue>fv->fvalue;}; virtual BOOL IsBetter(float fv) {return fvalue>fv;}; virtual void update_rank() {;}; virtual void Copy(FitnessValue* fv) {memcpy(this,fv,sizeof(FitnessValue));}; virtual ~FitnessValue() {;}; operator float() {return fvalue;}; operator >(FitnessValue& fv) {return IsBetter(&fv);}; operator <(FitnessValue& fv) {return fv.IsBetter(this);}; virtual void write(ostream& ofile = cout) { ofile<<fvalue; }; virtual BOOL unique_best() const {cout<<"FitnessValue::unique_best\n";return TRUE;}#ifdef GEN_MEM virtual void Save( ostream& out = cout); virtual int Load( istream& in); //LOAD_OK or otherwise#endif};#define EXPRLEN 512 // maximum length of expressionenum {LOAD_OK,LOAD_BADFILE,LOAD_BADFUNC,LOAD_TOOFEW,LOAD_TOOMANY,LOAD_BADCONST,LOAD_TOOLONG,BAD_TREE_NAME,BAD_TREE_FORMAT}; // subload error valuesenum {PRETTY_NONE,PRETTY_PARENS,PRETTY_NOPARENS}; // source listing options// The Chrome is the carrier for a program expression// It includes the eval, initialization, reading, mutation, crossover, reading and writingclass Chrome { // GP program structurepublic: short int ip; // Current instruction pointer#ifdef MULTREE unsigned short int tree_starts [NUM_TREES]; // start of each tree #endif node *expr; // actual code //float lastfitness; // fitness on last eval INT32 birth; // gencount when generated Problem* probl;// CSelector* funcbag; // select functions by weight FitnessValue* nfitness; // pointer to an allocated object holding the type of fitness Function** funclist; // array of pointers to functions and operations ChromeParams* params; retval* constlist; // array of constants#ifdef TRACE short int num_children;// = 0; struct parent { INT32 birth;// = -1; short int xpoint;// = -1;#ifdef MULTREE short int xtree;// = -1;#endif parent(): birth(-1), xpoint(-1)#ifdef MULTREE ,xtree(-1)#endif {}; }; parent mum; parent dad;#endif Chrome(ChromeParams* p,Problem* pr,Function** f,retval* c,BOOL doinit=TRUE, istream* fil = NULL ); // returns a randomly initialized condition void reinit_trees(BOOL which_trees[NUM_TREES]); virtual Chrome* Copy(); // copy yourself. Extend for subclasses, and call base. virtual void Dup(Chrome* source); // make a copy without re-initializing. Extend for subclass, and call base virtual ~Chrome();#ifdef MULTREE void SubInit(CSelector* funcbag, int argstogo, int maxlen, int full, BOOL start, int tree);#else void SubInit(CSelector* funcbag, int argstogo,int maxlen,int full=FALSE, BOOL start=FALSE); // Initialize a subtree half full#endif BOOL IsBetter(Chrome* chrome) {return nfitness->IsBetter(chrome->nfitness);};#ifndef FASTEVAL retval eval() {ip++;return funclist[FUNCNUM(expr[ip])]->eval(this);} ;#endif#ifdef MULTREE retval evalAll(int) ; // eval the whole expression anew#else retval evalAll() ; // eval the whole expression anew#endif void SetupEval(const int tree = -1);// expand expression for multiple evals void Traverse(); // Skips over next subtree void TraverseGlobal(); int Depth(int start, int end); int DepthMax(int start, int end);#ifdef MULTREE int ChooseCrossTree(Chrome* mate); Chrome* CrossTree(Chrome* mate, int tree); int GetIntNode(int tree); // get an internal node for crossover int GetAnyNode(int tree); // get any node for crossover#else Chrome* CrossTree(Chrome* mate); int GetIntNode(); // get an internal node for crossover int GetAnyNode(); // get any node for crossover#endif void Mutate(); // mutate nodes with rate r void MutateC(); void MutateShrink(); void MutateSubTree(); int SubLen(int startat=0) {ip=startat;Traverse();return ip-startat;}; // return length of expression at startat#ifdef MULTREE void write(int pretty,ostream& ofile = cout, int last_tree=NUM_TREES-1)#else void write(int pretty,ostream& ofile = cout) {ip=-1;SubWrite(ofile,pretty,0);};} // write the expression#endif ;#ifdef TRACE void write_trace(ostream& ofile = cout);#endif void SubWrite(ostream& ostr,int pretty = 0, int depth = 0);#ifdef MULTREE int SubLoad(istream& istr,node* buf, int tree);// load an expression. int FindFunc(char* funcname, int tree); // find index of a function#else int SubLoad(istream& istr,node* buf); // load an expression. Return 0 on success or error val int FindFunc(char* funcname); // find index of a function, or -1 if not found#endif virtual int Load(istream& istr,int issource); // load from a stream. Return success BOOL same(Chrome* other) const; //Is code for two chromes the same int hashcode() const; //hash code};const int pcount_size = 4;//fix laterclass Problem { // Sets up a particular GP problem. GA independent. // contains function set, variables, and fitness functionprotected: retval* constlist; // array of constants retval* varlist; // array of variablespublic: Function** funclist; // primitive functionspublic: int funccount; CSelector* funcbag[NUM_TREES]; // select functions by weight Problem(); // allocate the arrays virtual ~Problem(); void AddF(Function* f) // add a function to the problem {funclist[funccount++]=f;}; Function** getfuncs() {return funclist;}; retval* getconsts() {return constlist;};// CSelector* getfuncbag() ; void addtofuncbag(int tree, Function* f); // User hooks virtual FitnessValue* GetFitnessObj(Chrome* c=NULL); // Can change behavior of FitnessValue virtual float fitness(Chrome* chrome); // The active ingredient. You add this. virtual void WriteTreeName(int tree, ostream& ostr = cout ) // The active ingredient. You add this. {ostr<<" T"<<tree<<" =";}; //default You overwrite this virtual BOOL TreeNameMatch(int tree, char* s ) // The active ingredient. You add this. {return (s[0]=='T');}; //default You overwrite this virtual Chrome* NewChrome(ChromeParams* p, istream* fil = NULL){cout<<"Problem::NewChrome\n"; return new Chrome(p,this,getfuncs(),getconsts(), TRUE, fil); };// Can change behavior virtual Chrome* Bestof(const PtrChrome list[], const int listsize, int* bestinlist = NULL, const int target = 0 ); virtual Chrome* Worstof(const PtrChrome list[], const int listsize, const int timenow, int* worstinlist, const int target = 0 ); virtual int static_check(Chrome* chrome, int tree) {return 0;};#ifdef MAXTREEDEPTH virtual void ProbLPStats(int opcode_counts[][NUM_TREES][MAXTREEDEPTH+1], int array[pcount_size] ){;};#else virtual void ProbLPStats(int opcode_counts[][NUM_TREES], int array[pcount_size] ){;};#endif virtual int ProbLTStat(int tree, int start, int length, node* code){ return 0;};};class Pop { // a population for a particular GA. Problem independent // controls the GA - selection, crossover, etc void select_candidates (int target, int tourn_size, Chrome* candidates[], int slots[], BOOL best );#ifdef MAXTREEDEPTH void GatherPStats( int opcode_counts[][NUM_TREES][MAXTREEDEPTH+1], int pcount[pcount_size], int tcount[NUM_TREES] ) const;#else void GatherPStats( int opcode_counts[][NUM_TREES], int pcount[pcount_size], int tcount[NUM_TREES] ) const;#endifpublic:#ifdef MULTREE int num_crosses[NUM_TREES]; int num_crosses_cleared_at;// = -1;#endifpublic: Chrome** pop; // allocated array holding the actual chromes#ifdef GENERATIONAL Chrome** newpop; // array holding pointers to new chromes#endif ChromeParams* params; Problem* problem; UINT popsize; // size of array INT32 gencount; // number of individuals generated time_t start; // starting time time_t elapsed; // elapsed time for last go_until BOOL isAborted;#ifndef PARETO FitnessValue* BestFitness; // Best current fitness value int BestMember; // Index of best current member#endif int initeval; // Flag: Still evaluating initial population? UINT nexteval; // Next initial pop member to evaluate Pop(Problem* prob,ChromeParams* par, UINT size,istream* = NULL ); // set up a population for a particular problem Pop(Problem* prob,ChromeParams* par); // stub for derived classes virtual ~Pop();#ifndef PARETO Chrome* best(); // return the current best chrome#endif virtual Chrome* selectParent(int target); // select one parent. Return pointer to selected parent // target identifies selection region in pop#ifdef MULTREE virtual Chrome* generate(int tree); // generate a new chrome. Return fitness#else virtual Chrome* generate(); // generate a new chrome. Return fitness #endif // Alternate steady state GA code can go here // generate until reaching time max_time, evaluating maxevals individuals, or reaching maxfitness#ifdef MULTREE virtual Chrome* go_until(time_t max_time, int maxevals, float maxfitness, int tree = -1); void reinitialise(int change_trees[NUM_TREES]);#else virtual Chrome* go_until(time_t max_time, int maxevals, float maxfitness);#endif int GetTarget(); // get a target member to replace with anti-tournament int GetAnnealTarget(); // get a target for annealing, with selection tournament virtual BOOL Aborted(){return isAborted;}; virtual float Fitness(Chrome* chrome); // Evaluate a member using the current problem void InsertMember(int slot,Chrome* NewChrome,int nodelete = FALSE); //insert a chrome and update BestMember values void DisplayStats( ostream& out = cout) const; void DisplayDStats( ostream& out = cout) const; void DisplayPStats( ostream& out = cout) const; void DisplayLPStats( ostream& out = cout) const; void DisplayDupStats( ostream& out = cout) const; void ClearCStats() {memset(num_crosses,0,sizeof(num_crosses)); num_crosses_cleared_at = gencount;}; void DisplayCStats( ostream& out = cout) const; void Write( ostream& out = cout, BOOL binary = FALSE );};#endif // #ifndef _CHROME_H//////////////////////////////////////////////////////////////may not be needed eg Borlandint strcmpi(char* s1, char* s2); // only checks equalityvoid clear_rank();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -