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 <stdio.h>
31 #include <math.h>
32 #include <string.h>
33 #include <iostream>
34 #include <stdlib.h>
35 #include <QString>
36 #include <QStringList>
37 #include <QColor>
38 #include <QDebug>
39 #include <QObject>
40 #include <QMutex>
41 
42 // All this stuff is to get rid of annoying warnings...
43 #ifdef __GNUC__
44  #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5)
45  #pragma GCC diagnostic push
46  #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
47  #else
48  #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
49  #endif
50 #endif
51 
52 #include "Eigen/Dense"
53 
54 #ifdef __GNUC__
55  #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5)
56  #pragma GCC diagnostic pop
57  #else
58  #pragma GCC diagnostic warning "-Wunused-local-typedefs"
59  #endif
60 #endif
61 
62 namespace farsa {
63 
70 class FARSA_EXPERIMENTS_API Evonet : public QObject, public ParameterSettableWithConfigureFunction {
71  Q_OBJECT
72 
73  friend class NetworkDialog;
74  friend class RendNetwork;
75 signals:
79  void evonetUpdated();
80 public:
82  static const int MAXSTOREDACTIVATIONS = 100;
84  static const int MAXN = 1000;
86  static const float DEFAULT_VALUE;
97  void configure(ConfigurationParameters& params, QString prefix);
107  void save(ConfigurationParameters& params, QString prefix);
111  static void describe( QString type );
114  ParameterSettableUI* getUIManager();
120  void create_net_block( int inputNeuronType, int hiddenNeuronType, int outputNeuronType, bool recurrentHiddens, bool inputOutputConnections, bool recurrentOutputs, bool biasOnHidden, bool biasOnOutput );
126  int load_net_blocks(const char *filename, int mode);
127  void save_net_blocks(const char *filename, int mode);
128  void readNewPheLine(QStringList, float*, float*);
129  void readOldPheLine(QStringList, float*, float*);
130  void updateNet();
131  void computeParameters();
132  int setInput(int inp, float value); //
133  float getOutput(int out);
134  float getInput(int in);
135  float getHidden(int h);
136  void resetNet();
137  int freeParameters(); //return number of free parameters
138  float getFreeParameter(int i); // Returns the i-th free parameter
139  void setParameters(const int* dt);
140  void getMutations(float* mut);
141  void copyPheParameters(int* pheGene);
142  void printIO();//to print inputs and outputs
143  int getParamBias(int nbias);
144  float getWrange();
145  void injectHidden(int nh, float val);
146  float logistic(float f);
147  void printBlocks();
148  int getNoInputs();
149  int getNoHiddens();
150  int getNoOutputs();
151  int getNoNeurons();
152  float getNeuron(int in);
153  bool pheFileLoaded();
154  Evonet();
155  char neuronl[MAXN][10];
156  int neurondisplay[MAXN]; // whether neurons should be displayed or not
157  double neuronrange[MAXN][2]; // the range of variation of the neuron
158  QColor neurondcolor[MAXN]; // the color used by the neuron monitor
159  bool neuronlesion[MAXN]; // if >0 the n neurons will be silented
160  float neuronlesionVal[MAXN]; //value to be assigned to the lesioned neuron
161  void setRanges(double weight, double bias, double gain); // set ranges of weights, biases and gains
172  float* getOldestStoredActivations();
178  int updateCounts();
179  float **selectedp; //pointer to a list of selected parameters
180  int nselected; //number of selected parameters
181  int neuronlesions; // whether some of the neurons has been lesioned or manually set
182 
184  float tansig(float f);
185  int maxIterations;
186 
187  bool inTraining() { return training; };
188 
189  void initWeightsInRange(float min, float max);
190  void initWeightsNguyenWidrow(float min, float max);
191  void printWeights();
192  void printAct();
193  void prepareForTraining(QVector<float>& err_w);
194  void endTraining();
195 
196  float computeMeanSquaredError(QVector<float> trainingSet, QVector<float> desiredOutput);
197  float trainLevembergMarquardt(QVector<float> trainingSet, QVector<float> desiredOutput, float maxError);
198  float trainLevembergMarquardtThroughTime(QVector<float> trainingSet, QVector<float> desiredOutput, int time, float maxError);
199 
200  void hardwire();
201  int extractWeightsFromNet(Eigen::VectorXf& w);
202  int importWeightsFromVector(Eigen::VectorXf& w);
203  int importWeightsFromMATLABFile(char *path);
204  int exportWeightsToMATLABFile(char *path);
205  float getWeight(int to, int from);
206  void setWeight(int to, int from, float w);
207 
208  void setNeckReflex();
209 private:
210  int isHidden(int neuron);
211  float derivative(int n, float x);
212 
213  bool training;
214  int nconnections;
215  int n_outputsToTrain;
216  char *outputsToTrain;
217 
218  char **trainingHiddenBlock;
219 
220  QVector<float> err_weights;
221  float err_weight_sum;
223 
224 private:
225  int ninputs; // n. input units
226  int nhiddens; // n. hidden units
227  int noutputs; // n. output units
228  int nneurons; // total n. of neurons
229  int net_nblocks; // network number of connection blocks
230  int net_block[MAXN][6]; // blocks: 0=(connection,update,gain), 12=(id first neuron and n.neurons), 34=(id second neuron and n.neurons, optional),5=(genetic, fixed, backprop)
231  int neuronbias[MAXN]; // whether neurons have bias
232  int neurontype[MAXN]; // the type of neuron (0=logistic,1=dynamic with timeconstant, 2=binary, 3=logistic netinput*0.2
233  int neurongain[MAXN]; // whether neurons have gain parameters
234  int neuronxy[MAXN][2]; // neurons xy position in display space
235  float wrange; // weights range
236  float grange; // gain range
237  float brange; // bias range
238  int nparameters; // usefull to set GA parameters number of free parameters
239  int nparambias; // number of parametric bias to add to the number of genes need for the nnet
240  // neurons label by default Input In0 In1.. Hidden: Hid0 Hid1 Output: Out0
241 
242  //variable to compute activation
243  float act[MAXN]; //activation
244  float storedActivations[MAXSTOREDACTIVATIONS][MAXN]; // Stored activations
245  int nextStoredActivation; // The index where the next activation will be stored
246  int firstStoredActivation; // The index of the first activation that was stored (since the stored activations were reset)
247  float input[MAXN]; //input vector
248  float netinput[MAXN];
249  float *freep; //dynamically resized to contain needed parameters
250  float *phep; //dynamically resized to contain manually set values specified in .phe files
251  bool pheloaded; //whether a .phe file has been loaded
252  float *muts; //mutation parameters
253  int geneMaxValue; //how parameters are codified into the GA (es. 255, 511, 1023 <0 is included!>)
254 
255  // counter of updates of the network; resetted to zero by resetNet, incremented by updateNet
256  int updatescounter;
257 
258  int p; //usato come puntatore per data
259  int ndata; //number of free parameters
260  //variable for rendering
261  int drawnymax;
262  int drawnxmax;
263 
264  // ConfigurationParameters variables
265  QString netFile;
266 
267 };
268 
269 } // end namespace farsa
270 
271 #endif