evonet.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 EVONET_H
25 #define EVONET_H
26 
27 #include "experimentsconfig.h"
28 #include "parametersettable.h"
29 #include "simpletimer.h"
30 #include "dataexchange.h"
31 #include <stdio.h>
32 #include <math.h>
33 #include <string.h>
34 #include <iostream>
35 #include <stdlib.h>
36 #include <QString>
37 #include <QStringList>
38 #include <QColor>
39 #include <QDebug>
40 #include <QObject>
41 #include <QMutex>
42 
43 // All this stuff is to get rid of annoying warnings...
44 #ifdef __GNUC__
45  #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5)
46  #pragma GCC diagnostic push
47  #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
48  #else
49  #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
50  #endif
51 #endif
52 
53 #include "Eigen/Dense"
54 
55 #ifdef __GNUC__
56  #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5)
57  #pragma GCC diagnostic pop
58  #else
59  #pragma GCC diagnostic warning "-Wunused-local-typedefs"
60  #endif
61 #endif
62 
63 namespace farsa {
64 
65 class EvonetUI;
66 
74 {
84 
88  QVector<float> data;
89 
94 
100  QVector<QString> neuronl;
101 
107  QVector<QColor> neurondcolor;
108 
113 };
114 
121 class FARSA_EXPERIMENTS_API Evonet : public QObject, public ParameterSettableWithConfigureFunction {
122  Q_OBJECT
123 
124  friend class NetworkDialog;
125  friend class RendNetwork;
126 signals:
130  void evonetUpdated();
131 public:
133  static const int MAXSTOREDACTIVATIONS = 100;
135  static const int MAXN = 1000;
137  static const float DEFAULT_VALUE;
148  void configure(ConfigurationParameters& params, QString prefix);
158  void save(ConfigurationParameters& params, QString prefix);
162  static void describe( QString type );
165  ParameterSettableUI* getUIManager();
173  {
174  return m_evonetUI;
175  }
182  {
183  return &neuronsMonitorUploader;
184  }
188  Evonet();
189 
190  Evonet* cloneNet() const;
191 
199  void setNetworkName(const QString& name);
205  const QString& getNetworkName() const;
216  void create_net_block( int inputNeuronType, int hiddenNeuronType, int outputNeuronType, bool recurrentHiddens, bool inputOutputConnections, bool recurrentOutputs, bool biasOnHidden, bool biasOnOutput );
223  int load_net_blocks(const char *filename, int mode);
230  void save_net_blocks(const char *filename, int mode);
240  void readNewPheLine(QStringList, float*, float*);
251  void readOldPheLine(QStringList, float*, float*);
258  void updateNet();
264  void computeParameters();
271  int setInput(int inp, float value);
277  float getOutput(int out);
283  float getInput(int in);
289  float getHidden(int h);
293  void resetNet();
297  int freeParameters();
301  float getFreeParameter(int i);
307  void setParameters(const float* dt);
313  void setParameters(const int* dt);
320  void getMutations(float* mut);
327  void copyPheParameters(int* pheGene);
332  void printIO();//to print inputs and outputs
338  int getParamBias(int nbias);
342  float getWrange();
346  float getBrange();
350  float getGrange();
357  void injectHidden(int nh, float val);
363  float logistic(float f);
367  void printBlocks();
371  int getNoInputs();
375  int getNoHiddens();
379  int getNoOutputs();
383  int getNoNeurons();
389  float getNeuron(int in);
393  bool pheFileLoaded();
400  void activateMonitorUpdate();
404  void deactivateMonitorUpdate();
405 
406  char neuronl[MAXN][10];
410  int neurondisplay[MAXN]; // whether neurons should be displayed or not
415  double neuronrange[MAXN][2]; // the range of variation of the neuron
419  QColor neurondcolor[MAXN];
423  bool neuronlesion[MAXN]; // if >0 the n neurons will be silented
427  float neuronlesionVal[MAXN]; //value to be assigned to the lesioned neuron
440  void setRanges(double weight, double bias, double gain);
451  float* getOldestStoredActivations();
457  int updateCounts();
462  float **selectedp;
472 
473  /******************** backpropagation *************************************/
474 
483  void prepareForTraining(QVector<float>& err_w);
487  float tansig(float f);
493  void initWeightsInRange(float min, float max);
501  void initWeightsInRange(float minBias, float maxBias, float minWeight, float maxWeight);
507  void initWeightsNguyenWidrow(float min, float max);
511  void printWeights();
515  void printAct();
519  void endTraining();
520 
526  float computeMeanSquaredError(QVector<float> trainingSet, QVector<float> desiredOutput);
527 
533  bool showTeachingInput();
534 
541  float getTeachingInputEntry(int id);
542 
548  float getBackPropError();
549 
557  float backPropStep(QVector<float> tInput, double rate);
558 
567  float backPropStep2(QVector<float> tInput, double rate);
568 
575  void calculateBackPropagationError(QVector<float> tInput);
576 
580  void initBackPropFreep();
581 
585  void updateWeightsAfterBackProp();
586 
592  float* getBackPropWeightModification();
593 
594  void saveCopyBackPropFreep();
595 
596  void initCopyBackPropFreep();
597 
598  float* getCopyBackPropFreep();
599 
600  float* getActivations();
601 
602  float* getNetInputs();
603 
610  float trainLevembergMarquardt(QVector<float> trainingSet, QVector<float> desiredOutput, float maxError);
618  float trainLevembergMarquardtThroughTime(QVector<float> trainingSet, QVector<float> desiredOutput, int time, float maxError);
619 
623  void hardwire();
627  int extractWeightsFromNet(Eigen::VectorXf& w);
631  int importWeightsFromVector(Eigen::VectorXf& w);
632  int importWeightsFromMATLABFile(char *path);
633  int exportWeightsToMATLABFile(char *path);
637  float getWeight(int to, int from);
641  void setWeight(int to, int from, float w);
645  void setNeckReflex();
650  bool inTraining() { return training; };
651 private:
652  int isHidden(int neuron);
656  float derivative(int n, float x);
657 
661  bool training;
665  int nconnections;
669  int n_outputsToTrain;
673  char *outputsToTrain;
674 
675  char **trainingHiddenBlock;
676 
677  QVector<float> err_weights;
678  float err_weight_sum;
679 /*********************** End back-propagation **************************************************/
680 
681 private:
685  int ninputs;
689  int nhiddens;
693  int noutputs;
697  int nneurons;
701  int net_nblocks; // network number of connection blocks
708  int net_block[MAXN][6];
712  int neuronbias[MAXN];
716  int neurontype[MAXN];
720  int neurongain[MAXN];
724  int neuronxy[MAXN][2];
728  float wrange;
732  float grange;
736  float brange;
740  int nparameters;
741  int nparambias; // number of parametric bias to add to the number of genes need for the nnet
742 
746  float act[MAXN];
747  float storedActivations[MAXSTOREDACTIVATIONS][MAXN]; // Stored activations
748  int nextStoredActivation; // The index where the next activation will be stored
749  int firstStoredActivation; // The index of the first activation that was stored (since the stored activations were reset)
753  float input[MAXN];
757  float netinput[MAXN];
761  float *freep;
765  float *backpropfreep;
766 
767  float *copybackpropfreep;
771  float backproperror;
775  QVector<float> teachingInput;
779  bool showTInput;
783  bool updateMonitor;
787  float *phep; //dynamically resized to contain manually set values specified in .phe files
791  bool pheloaded; //whether a .phe file has been loaded
795  float *muts; //mutation parameters
799  int geneMaxValue;
803  int updatescounter;
804 
805  int p; //usato come puntatore per data
806  int ndata; //number of free parameters
810  int drawnymax;
814  int drawnxmax;
818  QString netFile;
819 
823  QString networkName;
824 
828  DataUploader<ActivationsToGui> neuronsMonitorUploader;
829 
834  EvonetUI* m_evonetUI;
835 };
836 
837 } // end namespace farsa
838 
839 #endif
int nselected
Number of parameters selected through the graphic interface Enable the user to modify the parameters ...
Definition: evonet.h:467
FARSA_UTIL_TEMPLATE const T max(const T &t1, const U &t2)
bool updateNeuronMonitor
Set to true if labels or colors have to be updated in the neuron monitor.
Definition: evonet.h:431
bool updateLabelAndColors
If true the gui should update labels and colors.
Definition: evonet.h:112
DataUploader< ActivationsToGui > * getNeuronsMonitorUploader()
Returns the uploader for activations.
Definition: evonet.h:181
EvonetUI * getCurrentUIManager() const
Returns the current instance of the UI manager.
Definition: evonet.h:172
This file contains the common type defitions used on the whole framework.
int neuronlesions
Whether one or more neurons have been lesioned.
Definition: evonet.h:471
QVector< float > data
The vector with data.
Definition: evonet.h:88
Evonet is the neural network taken from the EvoRobot.
Definition: evonet.h:121
QVector< QColor > neurondcolor
The color for each neuron.
Definition: evonet.h:107
bool activations
Whether data in the vector is neurons activations or net intput and error.
Definition: evonet.h:83
FARSA_UTIL_TEMPLATE const T min(const T &t1, const U &t2)
int maxIterations
Maximum number of training iteration.
Definition: evonet.h:649
The class with data exchanged with the GUI.
Definition: evonet.h:73
float ** selectedp
pointer to the list pointer-to-parameters selected through the graphic interface Enable the user to m...
Definition: evonet.h:462
QVector< QString > neuronl
Neuron labels.
Definition: evonet.h:100
int updatesCounter
The current step.
Definition: evonet.h:93
static const float DEFAULT_VALUE
DEFAULT_VALUE is used for do not assign values to mut and parameters.
Definition: evonet.h:137