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 
72 {
82 
86  QVector<float> data;
87 
92 };
93 
100 class FARSA_EXPERIMENTS_API Evonet : public QObject, public ParameterSettableWithConfigureFunction {
101  Q_OBJECT
102 
103  friend class NetworkDialog;
104  friend class RendNetwork;
105 signals:
109  void evonetUpdated();
110 public:
112  static const int MAXSTOREDACTIVATIONS = 100;
114  static const int MAXN = 1000;
116  static const float DEFAULT_VALUE;
127  void configure(ConfigurationParameters& params, QString prefix);
137  void save(ConfigurationParameters& params, QString prefix);
141  static void describe( QString type );
144  ParameterSettableUI* getUIManager();
148  Evonet();
156  void setNetworkName(const QString& name);
162  const QString& getNetworkName() const;
173  void create_net_block( int inputNeuronType, int hiddenNeuronType, int outputNeuronType, bool recurrentHiddens, bool inputOutputConnections, bool recurrentOutputs, bool biasOnHidden, bool biasOnOutput );
180  int load_net_blocks(const char *filename, int mode);
187  void save_net_blocks(const char *filename, int mode);
197  void readNewPheLine(QStringList, float*, float*);
208  void readOldPheLine(QStringList, float*, float*);
215  void updateNet();
221  void computeParameters();
228  int setInput(int inp, float value);
234  float getOutput(int out);
240  float getInput(int in);
246  float getHidden(int h);
250  void resetNet();
254  int freeParameters();
258  float getFreeParameter(int i);
264  void setParameters(const int* dt);
271  void getMutations(float* mut);
278  void copyPheParameters(int* pheGene);
283  void printIO();//to print inputs and outputs
289  int getParamBias(int nbias);
293  float getWrange();
297  float getBrange();
301  float getGrange();
308  void injectHidden(int nh, float val);
314  float logistic(float f);
318  void printBlocks();
322  int getNoInputs();
326  int getNoHiddens();
330  int getNoOutputs();
334  int getNoNeurons();
340  float getNeuron(int in);
344  bool pheFileLoaded();
348  char neuronl[MAXN][10];
352  int neurondisplay[MAXN]; // whether neurons should be displayed or not
357  double neuronrange[MAXN][2]; // the range of variation of the neuron
361  QColor neurondcolor[MAXN];
365  bool neuronlesion[MAXN]; // if >0 the n neurons will be silented
369  float neuronlesionVal[MAXN]; //value to be assigned to the lesioned neuron
378  void setRanges(double weight, double bias, double gain);
389  float* getOldestStoredActivations();
395  int updateCounts();
400  float **selectedp;
410 
411  /******************** backpropagation *************************************/
412 
421  void prepareForTraining(QVector<float>& err_w);
425  float tansig(float f);
431  void initWeightsInRange(float min, float max);
439  void initWeightsInRange(float minBias, float maxBias, float minWeight, float maxWeight);
445  void initWeightsNguyenWidrow(float min, float max);
449  void printWeights();
453  void printAct();
457  void endTraining();
458 
464  float computeMeanSquaredError(QVector<float> trainingSet, QVector<float> desiredOutput);
465 
471  bool showTeachingInput();
472 
479  float getTeachingInputEntry(int id);
480 
486  float getBackPropError();
487 
495  float backPropStep(QVector<float> tInput, double rate);
496 
505  float backPropStep2(QVector<float> tInput, double rate);
506 
513  void calculateBackPropagationError(QVector<float> tInput);
514 
518  void initBackPropFreep();
519 
523  void updateWeightsAfterBackProp();
524 
531  float trainLevembergMarquardt(QVector<float> trainingSet, QVector<float> desiredOutput, float maxError);
539  float trainLevembergMarquardtThroughTime(QVector<float> trainingSet, QVector<float> desiredOutput, int time, float maxError);
540 
544  void hardwire();
548  int extractWeightsFromNet(Eigen::VectorXf& w);
552  int importWeightsFromVector(Eigen::VectorXf& w);
553  int importWeightsFromMATLABFile(char *path);
554  int exportWeightsToMATLABFile(char *path);
558  float getWeight(int to, int from);
562  void setWeight(int to, int from, float w);
566  void setNeckReflex();
571  bool inTraining() { return training; };
572 private:
573  int isHidden(int neuron);
577  float derivative(int n, float x);
578 
582  bool training;
586  int nconnections;
590  int n_outputsToTrain;
594  char *outputsToTrain;
595 
596  char **trainingHiddenBlock;
597 
598  QVector<float> err_weights;
599  float err_weight_sum;
600 /*********************** End back-propagation **************************************************/
601 
602 private:
606  int ninputs;
610  int nhiddens;
614  int noutputs;
618  int nneurons;
622  int net_nblocks; // network number of connection blocks
629  int net_block[MAXN][6];
633  int neuronbias[MAXN];
637  int neurontype[MAXN];
641  int neurongain[MAXN];
645  int neuronxy[MAXN][2];
649  float wrange;
653  float grange;
657  float brange;
661  int nparameters;
662  int nparambias; // number of parametric bias to add to the number of genes need for the nnet
663 
667  float act[MAXN];
668  float storedActivations[MAXSTOREDACTIVATIONS][MAXN]; // Stored activations
669  int nextStoredActivation; // The index where the next activation will be stored
670  int firstStoredActivation; // The index of the first activation that was stored (since the stored activations were reset)
674  float input[MAXN];
678  float netinput[MAXN];
682  float *freep;
686  float *backpropfreep;
690  float backproperror;
694  QVector<float> teachingInput;
698  bool showTInput;
702  float *phep; //dynamically resized to contain manually set values specified in .phe files
706  bool pheloaded; //whether a .phe file has been loaded
710  float *muts; //mutation parameters
714  int geneMaxValue;
718  int updatescounter;
719 
720  int p; //usato come puntatore per data
721  int ndata; //number of free parameters
725  int drawnymax;
729  int drawnxmax;
733  QString netFile;
734 
738  QString networkName;
739 
743  DataUploader<ActivationsToGui> neuronsMonitorUploader;
744 };
745 
746 } // end namespace farsa
747 
748 #endif