⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gplib.h

📁 遗传规划算法 智能算法:遗传规划
💻 H
字号:
// Header file for GPLib
// Include this file in your application and you'll be able to use GPLib from your own code

// GPLib v2.0, A Genetic programming Library for C++
// Copyright (C) 2006  Colin Frayn
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#ifndef GPLIB_H
#define GPLIB_H

#include <stdlib.h>#include <stdio.h>#include <time.h>#include <ctype.h>#include <math.h>#include <float.h>#include <string>#include <vector>// This version#define GPLIB_VER (2.0)using namespace std;// Miscellaneous internal utility defines#ifndef Random# define Random(a) ((a) == (0) ? (0) : (int)((double)rand() / ((double)RAND_MAX + 1) * (a)))#endif#ifndef FRandom# define FRandom(a) ((a) == (0) ? (0.0f) : (float)((float)rand() / ((float)RAND_MAX + 1.0f) * (float)(a)))#endif#ifndef Randomise# define Randomise()  (srand((unsigned)time(NULL)))#endif
// A few helpful functions
float GPLIB_CauchyRandom(float);float GPLIB_RoundFloat(float);bool  GPLIB_NotANumber(float);// Some variable typestypedef vector<float> FloatVector;typedef vector<int> IntVector;// Miscellaneous tree stuff#define GPLIB_GenomeStart ('A')   // Beginning of genome in ASCII translation#define GPLIB_FLeaf  (-100001)    // Floating point value leaf#define GPLIB_ILeaf  (-100002)    // Integer value leaf#define GPLIB_IsFunc(x)  (((x) < 0) ? 0 : 1)  // Is this a function node or a leaf node#ifndef INFINITY#ifdef HUGE_VALF#  define INFINITY HUGE_VALF # else#  define INFINITY  (1000000.0f)# endif#endif// Maximum buffer sizes#define GPLIB_MaxGenome      (1000)  // Buffer size for genomes#define GPLIB_MaxSubTree     (10)    // Maximum size of a randomly generated subtree#define GPLIB_IdealMaxLength (64)    // Ideal maximum genome length#define GPLIB_MaxParam       (4)     // Maximum number of parameters to a function#define GPLIB_MaxData        (1<<14) // Maximum number of entries in a datafile to fit// Common constants#define GPLIB_PI (3.14159265359f)#define GPLIB_E  (2.71828182846f)// Edit types// Return type > 0 = 'Replace the entire tree with the following single function'#define GPLIB_NOP      (-1)  // Do nothing#define GPLIB_SNIP     (-2)  // Snip this entire tree and replace it with zero#define GPLIB_SIMPLIFY (-3)  // Trivial numerical simplification#define GPLIB_FIRST    (-4)  // Replace this tree with its first argument #define GPLIB_SECOND   (-5)  // Replace this tree with its second argument#define GPLIB_THIRD    (-6)  // Replace this tree with its third argument#define GPLIB_FOURTH   (-7)  // Replace this tree with its fourth argument// Mutation types#define GPLIB_MUTATE_SUBSTITUTION (0)#define GPLIB_MUTATE_EDIT         (1)#define GPLIB_MUTATE_PERMUTE      (2)#define GPLIB_MUTATE_FLIP         (3)#define GPLIB_MUTATE_SWAP         (4)// Leaf node data#define GPLIB_LEAF_NODE_PROB  (25)   // % Chance of a leaf node at any point in tree creation#define GPLIB_LEAF_NODE_FUNC  (20)   // % Chance of using a function, if one exists, instead of a leaf#define GPLIB_LEAF_NODE_PARAM (50)   // % Chance of a leaf node being a parameter value#define GPLIB_LEAF_NODE_FLOAT (34)   // % Chance of a leaf node being a floating point value#define GPLIB_LEAF_NODE_INT   (16)   // % Chance of a leaf node being an integer-clamped value#define GPLIB_LEAF_NODE_MAX   (10)   // Maximum initial value for a leaf node#define GPLIB_LEAF_NODE_MIN   (0)    // Minimum initial value for a leaf node// A tree nodetypedef struct GPLIB_Node {  float value;  int func;}GPLIB_Node;// Define the parent class for an Entityclass GPLIB_EntityParent {  private :  float score;              // Current score  public :  vector<GPLIB_Node> genome; // This entity's genome as a Node list  void AddScore(int s) {score += (float)s;}  void SetScore(int s) {score = (float)s;}  void AddScore(float s) {score += s;}  void SetScore(float s) {score = s;}  float GetScore(void) {return score;}  void Mutate(void);  void StrongMutate(void) {    int n = Random(3) + 2;    for (int i=0;i<n;i++) Mutate();  }  void EditGenome(void);  void SwapSubtrees(int);  void CheckPermute(int);  void CopyFrom(class GPLIB_EntityParent *ent) {    score = ent->score;    genome.clear();    genome.reserve(ent->genome.size());    for (int n=0;n<(int)ent->genome.size();n++) genome.push_back(ent->genome[n]);  }    void GenerateOffspring(class GPLIB_EntityParent *, class GPLIB_EntityParent *);    float RunEntity(void);  void SnipSubTree(int);  void ReplaceWithSubTree(int,int);  void ValueMutation(int);  void GenerateRandomSubtree(void);  int GetBranchByPos(int, int);  int SplitGenome(int);  int NodeCount(void) {return (int)genome.size();}};// Function recordclass GPLIB_GPFunction {  private:  int NP;     // Number of parameters  int Weight; // Weighting of this function    public:  string Name;     // This function's name  GPLIB_GPFunction() { // Class constructor    NP = 0;    Weight = 1;    Name = "Unnamed";  }  virtual ~GPLIB_GPFunction() {}  void  SetWeight(int w) {Weight = w;}  int   GetWeight(void) {return Weight;}  void  SetNP(int n) {NP = n;}  int   GetNP(void) {return NP;}  void  SetName(string NewName) {Name = NewName;}  float Execute(GPLIB_EntityParent *ent, int pos);  float RunSubFunction(int pos, int PNo);  void  CalculateFitness(void);  virtual float FunctionBody(int pos) {return 0.0f;} // Placeholder function  virtual int   EditCheck(GPLIB_EntityParent *, int) {return GPLIB_NOP;} // Default function};// The entity class. If you want you can edit this and extend it to do more specialised stuff.class GPLIB_Entity : public GPLIB_EntityParent {  private:  // Add new private member items here  public:  void Initialise(void);  void CalculateFitness(void);  void MakeLean(void);  // Add new public member items here};

// The environment classclass GPLIB_Environment {  public:    int TuneLarge;     // Percent chance of a large finetuning step (as opposed to a small one)    float RoundError;  // Auto round a float which finds itself this close to an integer value    vector<GPLIB_GPFunction *> Functions;   // The available functions (global)    IntVector FuncByNParam[GPLIB_MaxParam]; // List of functions sorted by NParams    int MutateChance;  // Percent chance of a mutation of some sort during crossover    int SubstChance;   // Weighting for a substitution    int PermChance;    // Weighting for a permutation    int EditChance;    // Weighting for an edit mutation    int FlipChance;    // Weighting for a 'similar pair' flip    int SwapChance;    // Weighting for a node swap (with a similar function of same parameter count)    int ValueMutate;   // Percent chance of doing only a simple mutation on a real-value terminal    int TotalWeight;   // Total weight of functions    int LeafWeight;    // Total weight of leaf-node (NP=0) functions  private:    int EliteCount;    int TournamentSize;    int SurvivalFract;    int MutantFract;    int WarpedFract;    int RandomFract;    int TotalLength;            // Used for calculating average genome length    int LengthTally[GPLIB_MaxGenome]; // Keep a tally of how many of each length there are    int best,worst,longest;  // Record of best, worst and longest genomes    float totalscore;         // Total score summed from all entities    vector<FloatVector> xval; // X-values to be used (either pre-set or from loaded data)    FloatVector yval;      // Y-values to be used (either pre-calculated or from loaded data)    int LengthPenalty;    int Generation;    bool bVerbose;    bool bPrintProgress;    vector<class GPLIB_Entity> Entitylist;  // The global list of entities    int CurrentEntity;    // The ID number of the current entity    int CurrentDatum;     // The current datum    vector<string> strVariables;     // Variable names, loaded from file    string strTarget;  // Target value name, loaded from file  public:    GPLIB_Environment();    virtual ~GPLIB_Environment();    void Reset(void);    void LoadCSV(string);    void SetupPopulation(int);    void SetupRandomEntities(int);    void SetupEntitiesFromFile(string,int);    void RunGeneration(void);    void InitialiseGeneration(void);    void FitnessEvaluation(void);    void Breed(void);    void PostEvaluationStatistics(void);    void PostRunStatistics(void);    void PrintProgress(int);    void CheckGenome(vector<GPLIB_Node>, int);    int  GetIDByName(string);    void SetupFunctions(void);    void SetupFunctionArray(void);    int  TournamentSelect(void);    void SetVerbose(bool b) {bVerbose = b;}    void ShowProgress(bool b) {bPrintProgress = b;}    void WriteGenomeFile(int,string);    void WriteRecordFile(string);    void WriteTallyFile(string);    void WriteOutputFile(int,string);    void PrintGenome(vector<GPLIB_Node>, FILE *);    int  GetBranchByPos(GPLIB_EntityParent *, int, int);    void SetCurrentDatum(int n) {CurrentDatum = n;}    int  GetCurrentDatum(void) {return CurrentDatum;}    int  CountData(void) {return (int)yval.size();}    float GetYVal(int n) {return yval[n];}    float GetXVal(int v, int n) {return xval[n][v];}    int  CountVariables(void) {if (xval.empty()) return 0; else return (int)xval[0].size();}    void Catastrophe(int);    void Consolidate(int);    float GetFitness(int n) {return Entitylist[n].GetScore();}    int  GetBestEntity(void);};#endif // GPLIB_H

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -