Added the monitoring facilities for snapshots (i.e. generating and plotting a new file

every generation) which is different from the continuous monitoring (same file/plot is
angemented every generation).
This lead to a number of modifications in many files in utils dir

But now we can watch on-line
- fitness spreadout
- FDC plots
- multi-objective Pareto fronts (though the multi-objective sruff isn't there yet!)
This commit is contained in:
evomarc 2001-01-31 18:38:39 +00:00
commit 56abe66582
10 changed files with 817 additions and 268 deletions

View file

@ -41,11 +41,11 @@ class eoDistance : public eoBF<const EOT &, const EOT &, double>
assumes the 2 things are vectors of something that is double-castable
*/
template< class T >
class eoQuadDistance : public eoDistance<vector<T> >
template< class EOT >
class eoQuadDistance : public eoDistance<EOT>
{
public:
double operator()(const vector<T> & _v1, const vector<T> & _v2)
double operator()(const EOT & _v1, const EOT & _v2)
{
double sum=0.0;
for (unsigned i=0; i<_v1.size(); i++)

136
eo/src/utils/eoFDCStat.h Normal file
View file

@ -0,0 +1,136 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoFDCStat.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _eoFDCStat_h
#define _eoFDCStat_h
#include <utils/eoStat.h>
#include <utils/eoDistance.h>
#include <utils/eoFileSnapshot.h>
/**
The FDC computation - stores the values into eoValueParam<EOT,double>
so they can be snapshot by some eoGnuplotSnapshot ...
*/
template <class EOT>
class eoFDCStat : public eoStat<EOT, double>
{
public :
/** Ctor without the optimum
*/
eoFDCStat(eoDistance<EOT> & _dist, std::string _description = "FDC") :
eoStat<EOT,double>(0, _description), dist(_dist), boolOpt(false) {}
/** Ctor with the optimum
*/
eoFDCStat(eoDistance<EOT> & _dist, EOT & _theBest,
std::string _description = "FDC") :
eoStat<EOT,double>(0, _description), dist(_dist),
theBest(_theBest), boolOpt(true) {}
/** Compute the FDC - either from best in pop, or from absolute best
* if it was past in the constructor
*/
virtual void operator()(const eoPop<EOT>& _pop)
{
if (!boolOpt) // take the local best
theBest = _pop.best_element();
unsigned int pSize = _pop.size();
distToBest.value().resize(pSize);
fitnesses.value().resize(pSize);
double sumFit = 0.0, sumDist = 0.0;
for (unsigned i=0; i<pSize; i++)
{
sumDist += (distToBest.value()[i] = dist(_pop[i], theBest));
sumFit += (fitnesses.value()[i] = _pop[i].fitness());
}
// now the FDC coefficient
double avgDist = sumDist/pSize;
double avgFit = sumFit/pSize;
sumDist = sumFit = 0.0;
double num = 0.0;
for (unsigned i=0; i<pSize; i++)
{
double devDist = distToBest.value()[i] - avgDist ;
double devFit = fitnesses.value()[i] - avgFit ;
sumDist += devDist*devDist;
sumFit += devFit * devFit;
num += devDist * devFit ;
}
value() = num/(sqrt(sumDist)*sqrt(sumFit));
}
/** accessors to the private eoValueParam<vector<double> >
*/
const eoValueParam<vector<double> > & theDist()
{ return distToBest; }
const eoValueParam<vector<double> > & theFit()
{ return fitnesses; }
private:
eoDistance<EOT> & dist;
EOT theBest;
bool boolOpt; // whether the best is known or not
eoValueParam<vector<double> > distToBest;
eoValueParam<vector<double> > fitnesses;
};
/** Specific class for FDCStat monitoring:
* As I failed to have FDC stat as an eoStat, this is the trick
* to put the 2 eoParam<vector<double> > into a monitor
* This class does nothing else.
*/
template <class EOT>
class eoFDCFileSnapshot : public eoFileSnapshot // is an eoMonitor
{
public:
/** Ctor: in addition to the parameters of the ctor of an eoFileSnapshot
we need here an eoFDCStat. The 2 vectors (distances to optimum
and fitnesses) are added to the monitor so they can be processed
later to a file - and eventually by gnuplot
*/
eoFDCFileSnapshot(eoFDCStat<EOT> & _FDCstat,
std::string _dirname = "tmpFDC", unsigned _frequency = 1,
std::string _filename = "FDC", std::string _delim = " "):
eoFileSnapshot(_dirname, _frequency, _filename, _delim),
FDCstat(_FDCstat)
{
eoMonitor::add(FDCstat.theDist());
eoMonitor::add(FDCstat.theFit());
}
/** just to be sure the add method is not called further
*/
virtual void add(const eoParam& _param)
{ throw runtime_error("Trying to add stats to an eoFDCFileSnapshot"); }
private:
eoFDCStat<EOT> & FDCstat;
};
#endif

View file

@ -0,0 +1,174 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoFileSnapshot.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _eoFileSnapshot_h
#define _eoFileSnapshot_h
#include <string>
#include <fstream>
#include <utils/eoParam.h>
#include <utils/eoMonitor.h>
#include <eoObject.h>
/**
Prints snapshots of fitnesses to a (new) file every N generations
Assumes that the parameters that are passed to the monitor
(method add in eoMonitor.h) are eoValueParam<vector<double> > of same size.
A dir is created and one file per snapshot is created there -
so you can later generate a movie!
TODO: The counter is handled internally, but this should be changed
so that you can pass e.g. an evalcounter (minor)
I failed to templatize everything so that it can handle eoParam<vector<T> >
for any type T, simply calling their getValue method ...
*/
class eoFileSnapshot : public eoMonitor
{
public :
typedef vector<double> vDouble;
typedef eoValueParam<vector<double> > vDoubleParam;
eoFileSnapshot(std::string _dirname, unsigned _frequency = 1,
std::string _filename = "gen", std::string _delim = " "):
dirname(_dirname), frequency(_frequency),
filename(_filename), delim(_delim), counter(0), boolChanged(true)
{
string s = "test -d " + dirname;
int res = system(s.c_str());
// test for (unlikely) errors
if ( (res==-1) || (res==127) )
throw runtime_error("Problem executing test of dir in eoFileSnapshot");
// now make sure there is a dir without any genXXX file in it
if (res) // no dir present
{
s = string("mkdir ")+dirname;
}
else
{
s = string("/bin/rm ")+dirname+ "/" + filename + "*";
}
system(s.c_str());
// all done
}
/** accessor: has something changed (for gnuplot subclass)
*/
virtual bool hasChanged() {return boolChanged;}
/** accessor to the current filename: needed by the gnuplot subclass
*/
string getFileName() {return currentFileName;}
/** sets the current filename depending on the counter
*/
void setCurrentFileName()
{
char buff[255];
ostrstream oscount(buff, 254);
oscount << counter;
oscount << std::ends;
currentFileName = dirname + "/" + filename + oscount.str();
}
/** The operator(void): opens the ostream and calls the write method
*/
eoMonitor& operator()(void)
{
if (counter % frequency)
{
boolChanged = false; // subclass with gnuplot will do nothing
counter++;
return (*this);
}
counter++;
boolChanged = true;
setCurrentFileName();
ofstream os(currentFileName.c_str());
if (!os)
{
string str = "eoFileSnapshot: Could not open " + currentFileName;
throw runtime_error(str);
}
return operator()(os);
}
/** The operator(): write on an ostream
*/
eoMonitor& operator()(std::ostream& _os)
{
const eoValueParam<vector<double> > * ptParam =
static_cast<const eoValueParam<vector<double> >* >(vec[0]);
const vector<double> v = ptParam->value();
if (vec.size() == 1) // only one vector: -> add number in front
{
for (unsigned k=0; k<v.size(); k++)
_os << k << " " << v[k] << "\n" ;
}
else // need to get all other vectors
{
vector<vector<double> > vv(vec.size());
vv[0]=v;
cout << "taille des vecteurs " << v.size() << endl;
for (unsigned i=1; i<vec.size(); i++)
{
ptParam = static_cast<const eoValueParam<vector<double> >* >(vec[1]);
vv[i] = ptParam->value();
if (vv[i].size() != v.size())
throw runtime_error("Dimension error in eoSnapshotMonitor");
}
for (unsigned k=0; k<v.size(); k++)
{
for (unsigned i=0; i<vec.size(); i++)
_os << vv[i][k] << " " ;
_os << "\n";
}
}
return *this;
}
virtual const string getDirName() // for eoGnuPlot
{ return dirname;}
virtual const string baseFileName() // the title for eoGnuPlot
{ return filename;}
private :
std::string dirname;
unsigned frequency;
std::string filename;
std::string delim;
unsigned int counter;
std::string currentFileName;
bool boolChanged;
};
#endif

276
eo/src/utils/eoGnuplot.h Normal file
View file

@ -0,0 +1,276 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoGnuplot1DMonitor.h
// (c) Marc Schoenauer, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
#ifndef _eoGnuplot_H
#define _eoGnuplot_H
#include <string>
/**
@author Marc Schoenauer 2001
@version 0.0
This class is the abstract class that will be used by further gnuplot calls
to plots what is already written by some eoMonitor into a file
*/
//-----------------------------------------------------------------------------
#include <fstream>
#include <utils/pipecom.h>
/** eoGnuplot: base class that will be used to call gnuplot
*/
class eoGnuplot
{
public:
// Ctor
eoGnuplot(std::string _title, std::string _extra = string("")) :
firstTime(true)
{
// opens pipe with Gnuplot
initGnuPlot(_title, _extra);
}
// Dtor
virtual ~eoGnuplot() {
// close - the gnuplot windows if pipe was correctly opened
if( gpCom ) {
PipeComSend( gpCom, "quit\n" ); // Ferme gnuplot
PipeComClose( gpCom );
gpCom =NULL;
}
}
/// Class name.
virtual string className() const { return "eoGnuplot"; }
protected:
void initGnuPlot(std::string _title, std::string _extra);
// the private data
bool firstTime; // the stats might be unknown in Ctor
PCom *gpCom; // Communication with gnuplot OK
private:
};
// the following should be placed in a separate eoGnuplot.cpp
static unsigned numWindow=0;
////////////////////////////////////////////////////////////
void eoGnuplot::initGnuPlot(std::string _title, std::string _extra)
/////////////////////////////////////////////////////////
{
char snum[255];
ostrstream os(snum, 254);
os << "300x200-0+" << numWindow*220 << ends;
numWindow++;
char *args[6];
args[0] = strdup( "gnuplot" );
args[1] = strdup( "-geometry" );
args[2] = strdup( os.str() );
args[3] = strdup( "-title" );
args[4] = strdup( _title.c_str() );
args[5] = 0;
gpCom = PipeComOpenArgv( "gnuplot", args );
if( ! gpCom )
throw runtime_error("Impossible to spawn gnuplot\n");
else {
PipeComSend( gpCom, "set grid\n" );
char s[1024]; // because .c_str() is a const
strcpy(s, _extra.c_str());
PipeComSend( gpCom, strdup(_extra.c_str()) );
PipeComSend( gpCom, "\n" );
}
}
// the following should be placed in a separate file pipecom.c
// together with the corresponding pipecom.h
// but first their MSC equivalent must be written and tested
// or some #idef instructions put with clear message at compile time
// that this is for Unix only ???
/* ----------------------------------------------------------------------
* Where........: CMAP - Polytechnique
* File.........: pipecom.c
* Author.......: Bertrand Lamy (Equipe genetique)
* Created......: Mon Mar 13 13:50:11 1995
* Description..: Communication par pipe bidirectionnel avec un autre process
*
* Ident........: $Id: eoGnuplot.h,v 1.1 2001-01-31 18:38:39 evomarc Exp $
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
// #include "pipecom.h"
int Check( PCom *com )
{
if( ! com ) {
fprintf( stderr, "PipeCom: Null pointer.\n" );
fflush( stderr );
return 0;
}
if( kill( com->pid, 0 ) != 0 ) {
fprintf( stderr, "PipeCom: process doesn't exists.\n" );
fflush( stderr );
return 0;
}
return 1;
}
PCom * PipeComOpen( char *prog )
{
char *args[2];
args[0] = prog;
args[1] = NULL;
return PipeComOpenArgv( prog, args );
}
PCom * PipeComOpenArgv( char *prog, char *argv[] )
{
int toFils[2];
int toPere[2];
int sonPid;
PCom * ret = NULL;
if( pipe( toFils ) < 0 ) {
perror( "PipeComOpen: Creating pipes" );
return ret;
}
if( pipe( toPere ) < 0 ) {
perror( "PipeComOpen: Creating pipes" );
return ret;
}
switch( (sonPid = vfork()) ) {
case -1:
perror("PipeComOpen: fork failed" );
return ret;
break;
case 0:
/* --- Here's the son --- */
/* --- replace old stdin --- */
if( dup2( toFils[0], fileno(stdin) ) < 0 ) {
perror( "PipeComOpen(son): could not connect" );
exit( -1 );
/* --- AVOIR: kill my father --- */
}
if( dup2( toPere[1], fileno(stdout) ) < 0 ) {
perror( "PipeComOpen(son): could not connect" );
exit( -1 );
}
if( execvp( prog, argv ) < 0 ) {
perror( prog );
perror( "PipeComOpen: can't exec" );
exit(1);
}
break;
default:
ret = (PCom *) malloc( sizeof(PCom) );
if( ! ret )
return NULL;
ret->fWrit = (FILE *)fdopen( toFils[1], "w" );
ret->fRead = (FILE *)fdopen( toPere[0], "r" );
ret->pid = sonPid;
}
return ret;
}
int PipeComSend( PCom *to, char *line )
{
int nb = 0;
if( ! Check(to ) )
return nb;
nb = fprintf( to->fWrit, line );
fflush( to->fWrit );
return nb;
}
int PipeComSendn( PCom *to, char *data, int n )
{
int nb = 0;
if( ! Check(to) )
return nb;
nb = fwrite( data, 1, n, to->fWrit );
fflush( to->fWrit );
return nb;
}
int PipeComReceive( PCom *from, char *data, int max )
{
if( ! Check(from) )
return 0;
if( ! data ) {
fprintf( stderr, "PipeComReceive: Invalid data pointer\n" );
fflush( stderr );
return 0;
}
if( fgets( data, max, from->fRead ) )
return strlen(data);
return 0;
}
int PipeComClose( PCom *to )
{
if( ! Check(to) )
return 0;
fclose( to->fRead );
fclose( to->fWrit );
free( to );
return 1;
}
int PipeComWaitFor( PCom *from, char *what )
{
char buffer[256];
do {
if( ! PipeComReceive( from, buffer, 256 ) )
return 0;
} while( strcmp( buffer, what ) );
return 1;
}
#endif _eoGnuplot_H

View file

@ -30,6 +30,7 @@
#include <string>
#include <utils/eoMonitor.h>
#include <utils/eoGnuplot.h>
#include <eoObject.h>
/**
@ -42,94 +43,33 @@ This class plots through gnuplot the eoStat given as argument
//-----------------------------------------------------------------------------
#include <fstream>
// #include "pipecom.h"
//
// this is pipecom.h
/* ----------------------------------------------------------------------
* Where........: CMAP - Polytechnique
* File.........: pipecom.h
* Author.......: Bertrand Lamy (EEAAX)
* Created......: Thu Mar 9 17:21:15 1995
* Description..: Pipe communication with a process
*
* Ident........: $Id: eoGnuplot1DMonitor.h,v 1.2 2000-11-29 17:20:16 evomarc Exp $
* ----------------------------------------------------------------------
*/
#ifndef PIPECOM_H
#define PIPECOM_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
typedef struct PipeCommunication {
FILE *fWrit;
FILE *fRead;
int pid;
} PCom;
PCom *PipeComOpen( char *prog );
PCom *PipeComOpenArgv( char *prog, char *argv[] );
int PipeComSend( PCom *to, char *line );
int PipeComSendn( PCom *to, char *data, int n );
int PipeComReceive( PCom *from, char *data, int max );
int PipeComClose( PCom *to );
int PipeComWaitFor( PCom *from, char *what );
#ifdef __cplusplus
} /* ferme extern "C" */
#endif
#endif /* PIPECOM_H */
#include <utils/pipecom.h>
/** eoGnuplot1DMonitor plots stats through gnuplot
* assumes that the same file is appened every so and so,
* and replots it everytime
*/
class eoGnuplot1DMonitor: public eoFileMonitor
class eoGnuplot1DMonitor: public eoFileMonitor, public eoGnuplot
{
public:
// Ctor
eoGnuplot1DMonitor(std::string _filename) :
eoFileMonitor(_filename, " "), firstTime(true)
{
// opens pipe with Gnuplot
initGnuPlot(_filename);
}
eoGnuplot1DMonitor(std::string _filename, bool _top=false) :
eoFileMonitor(_filename, " "),
eoGnuplot(_filename,(_top?"":"set key bottom"))
{}
// Dtor
virtual ~eoGnuplot1DMonitor() {
// close - the gnuplot windows if pipe was correctly opened
if( gpCom ) {
PipeComSend( gpCom, "quit\n" ); // Ferme gnuplot
PipeComClose( gpCom );
gpCom =NULL;
}
}
virtual ~eoGnuplot1DMonitor(){}
virtual eoMonitor& operator() (void) ;
virtual void FirstPlot();
/// Class name.
virtual string className() const { return "eoGnuplot1DMonitor"; }
private:
void initGnuPlot(std::string _filename);
void FirstPlot();
// the private data
bool firstTime; // the stats might be unknown in Ctor
PCom *gpCom; // Communication with gnuplot OK
};
// the following should be placed in a separate eoGnuplot1DMonitor.cpp
@ -157,27 +97,6 @@ eoMonitor& eoGnuplot1DMonitor::operator() (void)
return *this;
}
////////////////////////////////////////////////////////////
void eoGnuplot1DMonitor::initGnuPlot(std::string _filename)
/////////////////////////////////////////////////////////
{
char *args[6];
args[0] = strdup( "gnuplot" );
args[1] = strdup( "-geometry" );
args[2] = strdup( "300x200-0+0" );
args[3] = strdup( "-title" );
args[4] = strdup( _filename.c_str() );
args[5] = 0;
gpCom = PipeComOpenArgv( "gnuplot", args );
if( ! gpCom )
throw runtime_error("Impossible to spawn gnuplot\n");
else {
PipeComSend( gpCom, "set grid\n" );
PipeComSend( gpCom, "set data style lines\n" );
}
}
////////////////////////////////////////////////////////////
void eoGnuplot1DMonitor::FirstPlot()
////////////////////////////////////////////////////////
@ -191,7 +110,7 @@ void eoGnuplot1DMonitor::FirstPlot()
os << "plot";
for (unsigned i=1; i<vec.size(); i++) {
os << " '" << getFileName().c_str() <<
"' using 1:" << i+1 << " title '" << vec[i]->longName() << "'" ;
"' using 1:" << i+1 << " title '" << vec[i]->longName() << "' with lines" ;
if (i<vec.size()-1)
os << ", ";
}
@ -200,170 +119,4 @@ void eoGnuplot1DMonitor::FirstPlot()
PipeComSend( gpCom, buff );
}
// the following should be placed in a separate file pipecom.c
// together with the corresponding pipecom.h
// but first their MSC equivalent must be written and tested
// or some #idef instructions put with clear message at compile time
// that this is for Unix only ???
/* ----------------------------------------------------------------------
* Where........: CMAP - Polytechnique
* File.........: pipecom.c
* Author.......: Bertrand Lamy (Equipe genetique)
* Created......: Mon Mar 13 13:50:11 1995
* Description..: Communication par pipe bidirectionnel avec un autre process
*
* Ident........: $Id: eoGnuplot1DMonitor.h,v 1.2 2000-11-29 17:20:16 evomarc Exp $
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
// #include "pipecom.h"
int Check( PCom *com )
{
if( ! com ) {
fprintf( stderr, "PipeCom: Null pointer.\n" );
fflush( stderr );
return 0;
}
if( kill( com->pid, 0 ) != 0 ) {
fprintf( stderr, "PipeCom: process doesn't exists.\n" );
fflush( stderr );
return 0;
}
return 1;
}
PCom * PipeComOpen( char *prog )
{
char *args[2];
args[0] = prog;
args[1] = NULL;
return PipeComOpenArgv( prog, args );
}
PCom * PipeComOpenArgv( char *prog, char *argv[] )
{
int toFils[2];
int toPere[2];
int sonPid;
PCom * ret = NULL;
if( pipe( toFils ) < 0 ) {
perror( "PipeComOpen: Creating pipes" );
return ret;
}
if( pipe( toPere ) < 0 ) {
perror( "PipeComOpen: Creating pipes" );
return ret;
}
switch( (sonPid = vfork()) ) {
case -1:
perror("PipeComOpen: fork failed" );
return ret;
break;
case 0:
/* --- Here's the son --- */
/* --- replace old stdin --- */
if( dup2( toFils[0], fileno(stdin) ) < 0 ) {
perror( "PipeComOpen(son): could not connect" );
exit( -1 );
/* --- AVOIR: kill my father --- */
}
if( dup2( toPere[1], fileno(stdout) ) < 0 ) {
perror( "PipeComOpen(son): could not connect" );
exit( -1 );
}
if( execvp( prog, argv ) < 0 ) {
perror( prog );
perror( "PipeComOpen: can't exec" );
exit(1);
}
break;
default:
ret = (PCom *) malloc( sizeof(PCom) );
if( ! ret )
return NULL;
ret->fWrit = (FILE *)fdopen( toFils[1], "w" );
ret->fRead = (FILE *)fdopen( toPere[0], "r" );
ret->pid = sonPid;
}
return ret;
}
int PipeComSend( PCom *to, char *line )
{
int nb = 0;
if( ! Check(to ) )
return nb;
nb = fprintf( to->fWrit, line );
fflush( to->fWrit );
return nb;
}
int PipeComSendn( PCom *to, char *data, int n )
{
int nb = 0;
if( ! Check(to) )
return nb;
nb = fwrite( data, 1, n, to->fWrit );
fflush( to->fWrit );
return nb;
}
int PipeComReceive( PCom *from, char *data, int max )
{
if( ! Check(from) )
return 0;
if( ! data ) {
fprintf( stderr, "PipeComReceive: Invalid data pointer\n" );
fflush( stderr );
return 0;
}
if( fgets( data, max, from->fRead ) )
return strlen(data);
return 0;
}
int PipeComClose( PCom *to )
{
if( ! Check(to) )
return 0;
fclose( to->fRead );
fclose( to->fWrit );
free( to );
return 1;
}
int PipeComWaitFor( PCom *from, char *what )
{
char buffer[256];
do {
if( ! PipeComReceive( from, buffer, 256 ) )
return 0;
} while( strcmp( buffer, what ) );
return 1;
}
#endif _eoGnuplot1DMonitor_H

View file

@ -0,0 +1,107 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoGnuplot1DSnapshot.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _eoGnuplot1DSnapshot_H
#define _eoGnuplot1DSnapshot_H
#include <string>
#include <utils/eoFileSnapshot.h>
#include <utils/eoGnuplot.h>
#include <eoObject.h>
/**
@author Marc Schoenauer 2000
@version 0.0
This class plots through gnuplot the eoStat given as argument
*/
//-----------------------------------------------------------------------------
#include <fstream>
#include <utils/pipecom.h>
/** eoGnuplot1DMonitor plots stats through gnuplot
* assumes that the same file is appened every so and so,
* and replots it everytime
*/
class eoGnuplot1DSnapshot: public eoFileSnapshot, public eoGnuplot
{
public:
// Ctor
eoGnuplot1DSnapshot(std::string _dirname, unsigned _frequency = 1,
std::string _filename = "gen", std::string _delim = " ") :
eoFileSnapshot(_dirname, _frequency, _filename, _delim),
eoGnuplot(_filename,"set data style points")
{}
// Ctor
eoGnuplot1DSnapshot(eoFileSnapshot & _fSnapshot) :
eoFileSnapshot(_fSnapshot),
eoGnuplot(_fSnapshot.baseFileName(),"set data style points")
{}
// Dtor
virtual ~eoGnuplot1DSnapshot(){}
virtual eoMonitor& operator() (void) ;
/// Class name.
virtual string className() const { return "eoGnuplot1DSnapshot"; }
private:
};
// the following should be placed in a separate eoGnuplot1DMonitor.cpp
////////////////////////////////////////////////////////////
eoMonitor& eoGnuplot1DSnapshot::operator() (void)
/////////////////////////////////////////////////////////
{
// update file using the eoFileMonitor
eoFileSnapshot::operator()();
// sends plot order to gnuplot
// assumes successive plots will have same nb of columns!!!
char buff[1024];
ostrstream os(buff, 1024);
os << "plot";
os << " '" << getFileName().c_str() <<
"' notitle with points ps 5" ;
os << "\n";
os << '\0';
PipeComSend( gpCom, buff );
return (*this);
}
#endif _eoGnuplot1DSnapshot_H

View file

@ -46,7 +46,7 @@ class eoMonitor : public eoF<eoMonitor&>
public :
virtual void lastCall() {}
void add(const eoParam& _param) { vec.push_back(&_param); }
virtual void add(const eoParam& _param) { vec.push_back(&_param); }
protected :

View file

@ -227,6 +227,29 @@ void eoValueParam<std::vector<double> >::setValue(std::string _value)
std::copy(std::istream_iterator<double>(is), std::istream_iterator<double>(), repValue.begin());
}
/// Because MSVC does not support partial specialization, the vector is a eoMinimizingFitness, not a T
template <>
std::string eoValueParam<std::vector<eoMinimizingFitness> >::getValue(void) const
{
std::ostrstream os;
os << repValue.size() << ' ';
std::copy(repValue.begin(), repValue.end(), std::ostream_iterator<eoMinimizingFitness>(os, " "));
os << std::ends;
return os.str();
}
/// Because MSVC does not support partial specialization, the vector is a eoMinimizingFitness, not a T
// NOTE: g++ doesn support it either!!!
template <>
void eoValueParam<std::vector<eoMinimizingFitness> >::setValue(std::string _value)
{
std::istrstream is(_value.c_str());
unsigned sz;
is >> sz;
repValue.resize(sz);
std::copy(std::istream_iterator<eoMinimizingFitness>(is), std::istream_iterator<eoMinimizingFitness>(), repValue.begin());
}
/*template <class ContainerType>
class eoContainerParam : public eoParam
{

View file

@ -0,0 +1,50 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoScalarFitnessStat.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _eoScalarFitnessStat_h
#define _eoScalarFitnessStat_h
#include <utils/eoStat.h>
/**
The fitnesses of a whole population, as a vector
*/
template <class EOT, class FitT = typename EOT::Fitness>
class eoScalarFitnessStat : public eoSortedStat<EOT, vector<FitT> >
{
public :
eoScalarFitnessStat(std::string _description = "FitnessES") :
eoSortedStat<EOT, vector<FitT> >(vector<FitT>(0), _description) {}
virtual void operator()(const vector<const EOT*>& _popPters)
{
value().resize(_popPters.size());
for (unsigned i=0; i<_popPters.size(); i++)
value()[i] = _popPters[i]->fitness();
}
};
#endif

View file

@ -14,7 +14,10 @@
// the general include for eo
#include <eo>
#include <utils/eoScalarFitnessStat.h>
#include <utils/eoGnuplot1DMonitor.h>
#include <utils/eoGnuplot1DSnapshot.h>
#include <utils/eoFDCStat.h>
// EVAL
#include "binary_value.h"
@ -24,7 +27,7 @@
// Include the corresponding file
#include <ga.h> // bitstring representation & operators
// define your genotype and fitness types
typedef eoBin<double> Indi;
typedef eoBin<eoMinimizingFitness> Indi;
// the main_function: nothing changed(!), except variable initialization
void main_function(int argc, char **argv)
@ -235,10 +238,10 @@ void main_function(int argc, char **argv)
/////////////////////////////////////
eoGenContinue<Indi> genCont(maxGen);
eoSteadyFitContinue<Indi> steadyCont(minGen, steadyGen);
eoFitContinue<Indi> fitCont(vecSize);
// eoFitContinue<Indi> fitCont(vecSize); // remove if minimizing :-)
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// continuator.add(fitCont);
// CHECKPOINT
@ -269,15 +272,20 @@ void main_function(int argc, char **argv)
eoAverageStat<Indi> averageStat;
// Second moment stats: average and stdev
eoSecondMomentStats<Indi> SecondStat;
// the Fitness Distance Correlation
// need first an object to compute the distances
eoQuadDistance<Indi> dist; // Hamming distance
eoFDCStat<Indi> fdcStat(dist);
// Add them to the checkpoint to get them called at the appropriate time
checkpoint.add(bestStat);
checkpoint.add(averageStat);
checkpoint.add(SecondStat);
checkpoint.add(fdcStat);
// The Stdout monitor will print parameters to the screen ...
eoStdoutMonitor monitor(false);
// when called by the checkpoint (i.e. at every generation)
checkpoint.add(monitor);
@ -286,10 +294,12 @@ void main_function(int argc, char **argv)
monitor.add(eval); // because now eval is an eoEvalFuncCounter!
monitor.add(bestStat);
monitor.add(SecondStat);
monitor.add(fdcStat);
// A file monitor: will print parameters to ... a File, yes, you got it!
eoFileMonitor fileMonitor("stats.xg", " ");
eoGnuplot1DMonitor gnuMonitor("best_average.xg");
// and an eoGnuplot1DMonitor will 1-print to a file, and 2- plot on screen
eoGnuplot1DMonitor gnuMonitor("best_average.xg",minimizing_fitness<Indi>());
// the checkpoint mechanism can handle multiple monitors
checkpoint.add(fileMonitor);
@ -304,6 +314,26 @@ void main_function(int argc, char **argv)
gnuMonitor.add(bestStat);
gnuMonitor.add(averageStat);
// a specific plot monitor for FDC
// first into a file (it adds everything ti itself
eoFDCFileSnapshot<Indi> fdcFileSnapshot(fdcStat);
// then to a Gnuplot monitor
eoGnuplot1DSnapshot fdcGnuplot(fdcFileSnapshot);
// and of coruse add them to the checkPoint
checkpoint.add(fdcFileSnapshot);
checkpoint.add(fdcGnuplot);
// want to see how the fitness is spread?
eoScalarFitnessStat<Indi> fitStat;
checkpoint.add(fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name
// where to store the files
eoGnuplot1DSnapshot fitSnapshot("Fitnesses");
// add any stat that is a vector<double> to it
fitSnapshot.add(fitStat);
// and of course add it to the checkpoint
checkpoint.add(fitSnapshot);
// Last type of item the eoCheckpoint can handle: state savers:
eoState outState;
// Register the algorithm into the state (so it has something to save!!)