00001 #ifndef _GAOPTIMIZER_H_ 00002 #define _GAOPTIMIZER_H_ 00003 00004 #include <vector> 00005 #include <functional> 00006 00007 namespace GAOptimizer 00008 { 00009 00010 class IGenotype 00011 { 00012 public: 00013 virtual void derive ( IGenotype * parent1, IGenotype * parent2 ) = 0; 00014 00015 virtual void random () = 0; 00016 00017 double m_fitness; 00018 }; 00019 00020 typedef std::vector<IGenotype*> GenotypeVec; 00021 00022 class IProblem 00023 { 00024 public: 00025 virtual IGenotype * createRandomSolution( int i ) = 0; 00026 00027 virtual double evaluteSolution( IGenotype * solution ) = 0; 00028 }; 00029 00030 class TestProblem: public IProblem 00031 { 00032 public: 00033 virtual IGenotype * createRandomSolution(); 00034 00035 virtual double evaluteSolution( IGenotype * solution ); 00036 }; 00037 00038 class TestGenoType: public IGenotype 00039 { 00040 public: 00041 TestGenoType(); 00042 00043 virtual void derive ( IGenotype * parent1, IGenotype * parent2 ); 00044 00045 virtual void random (); 00046 00047 double m_x; 00048 }; 00049 00050 00051 class Optimizer 00052 { 00053 public: 00054 Optimizer (); 00055 00056 virtual ~Optimizer (); 00057 00058 void init ( IProblem * problem, int populationSize, int subPopulationSize ); 00059 00060 void step (); 00061 00062 void step ( int n ); 00063 00064 IGenotype * getBest (); 00065 00066 GenotypeVec& getPopulation (); 00067 00068 double getMaxFitness (); 00069 00070 private: 00071 void clear(); 00072 00073 private: 00074 IProblem * m_problem; 00075 int m_populationSize; 00076 int m_subPopulationSize; 00077 GenotypeVec m_population; 00078 GenotypeVec m_subPopulation; 00079 IGenotype * m_bestSolution; 00080 double m_maxFitness; 00081 int m_bestIndNum; 00082 int m_firstBadInd; 00083 }; 00084 00085 } 00086 00087 #endif // _GAOPTIMIZER_H_