evoga.h
1 /********************************************************************************
2  * FARSA Experiments Library *
3  * Copyright (C) 2007-2012 *
4  * Stefano Nolfi <stefano.nolfi@istc.cnr.it> *
5  * Onofrio Gigliotta <onofrio.gigliotta@istc.cnr.it> *
6  * Gianluca Massera <emmegian@yahoo.it> *
7  * Tomassino Ferrauto <tomassino.ferrauto@istc.cnr.it> *
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  * This program is distributed in the hope that it will be useful, *
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17  * GNU General Public License for more details. *
18  * *
19  * You should have received a copy of the GNU General Public License *
20  * along with this program; if not, write to the Free Software *
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
22  ********************************************************************************/
23 
24 #ifndef EVOGA_H
25 #define EVOGA_H
26 #include <cstdlib>
27 #include <stdio.h>
28 #include <string.h>
29 #include "evorobotexperiment.h"
30 
31 #include <configurationparameters.h>
32 #include <parametersettable.h>
33 
34 #include <QObject>
35 #include <QString>
36 #include <QMutex>
37 #include <QWaitCondition>
38 
39 #include <Eigen/Core>
40 
41 namespace farsa {
42 
50 class FARSA_EXPERIMENTS_API Evoga : public QObject, public ParameterSettableWithConfigureFunction, public ConcurrentResourcesUser
51 {
52  Q_OBJECT
53 signals:
57  void startingReplication( int replication );
61  void recoveredInterruptedEvolution( QString statfile );
68  void endGeneration( int generation, double fmax, double faverage, double fmin );
70  void finished();
71 public:
73  static const int MAXINDIVIDUALS = 1000;
75  Evoga();
77  ~Evoga();
78 
86  void xnes();
87 
88  void saveStatistics(int popSize, int rp);
89 
104  void evolveSteadyState();
112  void evolveGenerational();
115  void evolveSpecializerSteadyState();
118  void evolveSpecializerSteadyState2();
119 
120  QString getEvolutionType();
121  float* xnesGetGenesForIndividual(unsigned int id);
122  float* xnesGetGenes(int ind);
123  void xnesComputeStats();
124  void xnesSaveStats();
125  void xnesSaveGen(FILE *fp, float* genotype);
126  void xnesSaveAllGen();
127  void xnesSaveBest(int bi);
128  void xnesSaveBestPhe(int gen, int bi);
129  void xnesLoadGen(FILE *fp, int ind);
130  int xnesLoadAllGen(int gen, const char *filew);
131 
132  void saveBestFitness();
133 
138  int rouletteWheel(QVector<double> candidates);
139 
144  int mrand(int i);
149  double drand();
152  double getNoise(double minn, double maxn);
156  void reproduce();
162  void mreproduce();
168  void putGenome(int fromgenome, int tobestgenome);
176  void getGenome(int frombestgenome, int togenome, int mut);
181  void setSeed(int s);
189  int mutate(int w, double mut);
193  void randomizePop();
201  void setInitialPopulation(int*);
206  void setMutations(float*);
209  void printPop();
212  void printBest();
218  void saveagenotype(FILE *fp, int ind);
224  void loadgenotype(FILE *fp, int ind);
228  void saveallg();
229 
233  void saveallgComposed(QVector< QVector<int> > composedGen);
234 
240  int loadallg(int gen, const char *filew);
241 
242 
248  void loadallTeams(int gen, const char *filew, QVector< QVector<int> > &teams);
252  void computeFStat();
256  void computeFStat2();
260  void saveFStat();
264  void saveRStat(QVector<int> subsVec);
270  void getLastFStat( double &min, double &max, double &average );
276  int loadStatistics(char *filename);
281  int* getGenes(int ind);
286  int* getBestGenes(int ind);
289  void resetGenerationCounter();
300  void copyGenes(int from, int to, int mut);
303  void saveBestInd();
304 
309  void saveBestTeam(QVector< QVector<int> > teams, QVector<double> fitness);
310 
311 
317  void getPheParametersAndMutationsFromEvonet();
318 
322  void updateGenomeFromEvonet( int ind );
323 
334  virtual void configure(ConfigurationParameters& params, QString prefix);
335 
346  virtual void save(ConfigurationParameters& params, QString prefix);
347 
355  static void describe( QString type );
356 
361  virtual void postConfigureInitialization();
362 
366  virtual void evolveAllReplicas();
367 
373  void stop();
374 
400  bool commitStep();
401 
420  bool isStopped();
421 
424  void resetStop();
425 
428  bool isEnabledStepByStep();
429 
440  virtual EvoRobotExperiment* getEvoRobotExperiment();
441 
450  virtual QVector<EvoRobotExperiment*> getEvoRobotExperimentPool();
451 
457  virtual unsigned int getCurrentGeneration();
458 
464  virtual unsigned int getStartingSeed();
465 
471  virtual unsigned int getCurrentSeed();
472 
478  virtual unsigned int getNumReplications();
479 
485  virtual unsigned int getNumOfGenerations();
486 
492  virtual double getCurrentMutationRate();
493 
498  virtual void setCurrentMutationRate( double mutation_rate );
499 
507  virtual unsigned int loadGenotypes(QString filename);
508 
514  virtual unsigned int numLoadedGenotypes() const;
515 
522  virtual int* getGenesForIndividual(unsigned int id);
523 
532  virtual QString statisticsFilename(unsigned int seed);
533 
542  virtual QString bestsFilename(unsigned int seed);
543 
547  virtual QString bestsFilename();
548 
558  virtual QString generationFilename(unsigned int generation, unsigned int seed);
559 
563  virtual QString generationFilename();
564 
569  virtual void doNotUseMultipleThreads();
570 
579  virtual QString retentionsFilename(unsigned int seed);
580 
583 
584 public slots:
591  void enableStepByStep( bool enable );
594  void doNextStep();
595 
596 protected:
600  int popSize;
602  int glen;
604  bool elitism;
609 
614  class Population {
615  public:
616  Population() :
617  m_pop(),
618  m_genomelength(1)
619  {
620  }
621 
622  ~Population()
623  {
624  clear();
625  }
626 
627  void setGenomeLength(int genomelength)
628  {
629  if (genomelength < 1) {
630  genomelength = 1;
631  }
632  m_genomelength = genomelength;
633 
634  clear();
635  }
636 
637  int getGenomeLength() const
638  {
639  return m_genomelength;
640  }
641 
642  void resize(int newSize)
643  {
644  if (newSize < 0) {
645  newSize = 0;
646  }
647 
648  // We have to be careful clearing or allocating memory
649  if (newSize < m_pop.size()) {
650  for (int i = (m_pop.size() - 1); i >= newSize; i--) {
651  delete[] m_pop[i];
652  }
653  m_pop.resize(newSize);
654  } else if (newSize > m_pop.size()) {
655  const int oldSize = m_pop.size();
656  m_pop.resize(newSize);
657  for (int i = oldSize; i < newSize; i++) {
658  m_pop[i] = new int[m_genomelength];
659  }
660  }
661  }
662 
663  int addOne()
664  {
665  m_pop.append(new int[m_genomelength]);
666 
667  // Returning the index of the new genome
668  return (m_pop.size() - 1);
669  }
670 
671  void clear()
672  {
673  resize(0);
674  }
675 
676  int size() const
677  {
678  return m_pop.size();
679  }
680 
681  int* operator[](int i)
682  {
683 #ifdef FARSA_DEBUG
684  if (i > m_pop.size()) {
685  abort();
686  }
687 #endif
688  return m_pop[i];
689  }
690 
691  const int* operator[](int i) const
692  {
693 #ifdef FARSA_DEBUG
694  if (i > m_pop.size()) {
695  abort();
696  }
697 #endif
698  return m_pop[i];
699  }
700 
701  private:
702  QVector<int *> m_pop;
703  int m_genomelength;
704  };
709  // Matrix containing genotypes for XNES algorithm
710  QVector<float *> genotypes;
714  double *tfitness;
716  double *ntfitness;
718  double **statfit;
720  double *terror;
725  QString evolutionType;
731  int seed;
735  double mutation;
743  float *mutations;
745  int cgen;
747  int savebest;
749  double fmin, fmax,faverage;
751  double fbest;
753  int fbestgen;
755  int ccycle;
763  QWaitCondition waitForNextStep;
765  unsigned int numThreads;
783 
791  double gaussianMean;
813  int pheGen;
826 
829 
832 
834  double crossRate;
835 
838 
841 
844 
846  QString selectionType;
847 
850 
855 
863 
870 };
871 
872 } // end namespace farsa
873 
874 #endif
bool useGaussian
Flag to decide whether using gaussian distribution to generate offspring.
Definition: evoga.h:789
bool minimization
Flags whether the fitness function is set to solve a minimization problem.
Definition: evoga.h:817
QString savedExperimentPrefix
A copy of the prefix for experiment parameters.
Definition: evoga.h:869
QString evolutionType
specify the type of the evolution process to execute This string can only assume two values at the mo...
Definition: evoga.h:725
double * tfitness
A pointer to a vector used to store the sum of the fitness obtained during different evaluations of a...
Definition: evoga.h:714
EvoRobotExperiment * exp
the EvoRobotExperiment
Definition: evoga.h:598
bool dissociateCovMatrix
Flags whether to dissociate back-propagation effect on the xNES covariance matrix update...
Definition: evoga.h:823
double mutation
The mutation rate can vary from 0 to 1 continuosly to express probability in the range [0...
Definition: evoga.h:735
bool mutateOnlyRelatives
Wheater a module should be replace by its own offspring or by any offspring – specializerSteadyState...
Definition: evoga.h:840
double modulesMutationRate
The probability that a module will be mutated on a team – specializerSteadyState.
Definition: evoga.h:837
double ** statfit
A matrix that store the statistics (average, min, and max fitness) for all generations.
Definition: evoga.h:718
bool limitRetention
Wheather the retention should be limited or not.
Definition: evoga.h:831
int nogenerations
The number of generations specified with the ngenerations parameter.
Definition: evoga.h:727
int fbestgen
fitness best generation (maximum)
Definition: evoga.h:753
int glen
genome lenght (number of free parameters)
Definition: evoga.h:602
int savePopulationEachNGenerations
How often (i.e. how many generations) we want to same the population genome in a .gen file.
Definition: evoga.h:767
int numStartInd
Number of possible individuals from which finding out the starting individual of XNES.
Definition: evoga.h:799
double fmin
fitness statistics (minimum, maximum, and average fitness)
Definition: evoga.h:749
int numModules
The number of modules that a genotype should use.
Definition: evoga.h:582
bool elitism
if the Evoga will use elitism or not
Definition: evoga.h:604
FARSA_UTIL_TEMPLATE const T max(const T &t1, const U &t2)
QString selectionType
The type of selection that will be used to define which individuals will survive. ...
Definition: evoga.h:846
int nreproducing
number of individuals allowed to reproduce
Definition: evoga.h:606
int pheGen
How often (in terms of number of generations) the best phenotype must be saved.
Definition: evoga.h:813
bool stopEvolution
Flag used to request to end the evolutionary process.
Definition: evoga.h:757
unsigned int numThreads
The number of concurrent threads to use.
Definition: evoga.h:765
double mutationdecay
The amount of reduction of the mutation generations during the first generations until it reaches the...
Definition: evoga.h:739
ConfigurationParameters savedConfigurationParameters
A copy of the ConfigurationParameters object that was passed to our configure method.
Definition: evoga.h:862
double offspringMutRange
The mutation range used in XNES algorithm to generate the offspring.
Definition: evoga.h:787
int backPropOffspringUtilityRank
The utility rank of the backpropagation offspring in the second type of combination with xNES...
Definition: evoga.h:807
double initial_mutation
The initial mutation rate setted when steadyState algorithm is used.
Definition: evoga.h:741
bool saveRetStat
Whether to save retentions statistics or not.
Definition: evoga.h:828
double mutationRange
The mutation range used in XNES algorithm to initialize the individual.
Definition: evoga.h:785
double offspringStdDev
Standard deviation to generate offspring.
Definition: evoga.h:795
double crossRate
The probability that a crossover will occur in an offspring team – specializerSteadyState.
Definition: evoga.h:834
int noffspring
number of sons
Definition: evoga.h:608
double mutationLearningRate
The mutation learning rate used to generate offspring from backprop array.
Definition: evoga.h:801
bool xnesCombination
Flag to decide whether combining xnes with backpropagation algorithm.
Definition: evoga.h:803
int ccycle
The current cycle.
Definition: evoga.h:755
Genetic algorithm from evorobot more or less (spare parts)
Definition: evoga.h:50
int seed
The number used to initialized the seed of the first replication (successive replication use incremen...
Definition: evoga.h:731
float * mutations
vector of parameter-specific mutations
Definition: evoga.h:743
int savebest
save best savebest parents by default equals 1
Definition: evoga.h:747
double gaussianStdDev
Standard deviation of the gaussian distribution.
Definition: evoga.h:793
double targetRetentionRate
The target retention rate.
Definition: evoga.h:852
QWaitCondition waitForNextStep
the wait condition for waiting on step-by-step modality
Definition: evoga.h:763
bool specialUtilityRanking
Flags whether to use a special version to compute utility ranking.
Definition: evoga.h:825
int nreplications
The number of replications specified with the corresponding parameter.
Definition: evoga.h:729
double * ntfitness
A pointer to a vector used to store the total number of trials in which an unchanged individuals have...
Definition: evoga.h:716
double rankBasedProb
The probability that the individuals with the highest fitness will be selected.
Definition: evoga.h:843
int currentSeed
The seed of the current generation (used for example to generate the name of the G?S?.gen files)
Definition: evoga.h:733
double fbest
fitness best
Definition: evoga.h:751
bool dissociateInd
Flags whether to dissociate back-propagation effect on the xNES individual update.
Definition: evoga.h:821
float backPropOffspringFitnessIncreasePercentage
Percentage of increase of the fitness of the backpropagation offspring.
Definition: evoga.h:811
QMutex mutexStepByStep
the mutex used for controlling the step-by-step modality
Definition: evoga.h:761
double limitationFactor
The limitation factor that will multiply the offsprings' fitness.
Definition: evoga.h:854
double * terror
A pointer to a vector used to store the sum of the errors obtained during different evaluations of an...
Definition: evoga.h:720
double gaussianMean
Mean of the gaussian distribution.
Definition: evoga.h:791
Population bestgenome
The matrix that contains a copy of the genome of the best individuals.
Definition: evoga.h:708
bool standardNes
Flags whether the standard xNES algorithm must be used (i.e. the parameters are set according to the ...
Definition: evoga.h:815
int cgen
current generation
Definition: evoga.h:745
FARSA_UTIL_TEMPLATE const T min(const T &t1, const U &t2)
Population genome
The matrix that contain the genome of the corrent population.
Definition: evoga.h:706
A class modelling a population of genomes.
Definition: evoga.h:614
bool averageIndividualFitnessOverGenerations
Whether to average an individual fitness with its previous one or not.
Definition: evoga.h:782
double overwriteRate
The probability that a module will be overwritten by another one – specializerSteadyState.
Definition: evoga.h:849
int popSize
population size
Definition: evoga.h:600
int loadedIndividuals
The number of individual genome loaded from a .gen file into the genome matrix (-1 when none has been...
Definition: evoga.h:712
bool debugPrintInfoToFile
Flags whether to print debug information about the xNES algorithm to file.
Definition: evoga.h:819
The base common class that evaluate the fitness of a robot.
bool variableStdDev
Flags whether the standard deviation to generate offspring is constant or not.
Definition: evoga.h:797
bool backPropOffspringFitnessIncrease
Flag whether to increase the fitness of the backpropagation offspring.
Definition: evoga.h:809
bool isStepByStep
if step-by-step modality is enabled or not
Definition: evoga.h:759
int xnesCombinationType
The type of combination between xnes and backpropagation algorithms.
Definition: evoga.h:805