New style for PEO

git-svn-id: svn://scm.gforge.inria.fr/svnroot/paradiseo@789 331e1502-861f-0410-8da2-ba01fb791d7f
This commit is contained in:
canape 2007-11-16 11:34:20 +00:00
commit 9c87b3b0c0
132 changed files with 3781 additions and 3396 deletions

View file

@ -58,6 +58,8 @@ structure:
| |
| |
+-- tutorial APPLICATIONS +-- tutorial APPLICATIONS
|
+-- examples TSP
| |
+-- Introduction Technical introduction +-- Introduction Technical introduction
| |
@ -69,7 +71,9 @@ structure:
| |
+-- Lesson4 PSO and EA completely parallel +-- Lesson4 PSO and EA completely parallel
| |
+-- Lesson5 Multi-start : several local searches +-- Lesson5 Hybridization
|
+-- Lesson6 Multi-start : several local searches
=================================================================== ===================================================================
NOTES NOTES

View file

@ -46,7 +46,8 @@ static std :: map <const Communicable *, unsigned> comm_to_key; /* Map of regist
unsigned Communicable :: num_comm = 0; unsigned Communicable :: num_comm = 0;
Communicable :: Communicable () { Communicable :: Communicable ()
{
comm_to_key [this] = key = ++ num_comm; comm_to_key [this] = key = ++ num_comm;
key_to_comm.push_back (this); key_to_comm.push_back (this);
@ -54,41 +55,48 @@ Communicable :: Communicable () {
sem_init (& sem_stop, 0, 0); sem_init (& sem_stop, 0, 0);
} }
Communicable :: ~ Communicable () { Communicable :: ~ Communicable ()
{
} }
COMM_ID Communicable :: getKey () { COMM_ID Communicable :: getKey ()
{
return key; return key;
} }
Communicable * getCommunicable (COMM_ID __key) { Communicable * getCommunicable (COMM_ID __key)
{
assert (__key < key_to_comm.size ()); assert (__key < key_to_comm.size ());
return key_to_comm [__key]; return key_to_comm [__key];
} }
COMM_ID getKey (const Communicable * __comm) { COMM_ID getKey (const Communicable * __comm)
{
return comm_to_key [__comm]; return comm_to_key [__comm];
} }
void Communicable :: lock () { void Communicable :: lock ()
{
sem_wait (& sem_lock); sem_wait (& sem_lock);
} }
void Communicable :: unlock () { void Communicable :: unlock ()
{
sem_post (& sem_lock); sem_post (& sem_lock);
} }
void Communicable :: stop () { void Communicable :: stop ()
{
sem_wait (& sem_stop); sem_wait (& sem_stop);
} }
void Communicable :: resume () { void Communicable :: resume ()
{
sem_post (& sem_stop); sem_post (& sem_stop);
} }

View file

@ -41,9 +41,10 @@
typedef unsigned COMM_ID; typedef unsigned COMM_ID;
class Communicable { class Communicable
{
public : public :
Communicable (); Communicable ();
@ -57,7 +58,7 @@ public :
void stop (); /* It suspends the current process */ void stop (); /* It suspends the current process */
void resume (); /* It resumes ___________ */ void resume (); /* It resumes ___________ */
protected : protected :
COMM_ID key; COMM_ID key;
@ -66,7 +67,7 @@ protected :
sem_t sem_stop; sem_t sem_stop;
static unsigned num_comm; static unsigned num_comm;
}; };
extern Communicable * getCommunicable (COMM_ID __key); extern Communicable * getCommunicable (COMM_ID __key);

View file

@ -42,9 +42,10 @@
typedef unsigned COOP_ID; typedef unsigned COOP_ID;
class Cooperative : public Communicable { class Cooperative : public Communicable
{
public : public :
Runner * getOwner (); Runner * getOwner ();
@ -58,11 +59,11 @@ public :
virtual void notifySending (); virtual void notifySending ();
private : private :
Runner * owner; Runner * owner;
}; };
extern Cooperative * getCooperative (COOP_ID __key); extern Cooperative * getCooperative (COOP_ID __key);

View file

@ -41,14 +41,16 @@
#include "messaging.h" #include "messaging.h"
template <class EOT> void pack (const eoPop <EOT> & __pop) { template <class EOT> void pack (const eoPop <EOT> & __pop)
{
pack ((unsigned) __pop.size ()); pack ((unsigned) __pop.size ());
for (unsigned i = 0; i < __pop.size (); i ++) for (unsigned i = 0; i < __pop.size (); i ++)
pack (__pop [i]); pack (__pop [i]);
} }
template <class EOT> void unpack (eoPop <EOT> & __pop) { template <class EOT> void unpack (eoPop <EOT> & __pop)
{
unsigned n; unsigned n;

View file

@ -41,7 +41,8 @@
#include "messaging.h" #include "messaging.h"
template <class F, class T> void pack (const eoVector <F, T> & __v) { template <class F, class T> void pack (const eoVector <F, T> & __v)
{
if ( !__v.invalid() ) if ( !__v.invalid() )
@ -57,7 +58,8 @@ template <class F, class T> void pack (const eoVector <F, T> & __v) {
pack (__v [i]); pack (__v [i]);
} }
template <class F, class T> void unpack (eoVector <F, T> & __v) { template <class F, class T> void unpack (eoVector <F, T> & __v)
{
F fit; F fit;
unsigned int vfit; unsigned int vfit;
@ -76,7 +78,8 @@ template <class F, class T> void unpack (eoVector <F, T> & __v) {
unpack (__v [i]); unpack (__v [i]);
} }
template <class F, class T, class V> void pack (const eoVectorParticle <F, T, V> & __v) { template <class F, class T, class V> void pack (const eoVectorParticle <F, T, V> & __v)
{
pack (__v.fitness ()) ; pack (__v.fitness ()) ;
pack (__v.best()); pack (__v.best());
@ -90,7 +93,8 @@ template <class F, class T, class V> void pack (const eoVectorParticle <F, T, V>
pack (__v.velocities[i]); pack (__v.velocities[i]);
} }
template <class F, class T, class V> void unpack (eoVectorParticle <F, T, V> & __v) { template <class F, class T, class V> void unpack (eoVectorParticle <F, T, V> & __v)
{
F fit; F fit;
unpack(fit); unpack(fit);

View file

@ -70,13 +70,15 @@ extern void pack (const unsigned long & __ul, int __nitem = 1);
extern void pack (const char * __str); extern void pack (const char * __str);
/* Pointer */ /* Pointer */
template <class T> void pack (const T * __ptr) { template <class T> void pack (const T * __ptr)
{
pack ((unsigned long) __ptr); pack ((unsigned long) __ptr);
} }
/* Pair */ /* Pair */
template <class U, class V> void pack (const std :: pair <U, V> & __pair) { template <class U, class V> void pack (const std :: pair <U, V> & __pair)
{
pack (__pair.first); pack (__pair.first);
pack (__pair.second); pack (__pair.second);
@ -116,7 +118,8 @@ extern void unpack (unsigned long & __ul, int __nitem = 1);
extern void unpack (char * __str); extern void unpack (char * __str);
/* Pointer */ /* Pointer */
template <class T> void unpack (T * & __ptr) { template <class T> void unpack (T * & __ptr)
{
unsigned long p; unsigned long p;
unpack (p); unpack (p);
@ -124,7 +127,8 @@ template <class T> void unpack (T * & __ptr) {
} }
/* Pair */ /* Pair */
template <class U, class V> void unpack (std :: pair <U, V> & __pair) { template <class U, class V> void unpack (std :: pair <U, V> & __pair)
{
unpack (__pair.first); unpack (__pair.first);
unpack (__pair.second); unpack (__pair.second);

View file

@ -56,7 +56,8 @@ static char host [MAX_BUFF_SIZE];
std :: vector <FILE *> files; std :: vector <FILE *> files;
void setDebugMode (bool __dbg) { void setDebugMode (bool __dbg)
{
debug = __dbg; debug = __dbg;
gethostname (host, MAX_BUFF_SIZE); gethostname (host, MAX_BUFF_SIZE);
@ -64,7 +65,8 @@ void setDebugMode (bool __dbg) {
extern int getNodeRank (); extern int getNodeRank ();
void initDebugging () { void initDebugging ()
{
mkdir (DEBUG_PATH, S_IRWXU); mkdir (DEBUG_PATH, S_IRWXU);
// files.push_back (stdout); // files.push_back (stdout);
@ -73,16 +75,19 @@ void initDebugging () {
files.push_back (fopen (buff, "w")); files.push_back (fopen (buff, "w"));
} }
void endDebugging () { void endDebugging ()
{
for (unsigned i = 0; i < files.size (); i ++) for (unsigned i = 0; i < files.size (); i ++)
if (files [i] != stdout) if (files [i] != stdout)
fclose (files [i]); fclose (files [i]);
} }
void printDebugMessage (const char * __mess) { void printDebugMessage (const char * __mess)
{
if (debug) { if (debug)
{
char buff [MAX_BUFF_SIZE]; char buff [MAX_BUFF_SIZE];
time_t t = time (0); time_t t = time (0);
@ -96,7 +101,8 @@ void printDebugMessage (const char * __mess) {
/* Message */ /* Message */
sprintf (buff, "%s", __mess); sprintf (buff, "%s", __mess);
for (unsigned i = 0; i < files.size (); i ++) { for (unsigned i = 0; i < files.size (); i ++)
{
fputs (buff, files [i]); fputs (buff, files [i]);
fputs ("\n", files [i]); fputs ("\n", files [i]);
fflush (files [i]); fflush (files [i]);

View file

@ -39,7 +39,8 @@
#include "runner.h" #include "runner.h"
#include "rmc.h" #include "rmc.h"
void peo :: finalize () { void peo :: finalize ()
{
printDebugMessage ("waiting for the termination of all threads"); printDebugMessage ("waiting for the termination of all threads");

View file

@ -37,7 +37,8 @@
#ifndef __peo_finalize_h #ifndef __peo_finalize_h
#define __peo_finalize_h #define __peo_finalize_h
namespace peo { namespace peo
{
extern void finalize (); extern void finalize ();
} }

View file

@ -41,13 +41,15 @@
#include "peo_debug.h" #include "peo_debug.h"
#include "rmc.h" #include "rmc.h"
namespace peo { namespace peo
{
int * argc; int * argc;
char * * * argv; char * * * argv;
void init (int & __argc, char * * & __argv) { void init (int & __argc, char * * & __argv)
{
argc = & __argc; argc = & __argc;

View file

@ -37,7 +37,8 @@
#ifndef __peo_init_h #ifndef __peo_init_h
#define __peo_init_h #define __peo_init_h
namespace peo { namespace peo
{
extern int * argc; extern int * argc;

View file

@ -41,7 +41,8 @@
void peo :: loadParameters (int & __argc, char * * & __argv) { void peo :: loadParameters (int & __argc, char * * & __argv)
{
eoParser parser (__argc, __argv); eoParser parser (__argc, __argv);

View file

@ -37,7 +37,8 @@
#ifndef __peo_param_h #ifndef __peo_param_h
#define __peo_param_h #define __peo_param_h
namespace peo { namespace peo
{
extern void loadParameters (int & __argc, char * * & __argv); extern void loadParameters (int & __argc, char * * & __argv);
} }

View file

@ -39,7 +39,8 @@
#include "rmc.h" #include "rmc.h"
#include "runner.h" #include "runner.h"
void peo :: run () { void peo :: run ()
{
startRunners (); startRunners ();

View file

@ -37,7 +37,8 @@
#ifndef __peo_run_h #ifndef __peo_run_h
#define __peo_run_h #define __peo_run_h
namespace peo { namespace peo
{
extern void run (); extern void run ();
} }

View file

@ -40,23 +40,27 @@ static bool the_end = false;
static std :: vector <ReactiveThread *> reac_threads; static std :: vector <ReactiveThread *> reac_threads;
ReactiveThread :: ReactiveThread () { ReactiveThread :: ReactiveThread ()
{
reac_threads.push_back (this); reac_threads.push_back (this);
sem_init (& sem, 0, 0); sem_init (& sem, 0, 0);
} }
void ReactiveThread :: sleep () { void ReactiveThread :: sleep ()
{
sem_wait (& sem); sem_wait (& sem);
} }
void ReactiveThread :: wakeUp () { void ReactiveThread :: wakeUp ()
{
sem_post (& sem); sem_post (& sem);
} }
void stopReactiveThreads () { void stopReactiveThreads ()
{
the_end = true; the_end = true;
for (unsigned i = 0; i < reac_threads.size (); i ++) for (unsigned i = 0; i < reac_threads.size (); i ++)

View file

@ -41,9 +41,10 @@
#include "thread.h" #include "thread.h"
class ReactiveThread : public Thread { class ReactiveThread : public Thread
{
public: public:
/* Ctor */ /* Ctor */
ReactiveThread (); ReactiveThread ();
@ -52,11 +53,11 @@ public:
void wakeUp (); void wakeUp ();
private: private:
sem_t sem; sem_t sem;
}; };
extern void stopReactiveThreads (); extern void stopReactiveThreads ();

View file

@ -38,14 +38,16 @@
void RingTopology :: setNeighbors (Cooperative * __mig, void RingTopology :: setNeighbors (Cooperative * __mig,
std :: vector <Cooperative *> & __from, std :: vector <Cooperative *> & __from,
std :: vector <Cooperative *> & __to) { std :: vector <Cooperative *> & __to)
{
__from.clear () ; __from.clear () ;
__to.clear () ; __to.clear () ;
int len = mig.size () ; int len = mig.size () ;
for (int i = 0 ; i < len ; i ++) for (int i = 0 ; i < len ; i ++)
if (mig [i] == __mig) { if (mig [i] == __mig)
{
__from.push_back (mig [(i - 1 + len) % len]) ; __from.push_back (mig [(i - 1 + len) % len]) ;
__to.push_back (mig [(i + 1) % len]) ; __to.push_back (mig [(i + 1) % len]) ;
break; break;

View file

@ -39,14 +39,15 @@
#include "topology.h" #include "topology.h"
class RingTopology : public Topology { class RingTopology : public Topology
{
public : public :
void setNeighbors (Cooperative * __mig, void setNeighbors (Cooperative * __mig,
std :: vector <Cooperative *> & __from, std :: vector <Cooperative *> & __from,
std :: vector <Cooperative *> & __to); std :: vector <Cooperative *> & __to);
}; };
#endif #endif

View file

@ -49,7 +49,8 @@ static std :: vector <Runner *> the_runners;
static unsigned num_runners = 0; static unsigned num_runners = 0;
Runner :: Runner () { Runner :: Runner ()
{
id = ++ num_runners; id = ++ num_runners;
the_runners.push_back (this); the_runners.push_back (this);
@ -61,29 +62,34 @@ extern int getNodeRank ();
extern int getNumberOfNodes (); extern int getNumberOfNodes ();
void unpackTerminationOfRunner () { void unpackTerminationOfRunner ()
{
RUNNER_ID id; RUNNER_ID id;
unpack (id); unpack (id);
num_act --; num_act --;
printDebugMessage ("I'm noticed of the termination of a runner"); printDebugMessage ("I'm noticed of the termination of a runner");
if (! num_act) { if (! num_act)
{
printDebugMessage ("all the runners have terminated. Now stopping the reactive threads."); printDebugMessage ("all the runners have terminated. Now stopping the reactive threads.");
stopReactiveThreads (); stopReactiveThreads ();
} }
} }
bool atLeastOneActiveRunner () { bool atLeastOneActiveRunner ()
{
return num_act; return num_act;
} }
RUNNER_ID Runner :: getID () { RUNNER_ID Runner :: getID ()
{
return id; return id;
} }
void Runner :: start () { void Runner :: start ()
{
setActive (); setActive ();
sem_post (& sem_start); sem_post (& sem_start);
@ -91,7 +97,8 @@ void Runner :: start () {
terminate (); terminate ();
} }
void Runner :: notifySendingTermination () { void Runner :: notifySendingTermination ()
{
/* /*
char b [1000]; char b [1000];
@ -103,21 +110,25 @@ void Runner :: notifySendingTermination () {
} }
void Runner :: waitStarting () { void Runner :: waitStarting ()
{
sem_wait (& sem_start); sem_wait (& sem_start);
} }
Runner * getRunner (RUNNER_ID __key) { Runner * getRunner (RUNNER_ID __key)
{
return dynamic_cast <Runner *> (getCommunicable (__key)); return dynamic_cast <Runner *> (getCommunicable (__key));
} }
void startRunners () { void startRunners ()
{
/* Runners */ /* Runners */
for (unsigned i = 0; i < the_runners.size (); i ++) for (unsigned i = 0; i < the_runners.size (); i ++)
if (the_runners [i] -> isLocal ()) { if (the_runners [i] -> isLocal ())
{
addThread (the_runners [i], ll_threads); addThread (the_runners [i], ll_threads);
the_runners [i] -> waitStarting (); the_runners [i] -> waitStarting ();
} }
@ -125,7 +136,8 @@ void startRunners () {
} }
void joinRunners () { void joinRunners ()
{
joinThreads (ll_threads); joinThreads (ll_threads);

View file

@ -44,9 +44,10 @@
typedef unsigned RUNNER_ID; typedef unsigned RUNNER_ID;
class Runner : public Communicable, public Thread { class Runner : public Communicable, public Thread
{
public : public :
Runner (); Runner ();
@ -66,12 +67,12 @@ public :
void notifySendingTermination (); void notifySendingTermination ();
private : private :
sem_t sem_start; sem_t sem_start;
unsigned id; unsigned id;
}; };
extern bool atLeastOneActiveRunner (); extern bool atLeastOneActiveRunner ();

View file

@ -36,51 +36,55 @@
#include "service.h" #include "service.h"
void Service :: setOwner (Thread & __owner) { void Service :: setOwner (Thread & __owner)
{
owner = & __owner; owner = & __owner;
} }
Thread * Service :: getOwner () { Thread * Service :: getOwner ()
{
return owner; return owner;
} }
Service * getService (SERVICE_ID __key) { Service * getService (SERVICE_ID __key)
{
return dynamic_cast <Service *> (getCommunicable (__key)); return dynamic_cast <Service *> (getCommunicable (__key));
} }
void Service :: notifySendingData () { void Service :: notifySendingData ()
{
} }
void Service :: notifySendingResourceRequest () { void Service :: notifySendingResourceRequest ()
{
num_sent_rr --; num_sent_rr --;
if (! num_sent_rr) if (! num_sent_rr)
notifySendingAllResourceRequests (); notifySendingAllResourceRequests ();
} }
void Service :: notifySendingAllResourceRequests () { void Service :: notifySendingAllResourceRequests ()
{
} }
void Service :: packData () { void Service :: packData ()
{
} }
void Service :: unpackData () { void Service :: unpackData ()
{
} }
void Service :: execute () { void Service :: execute ()
{
} }
void Service :: packResult () { void Service :: packResult ()
{
} }
void Service :: unpackResult () { void Service :: unpackResult ()
{
} }

View file

@ -42,9 +42,10 @@
typedef unsigned SERVICE_ID; typedef unsigned SERVICE_ID;
class Service : public Communicable { class Service : public Communicable
{
public : public :
void setOwner (Thread & __owner); void setOwner (Thread & __owner);
@ -65,13 +66,13 @@ public :
virtual void notifySendingResourceRequest (); virtual void notifySendingResourceRequest ();
virtual void notifySendingAllResourceRequests (); virtual void notifySendingAllResourceRequests ();
private : private :
Thread * owner; /* Owner thread (i.e. 'uses' that service) */ Thread * owner; /* Owner thread (i.e. 'uses' that service) */
unsigned num_sent_rr; /* Number of RR not really sent (i.e. still in the sending queue)*/ unsigned num_sent_rr; /* Number of RR not really sent (i.e. still in the sending queue)*/
}; };
extern Service * getService (SERVICE_ID __key); extern Service * getService (SERVICE_ID __key);

View file

@ -42,22 +42,26 @@ static std :: vector <Thread *> threads;
unsigned num_act = 0; unsigned num_act = 0;
Thread :: Thread () { Thread :: Thread ()
{
threads.push_back (this); threads.push_back (this);
act = false; act = false;
} }
Thread :: ~ Thread () { Thread :: ~ Thread ()
{
/* Nothing ! */ /* Nothing ! */
} }
extern int getNodeRank (); extern int getNodeRank ();
void Thread :: setActive () { void Thread :: setActive ()
{
if (! act ) { if (! act )
{
act = true; act = true;
num_act ++; num_act ++;
@ -66,9 +70,11 @@ void Thread :: setActive () {
} }
} }
void Thread :: setPassive () { void Thread :: setPassive ()
{
if (act) { if (act)
{
act = false; act = false;
num_act --; num_act --;
@ -78,31 +84,36 @@ void Thread :: setPassive () {
} }
} }
bool atLeastOneActiveThread () { bool atLeastOneActiveThread ()
{
return num_act; return num_act;
} }
unsigned numberOfActiveThreads () { unsigned numberOfActiveThreads ()
{
return num_act; return num_act;
} }
static void * launch (void * __arg) { static void * launch (void * __arg)
{
Thread * thr = (Thread *) __arg; Thread * thr = (Thread *) __arg;
thr -> start (); thr -> start ();
return 0; return 0;
} }
void addThread (Thread * __hl_thread, std :: vector <pthread_t *> & __ll_threads) { void addThread (Thread * __hl_thread, std :: vector <pthread_t *> & __ll_threads)
{
pthread_t * ll_thr = new pthread_t; pthread_t * ll_thr = new pthread_t;
__ll_threads.push_back (ll_thr); __ll_threads.push_back (ll_thr);
pthread_create (ll_thr, 0, launch, __hl_thread); pthread_create (ll_thr, 0, launch, __hl_thread);
} }
void joinThreads (std :: vector <pthread_t *> & __threads) { void joinThreads (std :: vector <pthread_t *> & __threads)
{
for (unsigned i = 0; i < __threads.size (); i ++) for (unsigned i = 0; i < __threads.size (); i ++)
pthread_join (* __threads [i], 0); pthread_join (* __threads [i], 0);

View file

@ -41,9 +41,10 @@
/* A high-level thread */ /* A high-level thread */
class Thread { class Thread
{
public: public:
/* Ctor */ /* Ctor */
Thread (); Thread ();
@ -58,10 +59,10 @@ public:
void setPassive ();/* The current process is not going to perform send operations void setPassive ();/* The current process is not going to perform send operations
(but it may receive messages) */ (but it may receive messages) */
private : private :
bool act; bool act;
}; };
extern void addThread (Thread * __hl_thread, std :: vector <pthread_t *> & __ll_threads); extern void addThread (Thread * __hl_thread, std :: vector <pthread_t *> & __ll_threads);

View file

@ -36,13 +36,15 @@
#include "topology.h" #include "topology.h"
Topology :: ~ Topology () { Topology :: ~ Topology ()
{
/* Nothing ! */ /* Nothing ! */
} }
void Topology :: add (Cooperative & __mig) { void Topology :: add (Cooperative & __mig)
{
mig.push_back (& __mig) ; mig.push_back (& __mig) ;
} }

View file

@ -41,9 +41,10 @@
#include "cooperative.h" #include "cooperative.h"
class Topology { class Topology
{
public: public:
virtual ~Topology (); virtual ~Topology ();
@ -53,9 +54,9 @@ public:
std :: vector <Cooperative *> & __from, std :: vector <Cooperative *> & __from,
std :: vector <Cooperative *> & __to) = 0; std :: vector <Cooperative *> & __to) = 0;
protected: protected:
std :: vector <Cooperative *> mig ; std :: vector <Cooperative *> mig ;
}; };
#endif #endif

View file

@ -50,9 +50,8 @@
//! </table> //! </table>
//! //!
//! The aggregation object is called in an iterative manner for each of the results obtained by applying partial evaluation functions. //! The aggregation object is called in an iterative manner for each of the results obtained by applying partial evaluation functions.
template< class EOT > class peoAggEvalFunc : public eoBF< EOT&, const typename EOT :: Fitness&, void > { template< class EOT > class peoAggEvalFunc : public eoBF< EOT&, const typename EOT :: Fitness&, void >
{};
};
#endif #endif

View file

@ -137,9 +137,10 @@
//! islands requires the reiteration of the steps 2 through 4 for creating distinct algorithms, with distinct populations and //! islands requires the reiteration of the steps 2 through 4 for creating distinct algorithms, with distinct populations and
//! the associated distinctly parametrized migration objects. The interconnecting element is the underlying topology, defined at step 1 //! the associated distinctly parametrized migration objects. The interconnecting element is the underlying topology, defined at step 1
//! (the same C++ migTopology object has to be passed as parameter for all the migration objects, in order to interconnect them). //! (the same C++ migTopology object has to be passed as parameter for all the migration objects, in order to interconnect them).
template< class EOT > class peoAsyncIslandMig : public Cooperative, public eoUpdater { template< class EOT > class peoAsyncIslandMig : public Cooperative, public eoUpdater
{
public: public:
//! Constructor for the peoAsyncIslandMig class; the characteristics of the migration model are defined //! Constructor for the peoAsyncIslandMig class; the characteristics of the migration model are defined
//! through the specified parameters - out of the box objects provided in EO, etc., or custom, derived objects may be passed as parameters. //! through the specified parameters - out of the box objects provided in EO, etc., or custom, derived objects may be passed as parameters.
@ -171,13 +172,13 @@ public:
void unpack(); void unpack();
private: private:
void emigrate(); void emigrate();
void immigrate(); void immigrate();
private: private:
eoContinue< EOT >& cont; // continuator eoContinue< EOT >& cont; // continuator
eoSelect< EOT >& select; // the selection strategy eoSelect< EOT >& select; // the selection strategy
@ -193,7 +194,7 @@ private:
std :: queue< eoPop< EOT > > em; std :: queue< eoPop< EOT > > em;
std :: queue< Cooperative* > coop_em; std :: queue< Cooperative* > coop_em;
}; };
template< class EOT > peoAsyncIslandMig< EOT > :: peoAsyncIslandMig( template< class EOT > peoAsyncIslandMig< EOT > :: peoAsyncIslandMig(
@ -205,7 +206,7 @@ template< class EOT > peoAsyncIslandMig< EOT > :: peoAsyncIslandMig(
eoPop< EOT >& __source, eoPop< EOT >& __source,
eoPop< EOT >& __destination eoPop< EOT >& __destination
) : cont( __cont ), select( __select ), replace( __replace ), topology( __topology ), source( __source ), destination( __destination ) ) : cont( __cont ), select( __select ), replace( __replace ), topology( __topology ), source( __source ), destination( __destination )
{ {
__topology.add( *this ); __topology.add( *this );
@ -215,7 +216,8 @@ template< class EOT > peoAsyncIslandMig< EOT > :: peoAsyncIslandMig(
template< class EOT > void peoAsyncIslandMig< EOT > :: pack() template< class EOT > void peoAsyncIslandMig< EOT > :: pack()
{ {
lock(); { lock ();
{
:: pack( coop_em.front()->getKey() ); :: pack( coop_em.front()->getKey() );
:: pack( em.front() ); :: pack( em.front() );
@ -229,7 +231,8 @@ template< class EOT > void peoAsyncIslandMig< EOT > :: pack()
template< class EOT > void peoAsyncIslandMig< EOT > :: unpack() template< class EOT > void peoAsyncIslandMig< EOT > :: unpack()
{ {
lock(); { lock ();
{
eoPop< EOT > mig; eoPop< EOT > mig;
:: unpack( mig ); :: unpack( mig );
@ -245,7 +248,8 @@ template< class EOT > void peoAsyncIslandMig< EOT > :: emigrate()
std :: vector< Cooperative* >in, out; std :: vector< Cooperative* >in, out;
topology.setNeighbors( this, in, out ); topology.setNeighbors( this, in, out );
for ( unsigned i = 0; i < out.size(); i++ ) { for ( unsigned i = 0; i < out.size(); i++ )
{
eoPop< EOT > mig; eoPop< EOT > mig;
select( source, mig ); select( source, mig );
@ -260,9 +264,11 @@ template< class EOT > void peoAsyncIslandMig< EOT > :: emigrate()
template< class EOT > void peoAsyncIslandMig< EOT > :: immigrate() template< class EOT > void peoAsyncIslandMig< EOT > :: immigrate()
{ {
lock(); { lock ();
{
while ( !imm.empty() ) { while ( !imm.empty() )
{
replace( destination, imm.front() ); replace( destination, imm.front() );
imm.pop(); imm.pop();
@ -273,9 +279,11 @@ template< class EOT > void peoAsyncIslandMig< EOT > :: immigrate()
} }
template< class EOT > void peoAsyncIslandMig< EOT > :: operator()() { template< class EOT > void peoAsyncIslandMig< EOT > :: operator()()
{
if ( !cont( source ) ) { if ( !cont( source ) )
{
emigrate(); // sending emigrants emigrate(); // sending emigrants
immigrate(); // receiving immigrants immigrate(); // receiving immigrants

View file

@ -79,9 +79,10 @@
//! <tr><td>eaAlg( population ); &nbsp;</td> <td>// specifying the initial population for the algorithm </td></tr> //! <tr><td>eaAlg( population ); &nbsp;</td> <td>// specifying the initial population for the algorithm </td></tr>
//! <tr><td>... &nbsp;</td> <td> &nbsp; </td></tr> //! <tr><td>... &nbsp;</td> <td> &nbsp; </td></tr>
//! </table> //! </table>
template < class EOT > class peoEA : public Runner { template < class EOT > class peoEA : public Runner
{
public: public:
//! Constructor for the evolutionary algorithm object - several basic parameters have to be specified, //! Constructor for the evolutionary algorithm object - several basic parameters have to be specified,
//! allowing for different levels of parallelism. Depending on the requirements, a sequential or a parallel //! allowing for different levels of parallelism. Depending on the requirements, a sequential or a parallel
@ -111,7 +112,7 @@ public:
//! @param eoPop< EOT >& __pop - initial population of the algorithm, to be iteratively evolved; //! @param eoPop< EOT >& __pop - initial population of the algorithm, to be iteratively evolved;
void operator()( eoPop< EOT >& __pop ); void operator()( eoPop< EOT >& __pop );
private: private:
eoContinue< EOT >& cont; eoContinue< EOT >& cont;
@ -120,7 +121,7 @@ private:
peoTransform< EOT >& trans; peoTransform< EOT >& trans;
eoReplacement< EOT >& replace; eoReplacement< EOT >& replace;
eoPop< EOT >* pop; eoPop< EOT >* pop;
}; };
template < class EOT > peoEA< EOT > :: peoEA( template < class EOT > peoEA< EOT > :: peoEA(
@ -131,7 +132,7 @@ template < class EOT > peoEA< EOT > :: peoEA(
peoTransform< EOT >& __trans, peoTransform< EOT >& __trans,
eoReplacement< EOT >& __replace eoReplacement< EOT >& __replace
) : cont( __cont ), pop_eval( __pop_eval ), select( __select ), trans( __trans ), replace( __replace ) ) : cont( __cont ), pop_eval( __pop_eval ), select( __select ), trans( __trans ), replace( __replace )
{ {
trans.setOwner( *this ); trans.setOwner( *this );
@ -139,18 +140,21 @@ template < class EOT > peoEA< EOT > :: peoEA(
} }
template< class EOT > void peoEA< EOT > :: operator ()( eoPop< EOT >& __pop ) { template< class EOT > void peoEA< EOT > :: operator ()( eoPop< EOT >& __pop )
{
pop = &__pop; pop = &__pop;
} }
template< class EOT > void peoEA< EOT > :: run() { template< class EOT > void peoEA< EOT > :: run()
{
printDebugMessage( "performing the first evaluation of the population." ); printDebugMessage( "performing the first evaluation of the population." );
pop_eval( *pop ); pop_eval( *pop );
do { do
{
eoPop< EOT > off; eoPop< EOT > off;
@ -167,7 +171,8 @@ template< class EOT > void peoEA< EOT > :: run() {
printDebugMessage( "deciding of the continuation." ); printDebugMessage( "deciding of the continuation." );
} while ( cont( *pop ) ); }
while ( cont( *pop ) );
} }

View file

@ -42,19 +42,21 @@ template< class EOT, class FitT = EOT::Fitness, class FunctionArg = const EOT& >
#else #else
template< class EOT, class FitT = typename EOT::Fitness, class FunctionArg = const EOT& > template< class EOT, class FitT = typename EOT::Fitness, class FunctionArg = const EOT& >
#endif #endif
struct peoEvalFunc: public eoEvalFunc<EOT> { struct peoEvalFunc: public eoEvalFunc<EOT>
{
peoEvalFunc( FitT (* _eval)( FunctionArg ) ) peoEvalFunc( FitT (* _eval)( FunctionArg ) )
: eoEvalFunc<EOT>(), evalFunc( _eval ) {}; : eoEvalFunc<EOT>(), evalFunc( _eval )
{};
virtual void operator() ( EOT & _peo ) virtual void operator() ( EOT & _peo )
{ {
_peo.fitness((*evalFunc)( _peo )); _peo.fitness((*evalFunc)( _peo ));
}; };
private: private:
FitT (* evalFunc )( FunctionArg ); FitT (* evalFunc )( FunctionArg );
}; };
#endif #endif

View file

@ -49,10 +49,12 @@ template< class POT, class FitT = POT::Fitness, class FunctionArg = const POT& >
#else #else
template< class POT, class FitT = typename POT::Fitness, class FunctionArg = const POT& > template< class POT, class FitT = typename POT::Fitness, class FunctionArg = const POT& >
#endif #endif
struct peoEvalFuncPSO: public eoEvalFunc<POT> { struct peoEvalFuncPSO: public eoEvalFunc<POT>
{
peoEvalFuncPSO( FitT (* _eval)( FunctionArg ) ) peoEvalFuncPSO( FitT (* _eval)( FunctionArg ) )
: eoEvalFunc<POT>(), evalFunc( _eval ) {}; : eoEvalFunc<POT>(), evalFunc( _eval )
{};
//!Applies the evaluation function to a PEO //!Applies the evaluation function to a PEO
virtual void operator() ( POT & _peo ) virtual void operator() ( POT & _peo )
@ -60,9 +62,9 @@ struct peoEvalFuncPSO: public eoEvalFunc<POT> {
_peo.fitness((*evalFunc)( _peo )); _peo.fitness((*evalFunc)( _peo ));
}; };
private: private:
FitT (* evalFunc )( FunctionArg ); FitT (* evalFunc )( FunctionArg );
}; };
#endif #endif

View file

@ -44,7 +44,7 @@
*/ */
template <class POT> class peoInitializer : public eoInitializerBase <POT> template <class POT> class peoInitializer : public eoInitializerBase <POT>
{ {
public: public:
@ -91,7 +91,7 @@ template <class POT> class peoInitializer : public eoInitializerBase <POT>
eoVelocityInit < POT > & initVelo; eoVelocityInit < POT > & initVelo;
eoParticleBestInit <POT> & initBest; eoParticleBestInit <POT> & initBest;
eoPop <POT> * pop; eoPop <POT> * pop;
}; };
#endif #endif

View file

@ -44,16 +44,18 @@
//! The peoNoAggEvalFunc class does nothing more than an association between a fitness value and a specified individual. //! The peoNoAggEvalFunc class does nothing more than an association between a fitness value and a specified individual.
//! The class is provided as a mean of declaring that no aggregation is required for the evaluation function - the fitness //! The class is provided as a mean of declaring that no aggregation is required for the evaluation function - the fitness
//! value is explicitly specified. //! value is explicitly specified.
template< class EOT > class peoNoAggEvalFunc : public peoAggEvalFunc< EOT > { template< class EOT > class peoNoAggEvalFunc : public peoAggEvalFunc< EOT >
{
public : public :
//! Operator which sets as fitness the <b>__fit</b> value for the <b>__sol</b> individual //! Operator which sets as fitness the <b>__fit</b> value for the <b>__sol</b> individual
void operator()( EOT& __sol, const typename EOT :: Fitness& __fit ); void operator()( EOT& __sol, const typename EOT :: Fitness& __fit );
}; };
template< class EOT > void peoNoAggEvalFunc< EOT > :: operator()( EOT& __sol, const typename EOT :: Fitness& __fit ) { template< class EOT > void peoNoAggEvalFunc< EOT > :: operator()( EOT& __sol, const typename EOT :: Fitness& __fit )
{
__sol.fitness( __fit ); __sol.fitness( __fit );
} }

View file

@ -52,9 +52,10 @@
//! with the algorithms provided by the EO framework, the peoPSO class has the underlying necessary structure //! with the algorithms provided by the EO framework, the peoPSO class has the underlying necessary structure
//! for including, for example, parallel evaluation, etc. //! for including, for example, parallel evaluation, etc.
template < class POT > class peoPSO : public Runner { template < class POT > class peoPSO : public Runner
{
public: public:
//! Constructor for the Particle Swarm Optimization //! Constructor for the Particle Swarm Optimization
@ -76,7 +77,7 @@ public:
//! Function operator for specifying the population to be associated with the algorithm. //! Function operator for specifying the population to be associated with the algorithm.
void operator()( eoPop< POT >& __pop ); void operator()( eoPop< POT >& __pop );
private: private:
eoInitializerBase <POT> & Init; eoInitializerBase <POT> & Init;
eoContinue< POT >& cont; eoContinue< POT >& cont;
@ -84,7 +85,7 @@ private:
eoPop< POT >* pop; eoPop< POT >* pop;
eoVelocity < POT > &velocity; eoVelocity < POT > &velocity;
eoFlight < POT > &flight; eoFlight < POT > &flight;
}; };
template < class POT > peoPSO< POT > :: peoPSO( template < class POT > peoPSO< POT > :: peoPSO(
@ -93,24 +94,27 @@ template < class POT > peoPSO< POT > :: peoPSO(
peoPopEval< POT >& __pop_eval, peoPopEval< POT >& __pop_eval,
eoVelocity < POT > &__velocity, eoVelocity < POT > &__velocity,
eoFlight < POT > &__flight eoFlight < POT > &__flight
) : Init(_Init),cont( __cont ), pop_eval(__pop_eval ),velocity( __velocity),flight( __flight) ) : Init(_Init),cont( __cont ), pop_eval(__pop_eval ),velocity( __velocity),flight( __flight)
{ {
pop_eval.setOwner( *this ); pop_eval.setOwner( *this );
} }
template< class POT > void peoPSO< POT > :: operator ()( eoPop< POT >& __pop ) { template< class POT > void peoPSO< POT > :: operator ()( eoPop< POT >& __pop )
{
pop = &__pop; pop = &__pop;
} }
template< class POT > void peoPSO< POT > :: run() { template< class POT > void peoPSO< POT > :: run()
{
printDebugMessage( "Performing the first evaluation of the population." ); printDebugMessage( "Performing the first evaluation of the population." );
Init(); Init();
velocity.getTopology().setup(*pop); velocity.getTopology().setup(*pop);
do { do
{
printDebugMessage( "Performing the velocity evaluation." ); printDebugMessage( "Performing the velocity evaluation." );
velocity.apply ( *pop ); velocity.apply ( *pop );
printDebugMessage( "Performing the flight." ); printDebugMessage( "Performing the flight." );
@ -118,7 +122,8 @@ template< class POT > void peoPSO< POT > :: run() {
printDebugMessage( "Performing the evaluation." ); printDebugMessage( "Performing the evaluation." );
pop_eval(*pop); pop_eval(*pop);
velocity.updateNeighborhood( *pop ); velocity.updateNeighborhood( *pop );
} while ( cont( *pop ) ); }
while ( cont( *pop ) );
} }

View file

@ -47,27 +47,28 @@
template <class POT> template <class POT>
class peoPSOReplacement : public eoReplacement<POT> class peoPSOReplacement : public eoReplacement<POT>
{ {
public: public:
peoPSOReplacement(){} peoPSOReplacement()
{}
void operator()(eoPop<POT>& _dest, eoPop<POT>& _source) void operator()(eoPop<POT>& _dest, eoPop<POT>& _source)
{ {
unsigned ind=0; unsigned ind=0;
double best=_dest[0].best(); double best=_dest[0].best();
for(unsigned j=1;j<_dest.size();j++) for (unsigned j=1;j<_dest.size();j++)
if(_dest[j].best() < best) if (_dest[j].best() < best)
{ {
ind=j; ind=j;
best=_dest[j].best(); best=_dest[j].best();
} }
if(_dest[ind].best() < _source[0].best()) if (_dest[ind].best() < _source[0].best())
{ {
_dest[ind].best(_source[0].best()); _dest[ind].best(_source[0].best());
for(unsigned j=0;j<_dest[ind].size();j++) for (unsigned j=0;j<_dest[ind].size();j++)
_dest[ind].bestPositions[j]=_source[0].bestPositions[j]; _dest[ind].bestPositions[j]=_source[0].bestPositions[j];
} }
} }
}; };
#endif #endif

View file

@ -40,10 +40,11 @@
#include <eoSelectOne.h> #include <eoSelectOne.h>
template <class POT> class peoPSOSelect: public eoSelectOne<POT> template <class POT> class peoPSOSelect: public eoSelectOne<POT>
{ {
public: public:
peoPSOSelect(eoTopology < POT > & _topology):topology(_topology){} peoPSOSelect(eoTopology < POT > & _topology):topology(_topology)
{}
typedef typename PO < POT >::Fitness Fitness; typedef typename PO < POT >::Fitness Fitness;
@ -54,7 +55,7 @@ template <class POT> class peoPSOSelect: public eoSelectOne<POT>
private: private:
eoTopology < POT > & topology; eoTopology < POT > & topology;
}; };
#endif #endif

View file

@ -48,7 +48,7 @@
template <class POT> template <class POT>
class peoPSOVelocity : public eoReplacement<POT> class peoPSOVelocity : public eoReplacement<POT>
{ {
public: public:
typedef typename POT::ParticleVelocityType VelocityType; typedef typename POT::ParticleVelocityType VelocityType;
@ -56,15 +56,16 @@ class peoPSOVelocity : public eoReplacement<POT>
peoPSOVelocity( const double & _c3, peoPSOVelocity( const double & _c3,
eoVelocity < POT > &_velocity): eoVelocity < POT > &_velocity):
c3 (_c3), c3 (_c3),
velocity (_velocity){} velocity (_velocity)
{}
void operator()(eoPop<POT>& _dest, eoPop<POT>& _source) void operator()(eoPop<POT>& _dest, eoPop<POT>& _source)
{ {
VelocityType newVelocity,r3; VelocityType newVelocity,r3;
r3 = (VelocityType) rng.uniform (1) * c3; r3 = (VelocityType) rng.uniform (1) * c3;
for(unsigned i=0;i<_dest.size();i++) for (unsigned i=0;i<_dest.size();i++)
for(unsigned j=0;j<_dest[i].size();j++) for (unsigned j=0;j<_dest[i].size();j++)
{ {
newVelocity= _dest[i].velocities[j] + r3 * (_source[0].bestPositions[j] - _dest[i][j]); newVelocity= _dest[i].velocities[j] + r3 * (_source[0].bestPositions[j] - _dest[i][j]);
_dest[i].velocities[j]=newVelocity; _dest[i].velocities[j]=newVelocity;
@ -75,6 +76,6 @@ class peoPSOVelocity : public eoReplacement<POT>
protected: protected:
const double & c3; const double & c3;
eoVelocity < POT > & velocity; eoVelocity < POT > & velocity;
}; };
#endif #endif

View file

@ -51,9 +51,10 @@
//! The peoParaPopEval represents a wrapper for creating a functor capable of applying in parallel //! The peoParaPopEval represents a wrapper for creating a functor capable of applying in parallel
//! an EO-derived evaluation functor. The class offers the possibility of chosing between a single-function evaluation //! an EO-derived evaluation functor. The class offers the possibility of chosing between a single-function evaluation
//! and an aggregate evaluation function, including several sub-evalution functions. //! and an aggregate evaluation function, including several sub-evalution functions.
template< class EOT > class peoParaPopEval : public peoPopEval< EOT > { template< class EOT > class peoParaPopEval : public peoPopEval< EOT >
{
public: public:
using peoPopEval< EOT > :: requestResourceRequest; using peoPopEval< EOT > :: requestResourceRequest;
using peoPopEval< EOT > :: resume; using peoPopEval< EOT > :: resume;
@ -104,7 +105,7 @@ public:
//! performs the actual evaluation phase. There is no need to explicitly call the function. //! performs the actual evaluation phase. There is no need to explicitly call the function.
void notifySendingAllResourceRequests(); void notifySendingAllResourceRequests();
private: private:
const std :: vector< eoEvalFunc < EOT >* >& funcs; const std :: vector< eoEvalFunc < EOT >* >& funcs;
@ -124,7 +125,7 @@ private:
EOT *ad_sol; EOT *ad_sol;
unsigned total; unsigned total;
}; };
template< class EOT > peoParaPopEval< EOT > :: peoParaPopEval( eoEvalFunc< EOT >& __eval_func ) : template< class EOT > peoParaPopEval< EOT > :: peoParaPopEval( eoEvalFunc< EOT >& __eval_func ) :
@ -141,18 +142,19 @@ template< class EOT > peoParaPopEval< EOT > :: peoParaPopEval(
const std :: vector< eoEvalFunc< EOT >* >& __funcs, const std :: vector< eoEvalFunc< EOT >* >& __funcs,
peoAggEvalFunc< EOT >& __merge_eval peoAggEvalFunc< EOT >& __merge_eval
) : funcs( __funcs ), merge_eval( __merge_eval ) ) : funcs( __funcs ), merge_eval( __merge_eval )
{}
template< class EOT > void peoParaPopEval< EOT >::operator()( eoPop< EOT >& __pop )
{ {
for ( unsigned i = 0; i < __pop.size(); i++ )
} {
template< class EOT > void peoParaPopEval< EOT >::operator()( eoPop< EOT >& __pop ) {
for ( unsigned i = 0; i < __pop.size(); i++ ) {
__pop[ i ].fitness(typename EOT :: Fitness() ); __pop[ i ].fitness(typename EOT :: Fitness() );
progression[ &__pop[ i ] ].first = funcs.size() - 1; progression[ &__pop[ i ] ].first = funcs.size() - 1;
progression[ &__pop[ i ] ].second = funcs.size(); progression[ &__pop[ i ] ].second = funcs.size();
for ( unsigned j = 0; j < funcs.size(); j++ ) { for ( unsigned j = 0; j < funcs.size(); j++ )
{
/* Queuing the 'invalid' solution and its associated owner */ /* Queuing the 'invalid' solution and its associated owner */
tasks.push( &__pop[ i ] ); tasks.push( &__pop[ i ] );
} }
@ -163,7 +165,8 @@ template< class EOT > void peoParaPopEval< EOT >::operator()( eoPop< EOT >& __po
} }
template< class EOT > void peoParaPopEval< EOT > :: packData() { template< class EOT > void peoParaPopEval< EOT > :: packData()
{
// printDebugMessage ("debut pakc data"); // printDebugMessage ("debut pakc data");
pack( progression[ tasks.front() ].first-- ); pack( progression[ tasks.front() ].first-- );
@ -176,7 +179,8 @@ template< class EOT > void peoParaPopEval< EOT > :: packData() {
} }
template< class EOT > void peoParaPopEval< EOT > :: unpackData() { template< class EOT > void peoParaPopEval< EOT > :: unpackData()
{
unpack( num_func ); unpack( num_func );
/* Unpacking the solution */ /* Unpacking the solution */
unpack( sol ); unpack( sol );
@ -185,13 +189,15 @@ template< class EOT > void peoParaPopEval< EOT > :: unpackData() {
} }
template< class EOT > void peoParaPopEval< EOT > :: execute() { template< class EOT > void peoParaPopEval< EOT > :: execute()
{
/* Computing the fitness of the solution */ /* Computing the fitness of the solution */
funcs[ num_func ]->operator()( sol ); funcs[ num_func ]->operator()( sol );
} }
template< class EOT > void peoParaPopEval< EOT > :: packResult() { template< class EOT > void peoParaPopEval< EOT > :: packResult()
{
/* Packing the fitness of the solution */ /* Packing the fitness of the solution */
pack( sol.fitness() ); pack( sol.fitness() );
/* Packing the @ of the individual */ /* Packing the @ of the individual */
@ -199,7 +205,8 @@ template< class EOT > void peoParaPopEval< EOT > :: packResult() {
} }
template< class EOT > void peoParaPopEval< EOT > :: unpackResult() { template< class EOT > void peoParaPopEval< EOT > :: unpackResult()
{
typename EOT :: Fitness fit; typename EOT :: Fitness fit;
/* Unpacking the computed fitness */ /* Unpacking the computed fitness */
@ -215,13 +222,15 @@ template< class EOT > void peoParaPopEval< EOT > :: unpackResult() {
progression[ ad_sol ].second--; progression[ ad_sol ].second--;
/* Notifying the container of the termination of the evaluation */ /* Notifying the container of the termination of the evaluation */
if ( !progression[ ad_sol ].second ) { if ( !progression[ ad_sol ].second )
{
progression.erase( ad_sol ); progression.erase( ad_sol );
} }
total--; total--;
if ( !total ) { if ( !total )
{
getOwner()->setActive(); getOwner()->setActive();
resume(); resume();
@ -229,11 +238,12 @@ template< class EOT > void peoParaPopEval< EOT > :: unpackResult() {
} }
template< class EOT > void peoParaPopEval< EOT > :: notifySendingData() { template< class EOT > void peoParaPopEval< EOT > :: notifySendingData()
} {}
template< class EOT > void peoParaPopEval< EOT > :: notifySendingAllResourceRequests() { template< class EOT > void peoParaPopEval< EOT > :: notifySendingAllResourceRequests()
{
getOwner()->setPassive(); getOwner()->setPassive();
} }

View file

@ -46,9 +46,10 @@
extern int getNodeRank(); extern int getNodeRank();
template< class EOT > class peoParaSGATransform : public peoTransform< EOT > { template< class EOT > class peoParaSGATransform : public peoTransform< EOT >
{
public: public:
using peoTransform< EOT > :: requestResourceRequest; using peoTransform< EOT > :: requestResourceRequest;
using peoTransform< EOT > :: resume; using peoTransform< EOT > :: resume;
@ -78,7 +79,7 @@ public:
void notifySendingData(); void notifySendingData();
void notifySendingAllResourceRequests(); void notifySendingAllResourceRequests();
private: private:
eoQuadOp< EOT >& cross; eoQuadOp< EOT >& cross;
double cross_rate; double cross_rate;
@ -93,7 +94,7 @@ private:
EOT father, mother; EOT father, mother;
unsigned num_term; unsigned num_term;
}; };
template< class EOT > peoParaSGATransform< EOT > :: peoParaSGATransform( template< class EOT > peoParaSGATransform< EOT > :: peoParaSGATransform(
@ -102,21 +103,21 @@ template< class EOT > peoParaSGATransform< EOT > :: peoParaSGATransform(
eoMonOp < EOT >& __mut, eoMonOp < EOT >& __mut,
double __mut_rate double __mut_rate
) : cross( __cross ), cross_rate( __cross_rate ), mut( __mut ), mut_rate( __mut_rate ) ) : cross( __cross ), cross_rate( __cross_rate ), mut( __mut ), mut_rate( __mut_rate )
{}
template< class EOT > void peoParaSGATransform< EOT > :: packData()
{ {
}
template< class EOT > void peoParaSGATransform< EOT > :: packData() {
pack( idx ); pack( idx );
:: pack( pop->operator[]( idx++ ) ); :: pack( pop->operator[]( idx++ ) );
:: pack( pop->operator[]( idx++ ) ); :: pack( pop->operator[]( idx++ ) );
} }
template< class EOT > void peoParaSGATransform< EOT > :: unpackData() { template< class EOT > void peoParaSGATransform< EOT > :: unpackData()
{
unpack( idx ); unpack( idx );
:: unpack( father ); :: unpack( father );
@ -124,16 +125,18 @@ template< class EOT > void peoParaSGATransform< EOT > :: unpackData() {
} }
template< class EOT > void peoParaSGATransform< EOT > :: execute() { template< class EOT > void peoParaSGATransform< EOT > :: execute()
{
if( rng.uniform() < cross_rate ) cross( mother, father ); if ( rng.uniform() < cross_rate ) cross( mother, father );
if( rng.uniform() < mut_rate ) mut( mother ); if ( rng.uniform() < mut_rate ) mut( mother );
if( rng.uniform() < mut_rate ) mut( father ); if ( rng.uniform() < mut_rate ) mut( father );
} }
template< class EOT > void peoParaSGATransform< EOT > :: packResult() { template< class EOT > void peoParaSGATransform< EOT > :: packResult()
{
pack( idx ); pack( idx );
:: pack( father ); :: pack( father );
@ -141,7 +144,8 @@ template< class EOT > void peoParaSGATransform< EOT > :: packResult() {
} }
template< class EOT > void peoParaSGATransform< EOT > :: unpackResult() { template< class EOT > void peoParaSGATransform< EOT > :: unpackResult()
{
unsigned sidx; unsigned sidx;
@ -150,7 +154,8 @@ template< class EOT > void peoParaSGATransform< EOT > :: unpackResult() {
:: unpack( pop->operator[]( sidx ) ); :: unpack( pop->operator[]( sidx ) );
num_term += 2; num_term += 2;
// Can be used with a odd size // Can be used with a odd size
if( num_term == 2*(pop->size()/2) ) { if ( num_term == 2*(pop->size()/2) )
{
getOwner()->setActive(); getOwner()->setActive();
resume(); resume();
@ -158,7 +163,8 @@ template< class EOT > void peoParaSGATransform< EOT > :: unpackResult() {
} }
template< class EOT > void peoParaSGATransform< EOT > :: operator()( eoPop < EOT >& __pop ) { template< class EOT > void peoParaSGATransform< EOT > :: operator()( eoPop < EOT >& __pop )
{
printDebugMessage( "performing the parallel transformation step." ); printDebugMessage( "performing the parallel transformation step." );
pop = &__pop; pop = &__pop;
@ -169,12 +175,12 @@ template< class EOT > void peoParaSGATransform< EOT > :: operator()( eoPop < EOT
} }
template< class EOT > void peoParaSGATransform< EOT > :: notifySendingData() { template< class EOT > void peoParaSGATransform< EOT > :: notifySendingData()
{}
}
template< class EOT > void peoParaSGATransform< EOT > :: notifySendingAllResourceRequests() { template< class EOT > void peoParaSGATransform< EOT > :: notifySendingAllResourceRequests()
{
getOwner()->setPassive(); getOwner()->setPassive();
} }

View file

@ -44,70 +44,82 @@
class peoParallelAlgorithmWrapper : public Runner { class peoParallelAlgorithmWrapper : public Runner
{
public: public:
template< typename AlgorithmType > peoParallelAlgorithmWrapper( AlgorithmType& externalAlgorithm ) template< typename AlgorithmType > peoParallelAlgorithmWrapper( AlgorithmType& externalAlgorithm )
: algorithm( new Algorithm< AlgorithmType, void >( externalAlgorithm ) ) { : algorithm( new Algorithm< AlgorithmType, void >( externalAlgorithm ) )
{}
}
template< typename AlgorithmType, typename AlgorithmDataType > peoParallelAlgorithmWrapper( AlgorithmType& externalAlgorithm, AlgorithmDataType& externalData ) template< typename AlgorithmType, typename AlgorithmDataType > peoParallelAlgorithmWrapper( AlgorithmType& externalAlgorithm, AlgorithmDataType& externalData )
: algorithm( new Algorithm< AlgorithmType, AlgorithmDataType >( externalAlgorithm, externalData ) ) { : algorithm( new Algorithm< AlgorithmType, AlgorithmDataType >( externalAlgorithm, externalData ) )
{}
} ~peoParallelAlgorithmWrapper()
{
~peoParallelAlgorithmWrapper() {
delete algorithm; delete algorithm;
} }
void run() { algorithm->operator()(); } void run()
{
algorithm->operator()();
}
private: private:
struct AbstractAlgorithm { struct AbstractAlgorithm
{
// virtual destructor as we will be using inheritance and polymorphism // virtual destructor as we will be using inheritance and polymorphism
virtual ~AbstractAlgorithm() { } virtual ~AbstractAlgorithm()
{ }
// operator to be called for executing the algorithm // operator to be called for executing the algorithm
virtual void operator()() { } virtual void operator()()
{ }
}; };
template< typename AlgorithmType, typename AlgorithmDataType > struct Algorithm : public AbstractAlgorithm { template< typename AlgorithmType, typename AlgorithmDataType > struct Algorithm : public AbstractAlgorithm
{
Algorithm( AlgorithmType& externalAlgorithm, AlgorithmDataType& externalData ) Algorithm( AlgorithmType& externalAlgorithm, AlgorithmDataType& externalData )
: algorithm( externalAlgorithm ), algorithmData( externalData ) { : algorithm( externalAlgorithm ), algorithmData( externalData )
{}
virtual void operator()()
{
algorithm( algorithmData );
} }
virtual void operator()() { algorithm( algorithmData ); }
AlgorithmType& algorithm; AlgorithmType& algorithm;
AlgorithmDataType& algorithmData; AlgorithmDataType& algorithmData;
}; };
template< typename AlgorithmType > struct Algorithm< AlgorithmType, void > : public AbstractAlgorithm { template< typename AlgorithmType > struct Algorithm< AlgorithmType, void > : public AbstractAlgorithm
{
Algorithm( AlgorithmType& externalAlgorithm ) : algorithm( externalAlgorithm ) { Algorithm( AlgorithmType& externalAlgorithm ) : algorithm( externalAlgorithm )
{}
virtual void operator()()
{
algorithm();
} }
virtual void operator()() { algorithm(); }
AlgorithmType& algorithm; AlgorithmType& algorithm;
}; };
private: private:
AbstractAlgorithm* algorithm; AbstractAlgorithm* algorithm;
}; };
#endif #endif

View file

@ -44,13 +44,14 @@
//! The <b>peoPopEval</b> class provides the interface for constructing ParadisEO specific evaluation functors. //! The <b>peoPopEval</b> class provides the interface for constructing ParadisEO specific evaluation functors.
//! The derived classes may be used as wrappers for <b>EO</b>-derived evaluation functors. In order to have an example, //! The derived classes may be used as wrappers for <b>EO</b>-derived evaluation functors. In order to have an example,
//! please refer to the implementation of the <b>peoSeqPopEval</b> and <b>peoParaPopEval</b> classes. //! please refer to the implementation of the <b>peoSeqPopEval</b> and <b>peoParaPopEval</b> classes.
template< class EOT > class peoPopEval : public Service { template< class EOT > class peoPopEval : public Service
{
public: public:
//! Interface function providing the signature for constructing an evaluation functor. //! Interface function providing the signature for constructing an evaluation functor.
virtual void operator()( eoPop< EOT >& __pop ) = 0; virtual void operator()( eoPop< EOT >& __pop ) = 0;
}; };
#endif #endif

View file

@ -46,9 +46,10 @@
//! The peoSeqPopEval class acts only as a ParadisEO specific sequential evaluation functor - a wrapper for incorporating //! The peoSeqPopEval class acts only as a ParadisEO specific sequential evaluation functor - a wrapper for incorporating
//! an <b>eoEvalFunc< EOT ></b>-derived class as evaluation functor. The specified EO evaluation object is applyied in an //! an <b>eoEvalFunc< EOT ></b>-derived class as evaluation functor. The specified EO evaluation object is applyied in an
//! iterative manner to each individual of a specified population. //! iterative manner to each individual of a specified population.
template< class EOT > class peoSeqPopEval : public peoPopEval< EOT > { template< class EOT > class peoSeqPopEval : public peoPopEval< EOT >
{
public: public:
//! Constructor function - it only sets an internal reference to point to the specified evaluation object. //! Constructor function - it only sets an internal reference to point to the specified evaluation object.
//! //!
@ -60,18 +61,18 @@ public:
//! @param eoPop< EOT >& __pop - population to be evaluated. //! @param eoPop< EOT >& __pop - population to be evaluated.
void operator()( eoPop< EOT >& __pop ); void operator()( eoPop< EOT >& __pop );
private: private:
eoEvalFunc< EOT >& eval; eoEvalFunc< EOT >& eval;
}; };
template< class EOT > peoSeqPopEval< EOT > :: peoSeqPopEval( eoEvalFunc< EOT >& __eval ) : eval( __eval ) { template< class EOT > peoSeqPopEval< EOT > :: peoSeqPopEval( eoEvalFunc< EOT >& __eval ) : eval( __eval )
{}
}
template< class EOT > void peoSeqPopEval< EOT > :: operator()( eoPop< EOT >& __pop ) { template< class EOT > void peoSeqPopEval< EOT > :: operator()( eoPop< EOT >& __pop )
{
for ( unsigned i = 0; i < __pop.size(); i++ ) for ( unsigned i = 0; i < __pop.size(); i++ )
eval( __pop[i] ); eval( __pop[i] );

View file

@ -45,9 +45,10 @@
//! The peoSeqTransform represent a wrapper for offering the possibility of using EO derived transform operators //! The peoSeqTransform represent a wrapper for offering the possibility of using EO derived transform operators
//! along with the ParadisEO evolutionary algorithms. A minimal set of interface functions is also provided for creating the //! along with the ParadisEO evolutionary algorithms. A minimal set of interface functions is also provided for creating the
//! link with the parallel architecture of the ParadisEO framework. //! link with the parallel architecture of the ParadisEO framework.
template< class EOT > class peoSeqTransform : public peoTransform< EOT > { template< class EOT > class peoSeqTransform : public peoTransform< EOT >
{
public: public:
//! Constructor function - sets an internal reference towards the specified EO-derived transform object. //! Constructor function - sets an internal reference towards the specified EO-derived transform object.
//! //!
@ -60,32 +61,37 @@ public:
void operator()( eoPop< EOT >& __pop ); void operator()( eoPop< EOT >& __pop );
//! Interface function for providing a link with the parallel architecture of the ParadisEO framework. //! Interface function for providing a link with the parallel architecture of the ParadisEO framework.
virtual void packData() { } virtual void packData()
{ }
//! Interface function for providing a link with the parallel architecture of the ParadisEO framework. //! Interface function for providing a link with the parallel architecture of the ParadisEO framework.
virtual void unpackData() { } virtual void unpackData()
{ }
//! Interface function for providing a link with the parallel architecture of the ParadisEO framework. //! Interface function for providing a link with the parallel architecture of the ParadisEO framework.
virtual void execute() { } virtual void execute()
{ }
//! Interface function for providing a link with the parallel architecture of the ParadisEO framework. //! Interface function for providing a link with the parallel architecture of the ParadisEO framework.
virtual void packResult() { } virtual void packResult()
{ }
//! Interface function for providing a link with the parallel architecture of the ParadisEO framework. //! Interface function for providing a link with the parallel architecture of the ParadisEO framework.
virtual void unpackResult() { } virtual void unpackResult()
{ }
private: private:
eoTransform< EOT >& trans; eoTransform< EOT >& trans;
}; };
template< class EOT > peoSeqTransform< EOT > :: peoSeqTransform( eoTransform< EOT >& __trans ) : trans( __trans ) { template< class EOT > peoSeqTransform< EOT > :: peoSeqTransform( eoTransform< EOT >& __trans ) : trans( __trans )
{}
}
template< class EOT > void peoSeqTransform< EOT > :: operator()( eoPop< EOT >& __pop ) { template< class EOT > void peoSeqTransform< EOT > :: operator()( eoPop< EOT >& __pop )
{
trans( __pop ); trans( __pop );
} }

View file

@ -139,9 +139,10 @@
//! islands requires the reiteration of the steps 2 through 4 for creating distinct algorithms, with distinct populations and //! islands requires the reiteration of the steps 2 through 4 for creating distinct algorithms, with distinct populations and
//! the associated distinctly parametrized migration objects. The interconnecting element is the underlying topology, defined at step 1 //! the associated distinctly parametrized migration objects. The interconnecting element is the underlying topology, defined at step 1
//! (the same C++ migTopology object has to be passed as parameter for all the migration objects, in order to interconnect them). //! (the same C++ migTopology object has to be passed as parameter for all the migration objects, in order to interconnect them).
template< class EOT > class peoSyncIslandMig : public Cooperative, public eoUpdater { template< class EOT > class peoSyncIslandMig : public Cooperative, public eoUpdater
{
public: public:
//! Constructor for the peoSyncIslandMig class; the characteristics of the migration model are defined //! Constructor for the peoSyncIslandMig class; the characteristics of the migration model are defined
//! through the specified parameters - out of the box objects provided in EO, etc., or custom, derived objects may be passed as parameters. //! through the specified parameters - out of the box objects provided in EO, etc., or custom, derived objects may be passed as parameters.
@ -176,13 +177,13 @@ public:
void notifySending(); void notifySending();
private: private:
void emigrate(); void emigrate();
void immigrate(); void immigrate();
private: private:
eoPeriodicContinue< EOT > cont; eoPeriodicContinue< EOT > cont;
eoSelect< EOT >& select; // selection strategy eoSelect< EOT >& select; // selection strategy
@ -200,7 +201,7 @@ private:
std :: queue< Cooperative* > coop_em; std :: queue< Cooperative* > coop_em;
sem_t sync; sem_t sync;
}; };
template< class EOT > peoSyncIslandMig< EOT > :: peoSyncIslandMig( template< class EOT > peoSyncIslandMig< EOT > :: peoSyncIslandMig(
@ -212,7 +213,7 @@ template< class EOT > peoSyncIslandMig< EOT > :: peoSyncIslandMig(
eoPop< EOT >& __source, eoPop< EOT >& __source,
eoPop< EOT >& __destination eoPop< EOT >& __destination
) : cont( __frequency ), select( __select ), replace( __replace ), topology( __topology ), source( __source ), destination( __destination ) ) : cont( __frequency ), select( __select ), replace( __replace ), topology( __topology ), source( __source ), destination( __destination )
{ {
__topology.add( *this ); __topology.add( *this );
@ -220,9 +221,11 @@ template< class EOT > peoSyncIslandMig< EOT > :: peoSyncIslandMig(
} }
template< class EOT > void peoSyncIslandMig< EOT > :: pack() { template< class EOT > void peoSyncIslandMig< EOT > :: pack()
{
lock(); { lock ();
{
:: pack( coop_em.front()->getKey() ); :: pack( coop_em.front()->getKey() );
:: pack( em.front() ); :: pack( em.front() );
@ -233,9 +236,11 @@ template< class EOT > void peoSyncIslandMig< EOT > :: pack() {
} }
template< class EOT > void peoSyncIslandMig< EOT > :: unpack() { template< class EOT > void peoSyncIslandMig< EOT > :: unpack()
{
lock(); { lock ();
{
eoPop< EOT > mig; eoPop< EOT > mig;
:: unpack( mig ); :: unpack( mig );
@ -247,12 +252,14 @@ template< class EOT > void peoSyncIslandMig< EOT > :: unpack() {
} }
template< class EOT > void peoSyncIslandMig< EOT > :: emigrate() { template< class EOT > void peoSyncIslandMig< EOT > :: emigrate()
{
std :: vector< Cooperative* > in, out; std :: vector< Cooperative* > in, out;
topology.setNeighbors( this, in, out ); topology.setNeighbors( this, in, out );
for ( unsigned i = 0; i < out.size(); i ++ ) { for ( unsigned i = 0; i < out.size(); i ++ )
{
eoPop< EOT > mig; eoPop< EOT > mig;
select( source, mig ); select( source, mig );
@ -264,9 +271,11 @@ template< class EOT > void peoSyncIslandMig< EOT > :: emigrate() {
} }
template< class EOT > void peoSyncIslandMig< EOT > :: immigrate() { template< class EOT > void peoSyncIslandMig< EOT > :: immigrate()
{
lock(); { lock ();
{
assert( imm.size() ); assert( imm.size() );
replace( destination, imm.front() ) ; replace( destination, imm.front() ) ;
@ -277,9 +286,11 @@ template< class EOT > void peoSyncIslandMig< EOT > :: immigrate() {
} }
template< class EOT > void peoSyncIslandMig< EOT > :: operator()() { template< class EOT > void peoSyncIslandMig< EOT > :: operator()()
{
if ( !cont( source ) ) { if ( !cont( source ) )
{
// sending emigrants // sending emigrants
emigrate(); emigrate();
@ -295,11 +306,14 @@ template< class EOT > void peoSyncIslandMig< EOT > :: operator()() {
} }
template< class EOT > void peoSyncIslandMig< EOT > :: notifySending() { template< class EOT > void peoSyncIslandMig< EOT > :: notifySending()
{
lock(); { lock ();
{
if ( imm.empty() ) { if ( imm.empty() )
{
printDebugMessage( "entering pasive mode\n" ); printDebugMessage( "entering pasive mode\n" );
getOwner()->setPassive(); getOwner()->setPassive();

View file

@ -61,9 +61,10 @@ extern int getNodeRank();
//! peoSyncMultiStart object can be specified as checkpoint object for a classic ParadisEO evolutionary algorithm //! peoSyncMultiStart object can be specified as checkpoint object for a classic ParadisEO evolutionary algorithm
//! thus allowing for simple hybridization schemes which combine the evolutionary approach with a local search approach, //! thus allowing for simple hybridization schemes which combine the evolutionary approach with a local search approach,
//! for example, executed at the end of each generation. //! for example, executed at the end of each generation.
template< class EOT > class peoSyncMultiStart : public Service, public eoUpdater { template< class EOT > class peoSyncMultiStart : public Service, public eoUpdater
{
public: public:
//! Constructor function - several simple parameters are required for defining the characteristics of the multi-start model. //! Constructor function - several simple parameters are required for defining the characteristics of the multi-start model.
//! //!
@ -113,7 +114,7 @@ public:
//! and the processes that performs the actual execution phase. There is no need to explicitly call the function. //! and the processes that performs the actual execution phase. There is no need to explicitly call the function.
void notifySendingAllResourceRequests(); void notifySendingAllResourceRequests();
private: private:
eoContinue< EOT >& cont; eoContinue< EOT >& cont;
eoSelect< EOT >& select; eoSelect< EOT >& select;
@ -128,7 +129,7 @@ private:
EOT sol; EOT sol;
unsigned idx; unsigned idx;
unsigned num_term; unsigned num_term;
}; };
template< class EOT > peoSyncMultiStart< EOT > :: peoSyncMultiStart( template< class EOT > peoSyncMultiStart< EOT > :: peoSyncMultiStart(
@ -139,43 +140,47 @@ template< class EOT > peoSyncMultiStart< EOT > :: peoSyncMultiStart(
moAlgo < EOT >& __ls, moAlgo < EOT >& __ls,
eoPop< EOT >& __pop eoPop< EOT >& __pop
) : cont( __cont ), select( __select ), replace( __replace ), ls( __ls ), pop( __pop ) ) : cont( __cont ), select( __select ), replace( __replace ), ls( __ls ), pop( __pop )
{}
template< class EOT > void peoSyncMultiStart< EOT > :: packData()
{ {
}
template< class EOT > void peoSyncMultiStart< EOT > :: packData() {
:: pack( sel[ idx++ ] ); :: pack( sel[ idx++ ] );
} }
template< class EOT > void peoSyncMultiStart< EOT > :: unpackData() { template< class EOT > void peoSyncMultiStart< EOT > :: unpackData()
{
unpack( sol ); unpack( sol );
} }
template< class EOT > void peoSyncMultiStart< EOT > :: execute() { template< class EOT > void peoSyncMultiStart< EOT > :: execute()
{
ls( sol ); ls( sol );
} }
template< class EOT > void peoSyncMultiStart< EOT > :: packResult() { template< class EOT > void peoSyncMultiStart< EOT > :: packResult()
{
pack( sol ); pack( sol );
} }
template< class EOT > void peoSyncMultiStart< EOT > :: unpackResult() { template< class EOT > void peoSyncMultiStart< EOT > :: unpackResult()
{
unpack( sol ); unpack( sol );
impr_sel.push_back( sol ); impr_sel.push_back( sol );
num_term++; num_term++;
if ( num_term == sel.size() ) { if ( num_term == sel.size() )
{
getOwner()->setActive(); getOwner()->setActive();
replace( pop, impr_sel ); replace( pop, impr_sel );
@ -186,7 +191,8 @@ template< class EOT > void peoSyncMultiStart< EOT > :: unpackResult() {
} }
template< class EOT > void peoSyncMultiStart< EOT > :: operator()() { template< class EOT > void peoSyncMultiStart< EOT > :: operator()()
{
printDebugMessage( "performing the parallel multi-start hybridization." ); printDebugMessage( "performing the parallel multi-start hybridization." );
select( pop, sel ); select( pop, sel );
@ -197,12 +203,12 @@ template< class EOT > void peoSyncMultiStart< EOT > :: operator()() {
} }
template< class EOT > void peoSyncMultiStart< EOT > :: notifySendingData() { template< class EOT > void peoSyncMultiStart< EOT > :: notifySendingData()
{}
}
template< class EOT > void peoSyncMultiStart< EOT > :: notifySendingAllResourceRequests() { template< class EOT > void peoSyncMultiStart< EOT > :: notifySendingAllResourceRequests()
{
getOwner()->setPassive(); getOwner()->setPassive();
} }

View file

@ -42,11 +42,13 @@
#include "core/messaging.h" #include "core/messaging.h"
template < typename EntityType > class peoSynchronousMultiStart : public Service { template < typename EntityType > class peoSynchronousMultiStart : public Service
{
public: public:
template < typename AlgorithmType > peoSynchronousMultiStart( AlgorithmType& externalAlgorithm ) { template < typename AlgorithmType > peoSynchronousMultiStart( AlgorithmType& externalAlgorithm )
{
singularAlgorithm = new Algorithm< AlgorithmType >( externalAlgorithm ); singularAlgorithm = new Algorithm< AlgorithmType >( externalAlgorithm );
algorithms.push_back( singularAlgorithm ); algorithms.push_back( singularAlgorithm );
@ -54,9 +56,11 @@ public:
aggregationFunction = new NoAggregationFunction(); aggregationFunction = new NoAggregationFunction();
} }
template < typename AlgorithmType, typename AggregationFunctionType > peoSynchronousMultiStart( std::vector< AlgorithmType* >& externalAlgorithms, AggregationFunctionType& externalAggregationFunction ) { template < typename AlgorithmType, typename AggregationFunctionType > peoSynchronousMultiStart( std::vector< AlgorithmType* >& externalAlgorithms, AggregationFunctionType& externalAggregationFunction )
{
for ( unsigned int index = 0; index < externalAlgorithms; index++ ) { for ( unsigned int index = 0; index < externalAlgorithms; index++ )
{
algorithms.push_back( new Algorithm< AlgorithmType >( *externalAlgorithms[ index ] ) ); algorithms.push_back( new Algorithm< AlgorithmType >( *externalAlgorithms[ index ] ) );
} }
@ -65,7 +69,8 @@ public:
} }
~peoSynchronousMultiStart() { ~peoSynchronousMultiStart()
{
for ( unsigned int index = 0; index < data.size(); index++ ) delete data[ index ]; for ( unsigned int index = 0; index < data.size(); index++ ) delete data[ index ];
for ( unsigned int index = 0; index < algorithms.size(); index++ ) delete algorithms[ index ]; for ( unsigned int index = 0; index < algorithms.size(); index++ ) delete algorithms[ index ];
@ -74,9 +79,11 @@ public:
} }
template < typename Type > void operator()( Type& externalData ) { template < typename Type > void operator()( Type& externalData )
{
for ( typename Type::iterator externalDataIterator = externalData.begin(); externalDataIterator != externalData.end(); externalDataIterator++ ) { for ( typename Type::iterator externalDataIterator = externalData.begin(); externalDataIterator != externalData.end(); externalDataIterator++ )
{
data.push_back( new DataType< EntityType >( *externalDataIterator ) ); data.push_back( new DataType< EntityType >( *externalDataIterator ) );
} }
@ -87,9 +94,11 @@ public:
} }
template < typename Type > void operator()( const Type& externalDataBegin, const Type& externalDataEnd ) { template < typename Type > void operator()( const Type& externalDataBegin, const Type& externalDataEnd )
{
for ( Type externalDataIterator = externalDataBegin; externalDataIterator != externalDataEnd; externalDataIterator++ ) { for ( Type externalDataIterator = externalDataBegin; externalDataIterator != externalDataEnd; externalDataIterator++ )
{
data.push_back( new DataType< EntityType >( *externalDataIterator ) ); data.push_back( new DataType< EntityType >( *externalDataIterator ) );
} }
@ -115,57 +124,76 @@ public:
void notifySendingAllResourceRequests(); void notifySendingAllResourceRequests();
private: private:
template < typename Type > struct DataType; template < typename Type > struct DataType;
struct AbstractDataType { struct AbstractDataType
{
virtual ~AbstractDataType() { } virtual ~AbstractDataType()
{ }
template < typename Type > operator Type& () { template < typename Type > operator Type& ()
{
return ( dynamic_cast< DataType< Type >& >( *this ) ).data; return ( dynamic_cast< DataType< Type >& >( *this ) ).data;
} }
}; };
template < typename Type > struct DataType : public AbstractDataType { template < typename Type > struct DataType : public AbstractDataType
{
DataType( Type& externalData ) : data( externalData ) { } DataType( Type& externalData ) : data( externalData )
{ }
Type& data; Type& data;
}; };
struct AbstractAlgorithm { struct AbstractAlgorithm
{
virtual ~AbstractAlgorithm() { } virtual ~AbstractAlgorithm()
{ }
virtual void operator()( AbstractDataType& dataTypeInstance ) {} virtual void operator()( AbstractDataType& dataTypeInstance )
{}
}; };
template < typename AlgorithmType > struct Algorithm : public AbstractAlgorithm { template < typename AlgorithmType > struct Algorithm : public AbstractAlgorithm
{
Algorithm( AlgorithmType& externalAlgorithm ) : algorithm( externalAlgorithm ) { } Algorithm( AlgorithmType& externalAlgorithm ) : algorithm( externalAlgorithm )
{ }
void operator()( AbstractDataType& dataTypeInstance ) { algorithm( dataTypeInstance ); } void operator()( AbstractDataType& dataTypeInstance )
{
algorithm( dataTypeInstance );
}
AlgorithmType& algorithm; AlgorithmType& algorithm;
}; };
struct AbstractAggregationAlgorithm { struct AbstractAggregationAlgorithm
{
virtual ~AbstractAggregationAlgorithm() { } virtual ~AbstractAggregationAlgorithm()
{ }
virtual void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB ) {}; virtual void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB )
{};
}; };
template < typename AggregationAlgorithmType > struct AggregationAlgorithm : public AbstractAggregationAlgorithm { template < typename AggregationAlgorithmType > struct AggregationAlgorithm : public AbstractAggregationAlgorithm
{
AggregationAlgorithm( AggregationAlgorithmType& externalAggregationAlgorithm ) : aggregationAlgorithm( externalAggregationAlgorithm ) { } AggregationAlgorithm( AggregationAlgorithmType& externalAggregationAlgorithm ) : aggregationAlgorithm( externalAggregationAlgorithm )
{ }
void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB ) { void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB )
{
aggregationAlgorithm( dataTypeInstanceA, dataTypeInstanceB ); aggregationAlgorithm( dataTypeInstanceA, dataTypeInstanceB );
} }
@ -173,9 +201,11 @@ private:
AggregationAlgorithmType& aggregationAlgorithm; AggregationAlgorithmType& aggregationAlgorithm;
}; };
struct NoAggregationFunction : public AbstractAggregationAlgorithm { struct NoAggregationFunction : public AbstractAggregationAlgorithm
{
void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB ) { void operator()( AbstractDataType& dataTypeInstanceA, AbstractDataType& dataTypeInstanceB )
{
static_cast< EntityType& >( dataTypeInstanceA ) = static_cast< EntityType& >( dataTypeInstanceB ); static_cast< EntityType& >( dataTypeInstanceA ) = static_cast< EntityType& >( dataTypeInstanceB );
} }
@ -196,10 +226,11 @@ private:
unsigned num_term; unsigned num_term;
unsigned dataIndex; unsigned dataIndex;
unsigned functionIndex; unsigned functionIndex;
}; };
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::packData() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::packData()
{
::pack( functionIndex ); ::pack( functionIndex );
::pack( idx ); ::pack( idx );
@ -207,20 +238,24 @@ template < typename EntityType > void peoSynchronousMultiStart< EntityType >::pa
// done with functionIndex for the entire data set - moving to another // done with functionIndex for the entire data set - moving to another
// function/algorithm starting all over with the entire data set ( idx is set to 0 ) // function/algorithm starting all over with the entire data set ( idx is set to 0 )
if ( idx == data.size() ) { if ( idx == data.size() )
{
++functionIndex; idx = 0; ++functionIndex;
idx = 0;
} }
} }
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::unpackData() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::unpackData()
{
::unpack( functionIndex ); ::unpack( functionIndex );
::unpack( dataIndex ); ::unpack( dataIndex );
::unpack( entityTypeInstance ); ::unpack( entityTypeInstance );
} }
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::execute() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::execute()
{
// wrapping the unpacked data - the definition of an abstract algorithm imposes // wrapping the unpacked data - the definition of an abstract algorithm imposes
// that its internal function operator acts only on abstract data types // that its internal function operator acts only on abstract data types
@ -230,13 +265,15 @@ template < typename EntityType > void peoSynchronousMultiStart< EntityType >::ex
delete entityWrapper; delete entityWrapper;
} }
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::packResult() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::packResult()
{
::pack( dataIndex ); ::pack( dataIndex );
::pack( entityTypeInstance ); ::pack( entityTypeInstance );
} }
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::unpackResult() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::unpackResult()
{
::unpack( dataIndex ); ::unpack( dataIndex );
::unpack( entityTypeInstance ); ::unpack( entityTypeInstance );
@ -249,18 +286,19 @@ template < typename EntityType > void peoSynchronousMultiStart< EntityType >::un
num_term++; num_term++;
if ( num_term == data.size() * algorithms.size() ) { if ( num_term == data.size() * algorithms.size() )
{
getOwner()->setActive(); getOwner()->setActive();
resume(); resume();
} }
} }
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::notifySendingData() { template < typename EntityType > void peoSynchronousMultiStart< EntityType >::notifySendingData()
{}
} template < typename EntityType > void peoSynchronousMultiStart< EntityType >::notifySendingAllResourceRequests()
{
template < typename EntityType > void peoSynchronousMultiStart< EntityType >::notifySendingAllResourceRequests() {
getOwner()->setPassive(); getOwner()->setPassive();
} }

View file

@ -45,9 +45,8 @@
//! The peoTransform class acts only as an interface for creating transform operators - for an example //! The peoTransform class acts only as an interface for creating transform operators - for an example
//! please refer to the <b>peoSeqTransform</b> and the <b>peoParaSGATransform</b> classes. //! please refer to the <b>peoSeqTransform</b> and the <b>peoParaSGATransform</b> classes.
template< class EOT > class peoTransform : public Service, public eoTransform< EOT > { template< class EOT > class peoTransform : public Service, public eoTransform< EOT >
{};
};
#endif #endif

View file

@ -51,7 +51,8 @@ static sem_t sem_comm_init;
static Communicator * the_thread; static Communicator * the_thread;
Communicator :: Communicator (int * __argc, char * * * __argv) { Communicator :: Communicator (int * __argc, char * * * __argv)
{
the_thread = this; the_thread = this;
initNode (__argc, __argv); initNode (__argc, __argv);
@ -59,9 +60,11 @@ Communicator :: Communicator (int * __argc, char * * * __argv) {
sem_post (& sem_comm_init); sem_post (& sem_comm_init);
} }
void Communicator :: start () { void Communicator :: start ()
{
while (true) { while (true)
{
/* Zzz Zzz Zzz :-))) */ /* Zzz Zzz Zzz :-))) */
sleep (); sleep ();
@ -76,17 +79,20 @@ void Communicator :: start () {
MPI_Finalize (); MPI_Finalize ();
} }
void initCommunication () { void initCommunication ()
{
sem_init (& sem_comm_init, 0, 0); sem_init (& sem_comm_init, 0, 0);
} }
void waitNodeInitialization () { void waitNodeInitialization ()
{
sem_wait (& sem_comm_init); sem_wait (& sem_comm_init);
} }
void wakeUpCommunicator () { void wakeUpCommunicator ()
{
the_thread -> wakeUp (); the_thread -> wakeUp ();
} }

View file

@ -40,15 +40,16 @@
#include "../../core/communicable.h" #include "../../core/communicable.h"
#include "../../core/reac_thread.h" #include "../../core/reac_thread.h"
class Communicator : public ReactiveThread { class Communicator : public ReactiveThread
{
public : public :
/* Ctor */ /* Ctor */
Communicator (int * __argc, char * * * __argv); Communicator (int * __argc, char * * * __argv);
void start (); void start ();
}; };
extern void initCommunication (); extern void initCommunication ();

View file

@ -41,28 +41,33 @@
#include "mess.h" #include "mess.h"
#include "../../core/peo_debug.h" #include "../../core/peo_debug.h"
Runner * Cooperative :: getOwner () { Runner * Cooperative :: getOwner ()
{
return owner; return owner;
} }
void Cooperative :: setOwner (Runner & __runner) { void Cooperative :: setOwner (Runner & __runner)
{
owner = & __runner; owner = & __runner;
} }
void Cooperative :: send (Cooperative * __coop) { void Cooperative :: send (Cooperative * __coop)
{
:: send (this, getRankOfRunner (__coop -> getOwner () -> getID ()), COOP_TAG); :: send (this, getRankOfRunner (__coop -> getOwner () -> getID ()), COOP_TAG);
// stop (); // stop ();
} }
Cooperative * getCooperative (COOP_ID __key) { Cooperative * getCooperative (COOP_ID __key)
{
return dynamic_cast <Cooperative *> (getCommunicable (__key)); return dynamic_cast <Cooperative *> (getCommunicable (__key));
} }
void Cooperative :: notifySending () { void Cooperative :: notifySending ()
{
//getOwner -> setPassive (); //getOwner -> setPassive ();
// resume (); // resume ();

View file

@ -51,14 +51,17 @@ static std :: vector <char *> act_buf; /* Active buffers */
static std :: vector <MPI_Request *> act_req; /* Active requests */ static std :: vector <MPI_Request *> act_req; /* Active requests */
void cleanBuffers () { void cleanBuffers ()
{
for (unsigned i = 0; i < act_req.size ();) { for (unsigned i = 0; i < act_req.size ();)
{
MPI_Status stat ; MPI_Status stat ;
int flag ; int flag ;
MPI_Test (act_req [i], & flag, & stat) ; MPI_Test (act_req [i], & flag, & stat) ;
if (flag) { if (flag)
{
delete act_buf [i] ; delete act_buf [i] ;
delete act_req [i] ; delete act_req [i] ;
@ -74,11 +77,13 @@ void cleanBuffers () {
} }
} }
void waitBuffers () { void waitBuffers ()
{
printDebugMessage ("waiting the termination of the asynchronous operations to complete"); printDebugMessage ("waiting the termination of the asynchronous operations to complete");
for (unsigned i = 0; i < act_req.size (); i ++) { for (unsigned i = 0; i < act_req.size (); i ++)
{
MPI_Status stat ; MPI_Status stat ;
@ -89,7 +94,8 @@ void waitBuffers () {
} }
} }
bool probeMessage (int & __src, int & __tag) { bool probeMessage (int & __src, int & __tag)
{
int flag; int flag;
@ -103,19 +109,22 @@ bool probeMessage (int & __src, int & __tag) {
return flag; return flag;
} }
void waitMessage () { void waitMessage ()
{
MPI_Status stat; MPI_Status stat;
MPI_Probe (MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, & stat); MPI_Probe (MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, & stat);
} }
void initMessage () { void initMessage ()
{
pos_buf = 0; pos_buf = 0;
} }
void sendMessage (int __to, int __tag) { void sendMessage (int __to, int __tag)
{
cleanBuffers (); cleanBuffers ();
act_buf.push_back (new char [pos_buf]); act_buf.push_back (new char [pos_buf]);
@ -124,13 +133,15 @@ void sendMessage (int __to, int __tag) {
MPI_Isend (act_buf.back (), pos_buf, MPI_PACKED, __to, __tag, MPI_COMM_WORLD, act_req.back ()); MPI_Isend (act_buf.back (), pos_buf, MPI_PACKED, __to, __tag, MPI_COMM_WORLD, act_req.back ());
} }
void sendMessageToAll (int __tag) { void sendMessageToAll (int __tag)
{
for (int i = 0; i < getNumberOfNodes (); i ++) for (int i = 0; i < getNumberOfNodes (); i ++)
sendMessage (i, __tag); sendMessage (i, __tag);
} }
void receiveMessage (int __from, int __tag) { void receiveMessage (int __from, int __tag)
{
MPI_Status stat; MPI_Status stat;
MPI_Request req; MPI_Request req;
@ -140,61 +151,71 @@ void receiveMessage (int __from, int __tag) {
} }
/* Char */ /* Char */
void pack (const char & __c) { void pack (const char & __c)
{
MPI_Pack ((void *) & __c, 1, MPI_CHAR, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __c, 1, MPI_CHAR, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Float */ /* Float */
void pack (const float & __f, int __nitem) { void pack (const float & __f, int __nitem)
{
MPI_Pack ((void *) & __f, __nitem, MPI_FLOAT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __f, __nitem, MPI_FLOAT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Double */ /* Double */
void pack (const double & __d, int __nitem) { void pack (const double & __d, int __nitem)
{
MPI_Pack ((void *) & __d, __nitem, MPI_DOUBLE, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __d, __nitem, MPI_DOUBLE, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Integer */ /* Integer */
void pack (const int & __i, int __nitem) { void pack (const int & __i, int __nitem)
{
MPI_Pack ((void *) & __i, __nitem, MPI_INT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __i, __nitem, MPI_INT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Unsigned int. */ /* Unsigned int. */
void pack (const unsigned int & __ui, int __nitem) { void pack (const unsigned int & __ui, int __nitem)
{
MPI_Pack ((void *) & __ui, __nitem, MPI_UNSIGNED, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __ui, __nitem, MPI_UNSIGNED, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Short int. */ /* Short int. */
void pack (const short & __sh, int __nitem) { void pack (const short & __sh, int __nitem)
{
MPI_Pack ((void *) & __sh, __nitem, MPI_SHORT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __sh, __nitem, MPI_SHORT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Unsigned short */ /* Unsigned short */
void pack (const unsigned short & __ush, int __nitem) { void pack (const unsigned short & __ush, int __nitem)
{
MPI_Pack ((void *) & __ush, __nitem, MPI_UNSIGNED_SHORT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __ush, __nitem, MPI_UNSIGNED_SHORT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Long */ /* Long */
void pack (const long & __l, int __nitem) { void pack (const long & __l, int __nitem)
{
MPI_Pack ((void *) & __l, __nitem, MPI_LONG, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __l, __nitem, MPI_LONG, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* Unsigned long */ /* Unsigned long */
void pack (const unsigned long & __ul, int __nitem) { void pack (const unsigned long & __ul, int __nitem)
{
MPI_Pack ((void *) & __ul, __nitem, MPI_UNSIGNED_LONG, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack ((void *) & __ul, __nitem, MPI_UNSIGNED_LONG, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
} }
/* String */ /* String */
void pack (const char * __str) { void pack (const char * __str)
{
int len = strlen (__str) + 1; int len = strlen (__str) + 1;
MPI_Pack (& len, 1, MPI_INT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD); MPI_Pack (& len, 1, MPI_INT, mpi_buf, MPI_BUF_SIZE, & pos_buf, MPI_COMM_WORLD);
@ -202,61 +223,71 @@ void pack (const char * __str) {
} }
/* Char */ /* Char */
void unpack (char & __c) { void unpack (char & __c)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __c, 1, MPI_CHAR, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __c, 1, MPI_CHAR, MPI_COMM_WORLD);
} }
/* Float */ /* Float */
void unpack (float & __f, int __nitem) { void unpack (float & __f, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __f, __nitem, MPI_FLOAT, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __f, __nitem, MPI_FLOAT, MPI_COMM_WORLD);
} }
/* Double */ /* Double */
void unpack (double & __d, int __nitem) { void unpack (double & __d, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __d, __nitem, MPI_DOUBLE, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __d, __nitem, MPI_DOUBLE, MPI_COMM_WORLD);
} }
/* Integer */ /* Integer */
void unpack (int & __i, int __nitem) { void unpack (int & __i, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __i, __nitem, MPI_INT, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __i, __nitem, MPI_INT, MPI_COMM_WORLD);
} }
/* Unsigned int. */ /* Unsigned int. */
void unpack (unsigned int & __ui, int __nitem) { void unpack (unsigned int & __ui, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ui, __nitem, MPI_UNSIGNED, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ui, __nitem, MPI_UNSIGNED, MPI_COMM_WORLD);
} }
/* Short int. */ /* Short int. */
void unpack (short & __sh, int __nitem) { void unpack (short & __sh, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __sh, __nitem, MPI_SHORT, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __sh, __nitem, MPI_SHORT, MPI_COMM_WORLD);
} }
/* Unsigned short */ /* Unsigned short */
void unpack (unsigned short & __ush, int __nitem) { void unpack (unsigned short & __ush, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ush, __nitem, MPI_UNSIGNED_SHORT, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ush, __nitem, MPI_UNSIGNED_SHORT, MPI_COMM_WORLD);
} }
/* Long */ /* Long */
void unpack (long & __l, int __nitem) { void unpack (long & __l, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __l, __nitem, MPI_LONG, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __l, __nitem, MPI_LONG, MPI_COMM_WORLD);
} }
/* Unsigned long */ /* Unsigned long */
void unpack (unsigned long & __ul, int __nitem) { void unpack (unsigned long & __ul, int __nitem)
{
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ul, __nitem, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & __ul, __nitem, MPI_UNSIGNED_LONG, MPI_COMM_WORLD);
} }
/* String */ /* String */
void unpack (char * __str) { void unpack (char * __str)
{
int len; int len;
MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & len, 1, MPI_INT, MPI_COMM_WORLD); MPI_Unpack (mpi_buf, MPI_BUF_SIZE, & pos_buf, & len, 1, MPI_INT, MPI_COMM_WORLD);

View file

@ -46,22 +46,26 @@ static std :: map <std :: string, int> name_to_rk;
static std :: vector <std :: string> rk_to_name; static std :: vector <std :: string> rk_to_name;
int getNodeRank () { int getNodeRank ()
{
return rk; return rk;
} }
int getNumberOfNodes () { int getNumberOfNodes ()
{
return sz; return sz;
} }
int getRankFromName (const std :: string & __name) { int getRankFromName (const std :: string & __name)
{
return atoi (__name.c_str ()); return atoi (__name.c_str ());
} }
void initNode (int * __argc, char * * * __argv) { void initNode (int * __argc, char * * * __argv)
{
int provided; int provided;
MPI_Init_thread (__argc, __argv, MPI_THREAD_FUNNELED, & provided); MPI_Init_thread (__argc, __argv, MPI_THREAD_FUNNELED, & provided);
@ -78,7 +82,8 @@ void initNode (int * __argc, char * * * __argv) {
MPI_Get_processor_name (names [0], & len); /* Me */ MPI_Get_processor_name (names [0], & len); /* Me */
MPI_Allgather (names, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, names, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, MPI_COMM_WORLD); /* Broadcast */ MPI_Allgather (names, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, names, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, MPI_COMM_WORLD); /* Broadcast */
for (int i = 0; i < sz; i ++) { for (int i = 0; i < sz; i ++)
{
rk_to_name.push_back (names [i]); rk_to_name.push_back (names [i]);
name_to_rk [names [i]] = i; name_to_rk [names [i]] = i;
} }

View file

@ -38,7 +38,8 @@
#include "schema.h" #include "schema.h"
void loadRMCParameters (int & __argc, char * * & __argv) { void loadRMCParameters (int & __argc, char * * & __argv)
{
eoParser parser (__argc, __argv); eoParser parser (__argc, __argv);

View file

@ -44,13 +44,16 @@
#include "../../core/cooperative.h" #include "../../core/cooperative.h"
#include "../../core/peo_debug.h" #include "../../core/peo_debug.h"
void receiveMessages () { void receiveMessages ()
{
cleanBuffers (); cleanBuffers ();
do { do
{
if (! atLeastOneActiveThread ()) { if (! atLeastOneActiveThread ())
{
// printDebugMessage ("debut wait"); // printDebugMessage ("debut wait");
waitMessage (); waitMessage ();
//printDebugMessage ("fin wait"); //printDebugMessage ("fin wait");
@ -58,7 +61,8 @@ void receiveMessages () {
int src, tag; int src, tag;
while (probeMessage (src, tag)) { while (probeMessage (src, tag))
{
receiveMessage (src, tag); receiveMessage (src, tag);
initMessage (); initMessage ();
@ -68,7 +72,8 @@ void receiveMessages () {
printDebugMessage (b); printDebugMessage (b);
*/ */
switch (tag) { switch (tag)
{
case RUNNER_STOP_TAG: case RUNNER_STOP_TAG:
unpackTerminationOfRunner (); unpackTerminationOfRunner ();
@ -136,5 +141,6 @@ void receiveMessages () {
}; };
} }
} while (! atLeastOneActiveThread () && atLeastOneActiveRunner () /*&& ! allResourcesFree ()*/); }
while (! atLeastOneActiveThread () && atLeastOneActiveRunner () /*&& ! allResourcesFree ()*/);
} }

View file

@ -43,7 +43,8 @@
static std :: vector <pthread_t *> ll_threads; /* Low level threads */ static std :: vector <pthread_t *> ll_threads; /* Low level threads */
void runRMC () { void runRMC ()
{
/* Worker(s) ? */ /* Worker(s) ? */
for (unsigned i = 0; i < my_node -> num_workers; i ++) for (unsigned i = 0; i < my_node -> num_workers; i ++)
@ -52,7 +53,8 @@ void runRMC () {
wakeUpCommunicator (); wakeUpCommunicator ();
} }
void initRMC (int & __argc, char * * & __argv) { void initRMC (int & __argc, char * * & __argv)
{
/* Communication */ /* Communication */
initCommunication (); initCommunication ();
@ -67,7 +69,8 @@ void initRMC (int & __argc, char * * & __argv) {
/// ///
} }
void finalizeRMC () { void finalizeRMC ()
{
printDebugMessage ("before join threads RMC"); printDebugMessage ("before join threads RMC");
joinThreads (ll_threads); joinThreads (ll_threads);

View file

@ -41,7 +41,8 @@
#include "tags.h" #include "tags.h"
#include "schema.h" #include "schema.h"
bool Runner :: isLocal () { bool Runner :: isLocal ()
{
for (unsigned i = 0; i < my_node -> id_run.size (); i ++) for (unsigned i = 0; i < my_node -> id_run.size (); i ++)
if (my_node -> id_run [i] == id) if (my_node -> id_run [i] == id)
@ -49,12 +50,14 @@ bool Runner :: isLocal () {
return false; return false;
} }
void Runner :: packTermination () { void Runner :: packTermination ()
{
pack (id); pack (id);
} }
void Runner :: terminate () { void Runner :: terminate ()
{
sendToAll (this, RUNNER_STOP_TAG); sendToAll (this, RUNNER_STOP_TAG);
} }

View file

@ -47,9 +47,11 @@ static std :: queue <SCHED_REQUEST> requests; /* Requests */
static unsigned initNumberOfRes = 0; static unsigned initNumberOfRes = 0;
void initScheduler () { void initScheduler ()
{
for (unsigned i = 0; i < the_schema.size (); i ++) { for (unsigned i = 0; i < the_schema.size (); i ++)
{
const Node & node = the_schema [i]; const Node & node = the_schema [i];
@ -60,16 +62,19 @@ void initScheduler () {
initNumberOfRes = resources.size (); initNumberOfRes = resources.size ();
} }
bool allResourcesFree () { bool allResourcesFree ()
{
return resources.size () == initNumberOfRes; return resources.size () == initNumberOfRes;
} }
static void update () { static void update ()
{
unsigned num_alloc = std :: min (resources.size (), requests.size ()); unsigned num_alloc = std :: min (resources.size (), requests.size ());
for (unsigned i = 0; i < num_alloc; i ++) { for (unsigned i = 0; i < num_alloc; i ++)
{
SCHED_REQUEST req = requests.front (); SCHED_REQUEST req = requests.front ();
requests.pop (); requests.pop ();
@ -85,7 +90,8 @@ static void update () {
} }
} }
void unpackResourceRequest () { void unpackResourceRequest ()
{
printDebugMessage ("queuing a resource request."); printDebugMessage ("queuing a resource request.");
SCHED_REQUEST req; SCHED_REQUEST req;
@ -94,7 +100,8 @@ void unpackResourceRequest () {
update (); update ();
} }
void unpackTaskDone () { void unpackTaskDone ()
{
printDebugMessage ("I'm notified a worker is now idle."); printDebugMessage ("I'm notified a worker is now idle.");
SCHED_RESOURCE res; SCHED_RESOURCE res;

View file

@ -47,7 +47,8 @@ std :: vector <Node> the_schema;
Node * my_node; Node * my_node;
RANK_ID getRankOfRunner (RUNNER_ID __key) { RANK_ID getRankOfRunner (RUNNER_ID __key)
{
for (unsigned i = 0; i < the_schema.size (); i ++) for (unsigned i = 0; i < the_schema.size (); i ++)
for (unsigned j = 0; j < the_schema [i].id_run.size (); j ++) for (unsigned j = 0; j < the_schema [i].id_run.size (); j ++)
@ -57,7 +58,8 @@ RANK_ID getRankOfRunner (RUNNER_ID __key) {
return 0; return 0;
} }
static void loadNode (int __rk_sched) { static void loadNode (int __rk_sched)
{
Node node; Node node;
@ -68,18 +70,21 @@ static void loadNode (int __rk_sched) {
/* ATT: num_workers */ /* ATT: num_workers */
node.num_workers = atoi (getAttributeValue ("num_workers").c_str ()); node.num_workers = atoi (getAttributeValue ("num_workers").c_str ());
while (true) { while (true)
{
/* TAG: <runner> | </node> */ /* TAG: <runner> | </node> */
std :: string name = getNextNode (); std :: string name = getNextNode ();
assert (name == "runner" || name == "node"); assert (name == "runner" || name == "node");
if (name == "runner") { if (name == "runner")
{
/* TAG: </node> */ /* TAG: </node> */
node.id_run.push_back (atoi (getNextNode ().c_str ())); node.id_run.push_back (atoi (getNextNode ().c_str ()));
/* TAG: </runner> */ /* TAG: </runner> */
assert (getNextNode () == "runner"); assert (getNextNode () == "runner");
} }
else { else
{
/* TAG: </node> */ /* TAG: </node> */
the_schema.push_back (node); the_schema.push_back (node);
break; break;
@ -87,14 +92,16 @@ static void loadNode (int __rk_sched) {
} }
} }
static void loadGroup () { static void loadGroup ()
{
std :: string name; std :: string name;
/* ATT: scheduler*/ /* ATT: scheduler*/
int rk_sched = getRankFromName (getAttributeValue ("scheduler")); int rk_sched = getRankFromName (getAttributeValue ("scheduler"));
while (true) { while (true)
{
/* TAG: <node> | </group> */ /* TAG: <node> | </group> */
name = getNextNode (); name = getNextNode ();
@ -108,12 +115,14 @@ static void loadGroup () {
} }
} }
bool isScheduleNode () { bool isScheduleNode ()
{
return my_node -> rk == my_node -> rk_sched; return my_node -> rk == my_node -> rk_sched;
} }
void loadSchema (const char * __filename) { void loadSchema (const char * __filename)
{
openXMLDocument (__filename); openXMLDocument (__filename);
@ -123,7 +132,8 @@ void loadSchema (const char * __filename) {
name = getNextNode (); name = getNextNode ();
assert (name == "schema"); assert (name == "schema");
while (true) { while (true)
{
/* TAG: <group> | </schema> */ /* TAG: <group> | </schema> */
name = getNextNode (); name = getNextNode ();
@ -148,11 +158,13 @@ void loadSchema (const char * __filename) {
printDebugMessage (mess); printDebugMessage (mess);
if (isScheduleNode ()) if (isScheduleNode ())
printDebugMessage ("I'am a scheduler"); printDebugMessage ("I'am a scheduler");
for (unsigned i = 0; i < my_node -> id_run.size (); i ++) { for (unsigned i = 0; i < my_node -> id_run.size (); i ++)
{
sprintf (mess, "I manage the runner %d", my_node -> id_run [i]); sprintf (mess, "I manage the runner %d", my_node -> id_run [i]);
printDebugMessage (mess); printDebugMessage (mess);
} }
if (my_node -> num_workers) { if (my_node -> num_workers)
{
sprintf (mess, "I manage %d worker(s)", my_node -> num_workers); sprintf (mess, "I manage %d worker(s)", my_node -> num_workers);
printDebugMessage (mess); printDebugMessage (mess);

View file

@ -45,14 +45,15 @@
typedef int RANK_ID; typedef int RANK_ID;
struct Node { struct Node
{
RANK_ID rk; /* Rank */ RANK_ID rk; /* Rank */
std :: string name; /* Host name */ std :: string name; /* Host name */
unsigned num_workers; /* Number of parallel workers */ unsigned num_workers; /* Number of parallel workers */
int rk_sched; /* rank of the scheduler */ int rk_sched; /* rank of the scheduler */
std :: vector <RUNNER_ID> id_run; /* List of runners */ std :: vector <RUNNER_ID> id_run; /* List of runners */
}; };
extern std :: vector <Node> the_schema; extern std :: vector <Node> the_schema;

View file

@ -49,24 +49,28 @@
#define TO_ALL -1 #define TO_ALL -1
typedef struct { typedef struct
{
Communicable * comm; Communicable * comm;
int to; int to;
int tag; int tag;
} SEND_REQUEST; }
SEND_REQUEST;
static std :: queue <SEND_REQUEST> mess; static std :: queue <SEND_REQUEST> mess;
static sem_t sem_send; static sem_t sem_send;
void initSending () { void initSending ()
{
sem_init (& sem_send, 0, 1); sem_init (& sem_send, 0, 1);
} }
void send (Communicable * __comm, int __to, int __tag) { void send (Communicable * __comm, int __to, int __tag)
{
SEND_REQUEST req; SEND_REQUEST req;
req.comm = __comm; req.comm = __comm;
@ -79,16 +83,19 @@ void send (Communicable * __comm, int __to, int __tag) {
wakeUpCommunicator (); wakeUpCommunicator ();
} }
void sendToAll (Communicable * __comm, int __tag) { void sendToAll (Communicable * __comm, int __tag)
{
send (__comm, TO_ALL, __tag); send (__comm, TO_ALL, __tag);
} }
void sendMessages () { void sendMessages ()
{
sem_wait (& sem_send); sem_wait (& sem_send);
while (! mess.empty ()) { while (! mess.empty ())
{
SEND_REQUEST req = mess.front (); SEND_REQUEST req = mess.front ();
/* /*
@ -101,7 +108,8 @@ void sendMessages () {
initMessage (); initMessage ();
switch (req.tag) { switch (req.tag)
{
case RUNNER_STOP_TAG: case RUNNER_STOP_TAG:
dynamic_cast <Runner *> (comm) -> packTermination (); dynamic_cast <Runner *> (comm) -> packTermination ();

View file

@ -41,14 +41,16 @@
#include "send.h" #include "send.h"
#include "scheduler.h" #include "scheduler.h"
void Service :: requestResourceRequest (unsigned __how_many) { void Service :: requestResourceRequest (unsigned __how_many)
{
num_sent_rr = __how_many; num_sent_rr = __how_many;
for (unsigned i = 0; i < __how_many; i ++) for (unsigned i = 0; i < __how_many; i ++)
send (this, my_node -> rk_sched, SCHED_REQUEST_TAG); send (this, my_node -> rk_sched, SCHED_REQUEST_TAG);
} }
void Service :: packResourceRequest () { void Service :: packResourceRequest ()
{
SCHED_REQUEST req; SCHED_REQUEST req;
req.first = getNodeRank (); req.first = getNodeRank ();

View file

@ -46,25 +46,29 @@
static std :: vector <Worker *> key_to_worker (1); /* Vector of registered workers */ static std :: vector <Worker *> key_to_worker (1); /* Vector of registered workers */
Worker * getWorker (WORKER_ID __key) { Worker * getWorker (WORKER_ID __key)
{
return key_to_worker [__key]; return key_to_worker [__key];
} }
Worker :: Worker () { Worker :: Worker ()
{
toto = false; toto = false;
id = key_to_worker.size (); id = key_to_worker.size ();
key_to_worker.push_back (this); key_to_worker.push_back (this);
} }
void Worker :: packResult () { void Worker :: packResult ()
{
pack (serv_id); pack (serv_id);
serv -> packResult (); serv -> packResult ();
} }
void Worker :: unpackData () { void Worker :: unpackData ()
{
printDebugMessage ("unpacking the ID. of the service."); printDebugMessage ("unpacking the ID. of the service.");
unpack (serv_id); unpack (serv_id);
@ -75,43 +79,51 @@ void Worker :: unpackData () {
setActive (); setActive ();
} }
void Worker :: packTaskDone () { void Worker :: packTaskDone ()
{
pack (getNodeRank ()); pack (getNodeRank ());
pack (id); pack (id);
} }
void Worker :: notifySendingResult () { void Worker :: notifySendingResult ()
{
/* Notifying the scheduler of the termination */ /* Notifying the scheduler of the termination */
toto = true; toto = true;
wakeUp (); wakeUp ();
} }
void Worker :: notifySendingTaskDone () { void Worker :: notifySendingTaskDone ()
{
setPassive (); setPassive ();
} }
void Worker :: setSource (int __rank) { void Worker :: setSource (int __rank)
{
src = __rank; src = __rank;
} }
void Worker :: start () { void Worker :: start ()
{
while (true) { while (true)
{
sleep (); sleep ();
if (! atLeastOneActiveRunner ()) if (! atLeastOneActiveRunner ())
break; break;
if (toto) { if (toto)
{
send (this, my_node -> rk_sched, TASK_DONE_TAG); send (this, my_node -> rk_sched, TASK_DONE_TAG);
toto = false; toto = false;
} }
else { else
{
printDebugMessage ("executing the task."); printDebugMessage ("executing the task.");
serv -> execute (); serv -> execute ();

View file

@ -43,9 +43,10 @@
typedef unsigned WORKER_ID; typedef unsigned WORKER_ID;
class Worker : public Communicable, public ReactiveThread { class Worker : public Communicable, public ReactiveThread
{
public : public :
Worker (); Worker ();
@ -63,7 +64,7 @@ public :
void setSource (int __rank); void setSource (int __rank);
private : private :
WORKER_ID id; WORKER_ID id;
SERVICE_ID serv_id; SERVICE_ID serv_id;
@ -71,7 +72,7 @@ private :
int src; int src;
bool toto; bool toto;
}; };
extern Worker * getWorker (WORKER_ID __key); extern Worker * getWorker (WORKER_ID __key);

View file

@ -40,23 +40,27 @@
static xmlTextReaderPtr reader; static xmlTextReaderPtr reader;
void openXMLDocument (const char * __filename) { void openXMLDocument (const char * __filename)
{
reader = xmlNewTextReaderFilename (__filename); reader = xmlNewTextReaderFilename (__filename);
if (! reader) { if (! reader)
{
fprintf (stderr, "unable to open '%s'.\n", __filename); fprintf (stderr, "unable to open '%s'.\n", __filename);
exit (1); exit (1);
} }
} }
void closeXMLDocument () { void closeXMLDocument ()
{
xmlFreeTextReader (reader); xmlFreeTextReader (reader);
} }
std :: string getAttributeValue (const std :: string & __attr) { std :: string getAttributeValue (const std :: string & __attr)
{
xmlChar * value = xmlTextReaderGetAttribute (reader, (const xmlChar *) __attr.c_str ()); xmlChar * value = xmlTextReaderGetAttribute (reader, (const xmlChar *) __attr.c_str ());
@ -67,7 +71,8 @@ std :: string getAttributeValue (const std :: string & __attr) {
return str; return str;
} }
static bool isSep (const xmlChar * __text) { static bool isSep (const xmlChar * __text)
{
for (unsigned i = 0; i < strlen ((char *) __text); i ++) for (unsigned i = 0; i < strlen ((char *) __text); i ++)
if (__text [i] != ' ' && __text [i] != '\t' && __text [i] != '\n') if (__text [i] != ' ' && __text [i] != '\t' && __text [i] != '\n')
@ -75,16 +80,19 @@ static bool isSep (const xmlChar * __text) {
return true; return true;
} }
std :: string getNextNode () { std :: string getNextNode ()
{
xmlChar * name, * value; xmlChar * name, * value;
do { do
{
xmlTextReaderRead (reader); xmlTextReaderRead (reader);
name = xmlTextReaderName (reader); name = xmlTextReaderName (reader);
value = xmlTextReaderValue (reader); value = xmlTextReaderValue (reader);
// printf ("value = %s\n", value); // printf ("value = %s\n", value);
} while (! strcmp ((char *) name, "#text") && isSep (value)); }
while (! strcmp ((char *) name, "#text") && isSep (value));
std :: string str; std :: string str;

View file

@ -55,19 +55,19 @@ double f (const Indi & _indi)
} }
template < class POT > class eoPrint : public eoContinue <POT> template < class POT > class eoPrint : public eoContinue <POT>
{ {
public : public :
bool operator () (const eoPop <POT> & __pop) bool operator () (const eoPop <POT> & __pop)
{ {
double result[__pop.size()]; double result[__pop.size()];
for(unsigned i=0;i<__pop.size();i++) for (unsigned i=0;i<__pop.size();i++)
result[i]=__pop[i].best(); result[i]=__pop[i].best();
std::sort(result,result+__pop.size()); std::sort(result,result+__pop.size());
std::cout << "\n"<<result[__pop.size()-1]; std::cout << "\n"<<result[__pop.size()-1];
return true ; return true ;
} }
} ; } ;
void peoPSOSeq () void peoPSOSeq ()
{ {
@ -95,7 +95,8 @@ void peoPSOSeq ()
eoStandardFlight < Indi > flight(bndsFlight); eoStandardFlight < Indi > flight(bndsFlight);
eoPop < Indi > popSeq; eoPop < Indi > popSeq;
popSeq.append (POP_SIZE, random); popSeq.append (POP_SIZE, random);
apply(evalSeq, popSeq);; apply(evalSeq, popSeq);
;
apply < Indi > (veloRandom, popSeq); apply < Indi > (veloRandom, popSeq);
apply < Indi > (localInit, popSeq); apply < Indi > (localInit, popSeq);
eoLinearTopology<Indi> topologySeq(NEIGHBORHOOD_SIZE); eoLinearTopology<Indi> topologySeq(NEIGHBORHOOD_SIZE);

View file

@ -78,7 +78,8 @@ double peoPSOSeq ()
eoStandardFlight < Indi > flight(bndsFlight); eoStandardFlight < Indi > flight(bndsFlight);
eoPop < Indi > popSeq; eoPop < Indi > popSeq;
popSeq.append (POP_SIZE, random); popSeq.append (POP_SIZE, random);
apply(evalSeq, popSeq);; apply(evalSeq, popSeq);
;
apply < Indi > (veloRandom, popSeq); apply < Indi > (veloRandom, popSeq);
apply < Indi > (localInit, popSeq); apply < Indi > (localInit, popSeq);
eoLinearTopology<Indi> topologySeq(NEIGHBORHOOD_SIZE); eoLinearTopology<Indi> topologySeq(NEIGHBORHOOD_SIZE);

View file

@ -67,7 +67,7 @@ int main (int __argc, char *__argv[])
const double C1 = 2; const double C1 = 2;
const double C2 = 2; const double C2 = 2;
rng.reseed (36); rng.reseed (36);
if((isScheduleNode())&&(__argc >= 3)) if ((isScheduleNode())&&(__argc >= 3))
begin=clock(); begin=clock();
peoEvalFuncPSO<Indi, double, const Indi& > plainEvalPara(f); peoEvalFuncPSO<Indi, double, const Indi& > plainEvalPara(f);
eoEvalFuncCounter < Indi > evalStartPara (plainEvalPara); eoEvalFuncCounter < Indi > evalStartPara (plainEvalPara);
@ -97,7 +97,7 @@ int main (int __argc, char *__argv[])
psaPara(popPara); psaPara(popPara);
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if((isScheduleNode())&&(__argc >= 3)) if ((isScheduleNode())&&(__argc >= 3))
{ {
end=clock(); end=clock();
time=end-begin; time=end-begin;

View file

@ -57,19 +57,19 @@ double f (const Indi & _indi)
} }
template < class POT > class eoPrint : public eoContinue <POT> template < class POT > class eoPrint : public eoContinue <POT>
{ {
public : public :
bool operator () (const eoPop <POT> & __pop) bool operator () (const eoPop <POT> & __pop)
{ {
double result[__pop.size()]; double result[__pop.size()];
for(unsigned i=0;i<__pop.size();i++) for (unsigned i=0;i<__pop.size();i++)
result[i]=__pop[i].best(); result[i]=__pop[i].best();
std::sort(result,result+__pop.size()); std::sort(result,result+__pop.size());
std::cout << "\n"<<result[__pop.size()-1]; std::cout << "\n"<<result[__pop.size()-1];
return true ; return true ;
} }
} ; } ;
int main (int __argc, char *__argv[]) int main (int __argc, char *__argv[])
@ -91,7 +91,7 @@ int main (int __argc, char *__argv[])
const double C1 = 0.5; const double C1 = 0.5;
const double C2 = 2; const double C2 = 2;
rng.reseed (44); rng.reseed (44);
if(getNodeRank()==1) if (getNodeRank()==1)
std::cout<<"\n\nWith two islands\n\n"; std::cout<<"\n\nWith two islands\n\n";
peoEvalFuncPSO<Indi, double, const Indi& > plainEval(f); peoEvalFuncPSO<Indi, double, const Indi& > plainEval(f);
eoUniformGenerator < double >uGen (INIT_POSITION_MIN, INIT_POSITION_MAX); eoUniformGenerator < double >uGen (INIT_POSITION_MIN, INIT_POSITION_MAX);
@ -123,7 +123,7 @@ int main (int __argc, char *__argv[])
peoPSOSelect<Indi> mig_selec(topology); peoPSOSelect<Indi> mig_selec(topology);
eoSelectNumber< Indi > mig_select(mig_selec); eoSelectNumber< Indi > mig_select(mig_selec);
peoPSOReplacement<Indi> mig_replace; peoPSOReplacement<Indi> mig_replace;
/*****************************************************************/ /*****************************************************************/
peoEvalFuncPSO<Indi, double, const Indi& > plainEval2(f); peoEvalFuncPSO<Indi, double, const Indi& > plainEval2(f);
eoUniformGenerator < double >uGen2 (INIT_POSITION_MIN, INIT_POSITION_MAX); eoUniformGenerator < double >uGen2 (INIT_POSITION_MIN, INIT_POSITION_MAX);

View file

@ -120,6 +120,6 @@ int main (int __argc, char *__argv[])
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
std::cout << "Final population :\n" << pop << std::endl; std::cout << "Final population :\n" << pop << std::endl;
} }

View file

@ -137,6 +137,6 @@ int main (int __argc, char *__argv[])
psa(pop); psa(pop);
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
std::cout << "Final population :\n" << pop << std::endl; std::cout << "Final population :\n" << pop << std::endl;
} }

View file

@ -91,7 +91,7 @@ int main (int __argc, char *__argv[])
peoParaSGATransform <Indi> eaTransform(crossover,CROSS_RATE,mutation,MUT_RATE); peoParaSGATransform <Indi> eaTransform(crossover,CROSS_RATE,mutation,MUT_RATE);
/******************************************************************************************/ /******************************************************************************************/
eoPlusReplacement<Indi> replace; eoPlusReplacement<Indi> replace;
eoPop < Indi > pop; eoPop < Indi > pop;
@ -100,6 +100,6 @@ int main (int __argc, char *__argv[])
Algo(pop); Algo(pop);
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
std::cout << "Final population :\n" << pop << std::endl; std::cout << "Final population :\n" << pop << std::endl;
} }

View file

@ -60,16 +60,16 @@ int main (int __argc, char *__argv[])
const float CROSS_RATE = 0.8; const float CROSS_RATE = 0.8;
const double EPSILON = 0.01; const double EPSILON = 0.01;
const float MUT_RATE = 0.3; const float MUT_RATE = 0.3;
// MIG_FREQ define the frequency of the migration. // MIG_FREQ define the frequency of the migration.
const unsigned int MIG_FREQ = 10; const unsigned int MIG_FREQ = 10;
// MIG_SIZE define the size of each migration. // MIG_SIZE define the size of each migration.
const unsigned int MIG_SIZE = 5; const unsigned int MIG_SIZE = 5;
rng.reseed (time(0)); rng.reseed (time(0));
// Define the topology of your island model // Define the topology of your island model
RingTopology topology; RingTopology topology;
// First algorithm // First algorithm
/*****************************************************************************************/ /*****************************************************************************************/
eoGenContinue < Indi > genContPara (MAX_GEN); eoGenContinue < Indi > genContPara (MAX_GEN);
eoCombinedContinue <Indi> continuatorPara (genContPara); eoCombinedContinue <Indi> continuatorPara (genContPara);
@ -93,7 +93,7 @@ int main (int __argc, char *__argv[])
eoSelectNumber<Indi> mig_select (mig_select_one,MIG_SIZE); eoSelectNumber<Indi> mig_select (mig_select_one,MIG_SIZE);
eoPlusReplacement<Indi> mig_replace; // Immigrants replace the worse individuals eoPlusReplacement<Indi> mig_replace; // Immigrants replace the worse individuals
/*****************************************************************************************/ /*****************************************************************************************/
// Second algorithm (on the same model but with others names) // Second algorithm (on the same model but with others names)
/*****************************************************************************************/ /*****************************************************************************************/
@ -118,7 +118,7 @@ int main (int __argc, char *__argv[])
eoSelectNumber<Indi> mig_select2 (mig_select_one2,MIG_SIZE); eoSelectNumber<Indi> mig_select2 (mig_select_one2,MIG_SIZE);
eoPlusReplacement<Indi> mig_replace2; eoPlusReplacement<Indi> mig_replace2;
/*****************************************************************************************/ /*****************************************************************************************/
// You can choose between : // You can choose between :
// //
@ -140,7 +140,7 @@ int main (int __argc, char *__argv[])
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
{ {
std::cout << "Final population 1 :\n" << pop << std::endl; std::cout << "Final population 1 :\n" << pop << std::endl;
std::cout << "Final population 2 :\n" << pop2 << std::endl; std::cout << "Final population 2 :\n" << pop2 << std::endl;

View file

@ -53,7 +53,7 @@ int main (int __argc, char *__argv[])
// In this lesson, we define two algorithms of the PSO witch represents two islands. // In this lesson, we define two algorithms of the PSO witch represents two islands.
// Obviously, you can define more algorithms. // Obviously, you can define more algorithms.
// The parameters are common between the two algorithms. // The parameters are common between the two algorithms.
/*****************************************************************************************/ /*****************************************************************************************/
peo :: init( __argc, __argv ); peo :: init( __argc, __argv );
const unsigned int VEC_SIZE = 2; const unsigned int VEC_SIZE = 2;
@ -66,17 +66,17 @@ int main (int __argc, char *__argv[])
const double INIT_VELOCITY_MAX = 1.; const double INIT_VELOCITY_MAX = 1.;
const double C1 = 0.5; const double C1 = 0.5;
const double C2 = 2.; const double C2 = 2.;
// C3 is used for the calculation of one of the strategies of the island model. // C3 is used for the calculation of one of the strategies of the island model.
const double C3 = 2.; const double C3 = 2.;
// MIG_FREQ define the frequency of the migration. // MIG_FREQ define the frequency of the migration.
const unsigned int MIG_FREQ = 10; // The optimal value is 1 or 2 for the component peoPSOVelocity. const unsigned int MIG_FREQ = 10; // The optimal value is 1 or 2 for the component peoPSOVelocity.
rng.reseed (time(0)); rng.reseed (time(0));
/*****************************************************************************************/ /*****************************************************************************************/
// Define the topology of your island model // Define the topology of your island model
RingTopology topologyMig; RingTopology topologyMig;
// First algorithm // First algorithm
/*****************************************************************************************/ /*****************************************************************************************/
peoEvalFuncPSO<Indi, double, const Indi& > plainEval(f); peoEvalFuncPSO<Indi, double, const Indi& > plainEval(f);
peoSeqPopEval< Indi > eval(plainEval); // Here, the evaluation is sequential ! peoSeqPopEval< Indi > eval(plainEval); // Here, the evaluation is sequential !
@ -95,17 +95,17 @@ int main (int __argc, char *__argv[])
eoStandardVelocity < Indi > velocity (topology,C1,C2,bnds); eoStandardVelocity < Indi > velocity (topology,C1,C2,bnds);
eoGenContinue < Indi > genContPara (MAX_GEN); eoGenContinue < Indi > genContPara (MAX_GEN);
eoCheckPoint<Indi> checkpoint(genContPara); eoCheckPoint<Indi> checkpoint(genContPara);
// Specific implementation for the island model // Specific implementation for the island model
eoPeriodicContinue< Indi > mig_cont( MIG_FREQ ); eoPeriodicContinue< Indi > mig_cont( MIG_FREQ );
peoPSOSelect<Indi> mig_selec(topology); peoPSOSelect<Indi> mig_selec(topology);
eoSelectNumber< Indi > mig_select(mig_selec); eoSelectNumber< Indi > mig_select(mig_selec);
// If you want to use a replacement stategy : peoPSOReplacement<Indi> mig_replace; // If you want to use a replacement stategy : peoPSOReplacement<Indi> mig_replace;
// If you want to use a consideration of the migration in the calculation of the velocity : peoPSOVelocity<Indi> mig_replace(C3,velocity); // If you want to use a consideration of the migration in the calculation of the velocity : peoPSOVelocity<Indi> mig_replace(C3,velocity);
peoPSOReplacement<Indi> mig_replace; peoPSOReplacement<Indi> mig_replace;
/*****************************************************************************************/ /*****************************************************************************************/
// Second algorithm (on the same model but with others names) // Second algorithm (on the same model but with others names)
/*****************************************************************************************/ /*****************************************************************************************/
peoEvalFuncPSO<Indi, double, const Indi& > plainEval2(f); peoEvalFuncPSO<Indi, double, const Indi& > plainEval2(f);
peoSeqPopEval< Indi > eval2(plainEval2); peoSeqPopEval< Indi > eval2(plainEval2);
eoUniformGenerator < double >uGen2 (INIT_POSITION_MIN, INIT_POSITION_MAX); eoUniformGenerator < double >uGen2 (INIT_POSITION_MIN, INIT_POSITION_MAX);
@ -127,14 +127,14 @@ int main (int __argc, char *__argv[])
peoPSOSelect<Indi> mig_selec2(topology2); peoPSOSelect<Indi> mig_selec2(topology2);
eoSelectNumber< Indi > mig_select2(mig_selec2); eoSelectNumber< Indi > mig_select2(mig_selec2);
peoPSOReplacement<Indi> mig_replace2; peoPSOReplacement<Indi> mig_replace2;
/*****************************************************************************************/ /*****************************************************************************************/
// Define the communication between the islands // Define the communication between the islands
peoAsyncIslandMig< Indi > mig( mig_cont, mig_select, mig_replace, topologyMig, pop, pop); peoAsyncIslandMig< Indi > mig( mig_cont, mig_select, mig_replace, topologyMig, pop, pop);
checkpoint.add( mig ); checkpoint.add( mig );
peoAsyncIslandMig< Indi > mig2( mig_cont2, mig_select2, mig_replace2, topologyMig, pop2, pop2); peoAsyncIslandMig< Indi > mig2( mig_cont2, mig_select2, mig_replace2, topologyMig, pop2, pop2);
checkpoint2.add( mig2 ); checkpoint2.add( mig2 );
// Initialization of the algorithms // Initialization of the algorithms
peoPSO < Indi > psa(init,checkpoint, eval, velocity, flight); peoPSO < Indi > psa(init,checkpoint, eval, velocity, flight);
mig.setOwner( psa ); mig.setOwner( psa );
psa(pop); psa(pop);
@ -144,7 +144,7 @@ int main (int __argc, char *__argv[])
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
{ {
std::cout << "Population 1 :\n" << pop << std::endl; std::cout << "Population 1 :\n" << pop << std::endl;
std::cout << "Population 2 :\n" << pop2 << std::endl; std::cout << "Population 2 :\n" << pop2 << std::endl;

View file

@ -143,7 +143,7 @@ int main (int __argc, char *__argv[])
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
{ {
std::cout << "Final population 1 :\n" << pop << std::endl; std::cout << "Final population 1 :\n" << pop << std::endl;
std::cout << "Final population 2 :\n" << pop2 << std::endl; std::cout << "Final population 2 :\n" << pop2 << std::endl;

View file

@ -150,7 +150,7 @@ int main (int __argc, char *__argv[])
peo :: run(); peo :: run();
peo :: finalize(); peo :: finalize();
if(getNodeRank()==1) if (getNodeRank()==1)
{ {
std::cout << "Population 1 :\n" << pop << std::endl; std::cout << "Population 1 :\n" << pop << std::endl;
std::cout << "Population 2 :\n" << pop2 << std::endl; std::cout << "Population 2 :\n" << pop2 << std::endl;

View file

@ -59,7 +59,8 @@
#define MUT_RATE 0.01 #define MUT_RATE 0.01
int main (int __argc, char * * __argv) { int main (int __argc, char * * __argv)
{
// Example of a problem (TSP) with an hybridization // Example of a problem (TSP) with an hybridization
@ -106,10 +107,10 @@ int main (int __argc, char * * __argv) {
peo :: run (); peo :: run ();
peo :: finalize (); /* Termination */ peo :: finalize (); /* Termination */
if(getNodeRank()==1) if (getNodeRank()==1)
std :: cout << "\nResult : "<<ox_pop[ 0 ].fitness(); std :: cout << "\nResult : "<<ox_pop[ 0 ].fitness();
hc( ox_pop[ 0 ] ); hc( ox_pop[ 0 ] );
if(getNodeRank()==1) if (getNodeRank()==1)
std :: cout << "\n\nAfter an hybridization : " << ox_pop[ 0 ].fitness() << std :: endl; std :: cout << "\n\nAfter an hybridization : " << ox_pop[ 0 ].fitness() << std :: endl;

View file

@ -51,7 +51,7 @@
int main( int __argc, char** __argv ) int main( int __argc, char** __argv )
{ {
/* In this lesson you will learn to use a multi-start. /* In this lesson you will learn to use a multi-start.
* *
* Thanks to this method, you can use several local searches together !!! * Thanks to this method, you can use several local searches together !!!
* *

View file

@ -38,7 +38,8 @@
#include "city_swap.h" #include "city_swap.h"
bool CitySwap :: operator () (Route & __route) { bool CitySwap :: operator () (Route & __route)
{
std :: swap (__route [rng.random (__route.size ())], std :: swap (__route [rng.random (__route.size ())],
__route [rng.random (__route.size ())]) ; __route [rng.random (__route.size ())]) ;

View file

@ -43,12 +43,13 @@
/** Its swaps two vertices /** Its swaps two vertices
randomly choosen */ randomly choosen */
class CitySwap : public eoMonOp <Route> { class CitySwap : public eoMonOp <Route>
{
public : public :
bool operator () (Route & __route) ; bool operator () (Route & __route) ;
} ; } ;
#endif #endif

View file

@ -48,7 +48,8 @@
#define MAX_FIELD_LENGTH 1000 #define MAX_FIELD_LENGTH 1000
#define MAX_LINE_LENGTH 1000 #define MAX_LINE_LENGTH 1000
static void getNextField (FILE * __f, char * __buff) { static void getNextField (FILE * __f, char * __buff)
{
char trash [MAX_TRASH_LENGTH]; char trash [MAX_TRASH_LENGTH];
@ -57,7 +58,8 @@ static void getNextField (FILE * __f, char * __buff) {
fgetc (__f); fgetc (__f);
} }
static void getLine (FILE * __f, char * __buff) { static void getLine (FILE * __f, char * __buff)
{
char trash [MAX_TRASH_LENGTH]; char trash [MAX_TRASH_LENGTH];
@ -65,11 +67,13 @@ static void getLine (FILE * __f, char * __buff) {
fscanf (__f, "%[^\n]", __buff); /* Reading the line */ fscanf (__f, "%[^\n]", __buff); /* Reading the line */
} }
void loadData (const char * __filename) { void loadData (const char * __filename)
{
FILE * f = fopen (__filename, "r"); FILE * f = fopen (__filename, "r");
if (f) { if (f)
{
printf ("Loading '%s'.\n", __filename); printf ("Loading '%s'.\n", __filename);
@ -109,14 +113,16 @@ void loadData (const char * __filename) {
assert (strstr (field, "EOF")); assert (strstr (field, "EOF"));
printf ("EOF.\n"); printf ("EOF.\n");
} }
else { else
{
fprintf (stderr, "Can't open '%s'.\n", __filename); fprintf (stderr, "Can't open '%s'.\n", __filename);
exit (1); exit (1);
} }
} }
void loadData (eoParser & __parser) { void loadData (eoParser & __parser)
{
/* Getting the path of the instance */ /* Getting the path of the instance */

View file

@ -67,13 +67,13 @@ static int screen;
/* Create a new backing pixmap of the appropriate size */ /* Create a new backing pixmap of the appropriate size */
/* Best tour */ /* Best tour */
/* /*
gdk_gc_set_line_attributes (gc, 2, GDK_LINE_ON_OFF_DASH, GDK_CAP_NOT_LAST, GDK_JOIN_MITER) ; gdk_gc_set_line_attributes (gc, 2, GDK_LINE_ON_OFF_DASH, GDK_CAP_NOT_LAST, GDK_JOIN_MITER) ;
gdk_gc_set_foreground (gc, & color_green) ; gdk_gc_set_foreground (gc, & color_green) ;
for (int i = 0 ; i < (int) numNodes ; i ++) { for (int i = 0 ; i < (int) numNodes ; i ++) {
gdk_draw_line (pixmap, gc, gdk_draw_line (pixmap, gc,
X_new_coord [opt_route [i]], X_new_coord [opt_route [i]],
@ -83,7 +83,8 @@ static int screen;
}*/ }*/
void openMainWindow (const char * __filename) { void openMainWindow (const char * __filename)
{
filename = __filename; filename = __filename;
@ -100,7 +101,8 @@ void openMainWindow (const char * __filename) {
X_new_coord = new unsigned [numNodes]; X_new_coord = new unsigned [numNodes];
Y_new_coord = new unsigned [numNodes]; Y_new_coord = new unsigned [numNodes];
for (unsigned i = 0; i < numNodes; i ++) { for (unsigned i = 0; i < numNodes; i ++)
{
X_new_coord [i] = (unsigned) (win_width * (1.0 - (X_coord [i] - X_min) / map_width) + BORDER); X_new_coord [i] = (unsigned) (win_width * (1.0 - (X_coord [i] - X_min) / map_width) + BORDER);
Y_new_coord [i] = (unsigned) (win_height * (1.0 - (Y_coord [i] - Y_min) / map_height) + BORDER); Y_new_coord [i] = (unsigned) (win_height * (1.0 - (Y_coord [i] - Y_min) / map_height) + BORDER);
} }
@ -118,7 +120,8 @@ void openMainWindow (const char * __filename) {
XMapWindow (disp, win) ; XMapWindow (disp, win) ;
XFlush (disp) ; XFlush (disp) ;
while (true) { while (true)
{
XClearWindow (disp, win) ; XClearWindow (disp, win) ;
/* Vertices as circles */ /* Vertices as circles */
@ -127,7 +130,8 @@ void openMainWindow (const char * __filename) {
/* New tour */ /* New tour */
std :: ifstream f (filename); std :: ifstream f (filename);
if (f) { if (f)
{
Route route; Route route;
f >> route; f >> route;
f.close (); f.close ();

View file

@ -38,12 +38,13 @@
#include "display.h" #include "display.h"
DisplayBestRoute :: DisplayBestRoute (eoPop <Route> & __pop DisplayBestRoute :: DisplayBestRoute (eoPop <Route> & __pop
) : pop (__pop) { ) : pop (__pop)
{
} }
void DisplayBestRoute :: operator () () { void DisplayBestRoute :: operator () ()
{
displayRoute (pop.best_element ()); displayRoute (pop.best_element ());
} }

View file

@ -43,18 +43,19 @@
#include "route.h" #include "route.h"
class DisplayBestRoute : public eoUpdater { class DisplayBestRoute : public eoUpdater
{
public : public :
DisplayBestRoute (eoPop <Route> & __pop); DisplayBestRoute (eoPop <Route> & __pop);
void operator () (); void operator () ();
private : private :
eoPop <Route> & pop; eoPop <Route> & pop;
}; };
#endif #endif

View file

@ -41,7 +41,8 @@
#include "edge_xover.h" #include "edge_xover.h"
void EdgeXover :: build_map (const Route & __par1, const Route & __par2) { void EdgeXover :: build_map (const Route & __par1, const Route & __par2)
{
unsigned len = __par1.size () ; unsigned len = __par1.size () ;
@ -49,7 +50,8 @@ void EdgeXover :: build_map (const Route & __par1, const Route & __par2) {
_map.clear () ; _map.clear () ;
_map.resize (len) ; _map.resize (len) ;
for (unsigned i = 0 ; i < len ; i ++) { for (unsigned i = 0 ; i < len ; i ++)
{
_map [__par1 [i]].insert (__par1 [(i + 1) % len]) ; _map [__par1 [i]].insert (__par1 [(i + 1) % len]) ;
_map [__par2 [i]].insert (__par2 [(i + 1) % len]) ; _map [__par2 [i]].insert (__par2 [(i + 1) % len]) ;
_map [__par1 [i]].insert (__par1 [(i - 1 + len) % len]) ; _map [__par1 [i]].insert (__par1 [(i - 1 + len) % len]) ;
@ -60,7 +62,8 @@ void EdgeXover :: build_map (const Route & __par1, const Route & __par2) {
visited.resize (len, false) ; visited.resize (len, false) ;
} }
void EdgeXover :: remove_entry (unsigned __vertex, std :: vector <std :: set <unsigned> > & __map) { void EdgeXover :: remove_entry (unsigned __vertex, std :: vector <std :: set <unsigned> > & __map)
{
std :: set <unsigned> & neigh = __map [__vertex] ; std :: set <unsigned> & neigh = __map [__vertex] ;
@ -69,16 +72,18 @@ void EdgeXover :: remove_entry (unsigned __vertex, std :: vector <std :: set <un
it ++) it ++)
__map [* it].erase (__vertex) ; __map [* it].erase (__vertex) ;
} }
void EdgeXover :: add_vertex (unsigned __vertex, Route & __child) { void EdgeXover :: add_vertex (unsigned __vertex, Route & __child)
{
visited [__vertex] = true ; visited [__vertex] = true ;
__child.push_back (__vertex) ; __child.push_back (__vertex) ;
remove_entry (__vertex, _map) ; /* Removing entries */ remove_entry (__vertex, _map) ; /* Removing entries */
} }
void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __child) { void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __child)
{
build_map (__par1, __par2) ; build_map (__par1, __par2) ;
@ -91,7 +96,8 @@ void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __c
add_vertex (cur_vertex, __child) ; add_vertex (cur_vertex, __child) ;
for (unsigned i = 1 ; i < len ; i ++) { for (unsigned i = 1 ; i < len ; i ++)
{
unsigned len_min_entry = MAXINT ; unsigned len_min_entry = MAXINT ;
@ -99,7 +105,8 @@ void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __c
for (std :: set <unsigned> :: iterator it = neigh.begin () ; for (std :: set <unsigned> :: iterator it = neigh.begin () ;
it != neigh.end () ; it != neigh.end () ;
it ++) { it ++)
{
unsigned l = _map [* it].size () ; unsigned l = _map [* it].size () ;
if (len_min_entry > l) if (len_min_entry > l)
len_min_entry = l ; len_min_entry = l ;
@ -109,13 +116,15 @@ void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __c
for (std :: set <unsigned> :: iterator it = neigh.begin () ; for (std :: set <unsigned> :: iterator it = neigh.begin () ;
it != neigh.end () ; it != neigh.end () ;
it ++) { it ++)
{
unsigned l = _map [* it].size () ; unsigned l = _map [* it].size () ;
if (len_min_entry == l) if (len_min_entry == l)
cand.push_back (* it) ; cand.push_back (* it) ;
} }
if (! cand.size ()) { if (! cand.size ())
{
/* Oh no ! Implicit mutation */ /* Oh no ! Implicit mutation */
for (unsigned j = 0 ; j < len ; j ++) for (unsigned j = 0 ; j < len ; j ++)
@ -129,7 +138,8 @@ void EdgeXover :: cross (const Route & __par1, const Route & __par2, Route & __c
} }
} }
bool EdgeXover :: operator () (Route & __route1, Route & __route2) { bool EdgeXover :: operator () (Route & __route1, Route & __route2)
{
// Init. copy // Init. copy
Route par [2] ; Route par [2] ;

View file

@ -45,13 +45,14 @@
#include "route.h" #include "route.h"
/** Edge Crossover */ /** Edge Crossover */
class EdgeXover : public eoQuadOp <Route> { class EdgeXover : public eoQuadOp <Route>
{
public : public :
bool operator () (Route & __route1, Route & __route2) ; bool operator () (Route & __route1, Route & __route2) ;
private : private :
void cross (const Route & __par1, const Route & __par2, Route & __child) ; /* Binary */ void cross (const Route & __par1, const Route & __par2, Route & __child) ; /* Binary */
@ -66,6 +67,6 @@ private :
std :: vector <bool> visited ; /* Vertices that are already visited */ std :: vector <bool> visited ; /* Vertices that are already visited */
} ; } ;
#endif #endif

View file

@ -36,7 +36,8 @@
#include "merge_route_eval.h" #include "merge_route_eval.h"
void MergeRouteEval :: operator () (Route & __route, const int & __part_fit) { void MergeRouteEval :: operator () (Route & __route, const int & __part_fit)
{
int len = __route.fitness (); int len = __route.fitness ();
len += __part_fit; len += __part_fit;

View file

@ -41,12 +41,13 @@
#include "route.h" #include "route.h"
class MergeRouteEval : public peoAggEvalFunc <Route> { class MergeRouteEval : public peoAggEvalFunc <Route>
{
public : public :
void operator () (Route & __route, const int & __part_fit) ; void operator () (Route & __route, const int & __part_fit) ;
}; };
#endif #endif

View file

@ -41,7 +41,8 @@
#include <utils/eoRNG.h> #include <utils/eoRNG.h>
template <class T> void mix (std :: vector <T> & __v) { template <class T> void mix (std :: vector <T> & __v)
{
unsigned len = __v.size () ; unsigned len = __v.size () ;

View file

@ -47,7 +47,8 @@ double * X_coord, * Y_coord;
double X_min = MAXDOUBLE, X_max = MINDOUBLE, Y_min = MAXDOUBLE, Y_max = MINDOUBLE; double X_min = MAXDOUBLE, X_max = MINDOUBLE, Y_min = MAXDOUBLE, Y_max = MINDOUBLE;
void loadNodes (FILE * __f) { void loadNodes (FILE * __f)
{
/* Coord */ /* Coord */
@ -57,7 +58,8 @@ void loadNodes (FILE * __f) {
unsigned num; unsigned num;
for (unsigned i = 0; i < numNodes; i ++) { for (unsigned i = 0; i < numNodes; i ++)
{
fscanf (__f, "%u%lf%lf", & num, X_coord + i, Y_coord + i); fscanf (__f, "%u%lf%lf", & num, X_coord + i, Y_coord + i);
@ -94,7 +96,8 @@ void loadNodes (FILE * __f) {
}*/ }*/
} }
unsigned distance (Node __from, Node __to) { unsigned distance (Node __from, Node __to)
{
// return dist [__from] [__to]; // return dist [__from] [__to];

View file

@ -40,7 +40,8 @@
#define MAX_FIELD_LENGTH 1000 #define MAX_FIELD_LENGTH 1000
#define MAX_LINE_LENGTH 1000 #define MAX_LINE_LENGTH 1000
static void getNextField (FILE * __f, char * __buff) { static void getNextField (FILE * __f, char * __buff)
{
char trash [MAX_TRASH_LENGTH]; char trash [MAX_TRASH_LENGTH];
@ -49,7 +50,8 @@ static void getNextField (FILE * __f, char * __buff) {
fgetc (__f); fgetc (__f);
} }
static void getLine (FILE * __f, char * __buff) { static void getLine (FILE * __f, char * __buff)
{
char trash [MAX_TRASH_LENGTH]; char trash [MAX_TRASH_LENGTH];
@ -57,11 +59,13 @@ static void getLine (FILE * __f, char * __buff) {
fscanf (__f, "%[^\n]", __buff); /* Reading the line */ fscanf (__f, "%[^\n]", __buff); /* Reading the line */
} }
static void loadBestRoute (FILE * __f) { static void loadBestRoute (FILE * __f)
{
opt_route.clear (); opt_route.clear ();
for (unsigned i = 0; i < numNodes; i ++) { for (unsigned i = 0; i < numNodes; i ++)
{
Node node; Node node;
fscanf (__f, "%u", & node); fscanf (__f, "%u", & node);
opt_route.push_back (node - 1); opt_route.push_back (node - 1);
@ -70,11 +74,13 @@ static void loadBestRoute (FILE * __f) {
fscanf (__f, "%d", & d); fscanf (__f, "%d", & d);
} }
void loadOptimumRoute (const char * __filename) { void loadOptimumRoute (const char * __filename)
{
FILE * f = fopen (__filename, "r"); FILE * f = fopen (__filename, "r");
if (f) { if (f)
{
printf ("Loading '%s'.\n", __filename); printf ("Loading '%s'.\n", __filename);
@ -111,14 +117,16 @@ void loadOptimumRoute (const char * __filename) {
printf ("The length of the best route is %u.\n", length (opt_route)); printf ("The length of the best route is %u.\n", length (opt_route));
} }
else { else
{
fprintf (stderr, "Can't open '%s'.\n", __filename); fprintf (stderr, "Can't open '%s'.\n", __filename);
exit (1); exit (1);
} }
} }
void loadOptimumRoute (eoParser & __parser) { void loadOptimumRoute (eoParser & __parser)
{
/* Getting the path of the instance */ /* Getting the path of the instance */

View file

@ -40,7 +40,8 @@
#include "order_xover.h" #include "order_xover.h"
void OrderXover :: cross (const Route & __par1, const Route & __par2, Route & __child) { void OrderXover :: cross (const Route & __par1, const Route & __par2, Route & __child)
{
unsigned cut2 = 1 + rng.random (numNodes) ; unsigned cut2 = 1 + rng.random (numNodes) ;
unsigned cut1 = rng.random (cut2); unsigned cut1 = rng.random (cut2);
@ -50,7 +51,8 @@ void OrderXover :: cross (const Route & __par1, const Route & __par2, Route & __
std :: vector <bool> v (numNodes, false); std :: vector <bool> v (numNodes, false);
/* Copy of the left partial route of the first parent */ /* Copy of the left partial route of the first parent */
for (unsigned i = cut1 ; i < cut2 ; i ++) { for (unsigned i = cut1 ; i < cut2 ; i ++)
{
__child [l ++] = __par1 [i] ; __child [l ++] = __par1 [i] ;
v [__par1 [i]] = true ; v [__par1 [i]] = true ;
} }
@ -58,7 +60,8 @@ void OrderXover :: cross (const Route & __par1, const Route & __par2, Route & __
/* Searching the vertex of the second path, that ended the previous first one */ /* Searching the vertex of the second path, that ended the previous first one */
unsigned from = 0 ; unsigned from = 0 ;
for (unsigned i = 0; i < numNodes; i ++) for (unsigned i = 0; i < numNodes; i ++)
if (__par2 [i] == __child [cut2 - 1]) { if (__par2 [i] == __child [cut2 - 1])
{
from = i ; from = i ;
break ; break ;
} }
@ -66,16 +69,19 @@ void OrderXover :: cross (const Route & __par1, const Route & __par2, Route & __
/* Selecting a direction (Left or Right) */ /* Selecting a direction (Left or Right) */
char direct = rng.flip () ? 1 : -1 ; char direct = rng.flip () ? 1 : -1 ;
for (unsigned i = 0; i < numNodes + 1; i ++) { for (unsigned i = 0; i < numNodes + 1; i ++)
{
unsigned bidule = (direct * i + from + numNodes) % numNodes; unsigned bidule = (direct * i + from + numNodes) % numNodes;
if (! v [__par2 [bidule]]) { if (! v [__par2 [bidule]])
{
__child [l ++] = __par2 [bidule] ; __child [l ++] = __par2 [bidule] ;
v [__par2 [bidule]] = true ; v [__par2 [bidule]] = true ;
} }
} }
} }
bool OrderXover :: operator () (Route & __route1, Route & __route2) { bool OrderXover :: operator () (Route & __route1, Route & __route2)
{
// Init. copy // Init. copy
Route par [2] ; Route par [2] ;

View file

@ -42,15 +42,16 @@
#include "route.h" #include "route.h"
/** Order Crossover */ /** Order Crossover */
class OrderXover : public eoQuadOp <Route> { class OrderXover : public eoQuadOp <Route>
{
public : public :
bool operator () (Route & __route1, Route & __route2) ; bool operator () (Route & __route1, Route & __route2) ;
private : private :
void cross (const Route & __par1, const Route & __par2, Route & __child) ; void cross (const Route & __par1, const Route & __par2, Route & __child) ;
} ; } ;
#endif #endif

View file

@ -39,7 +39,8 @@
#include "data.h" #include "data.h"
#include "opt_route.h" #include "opt_route.h"
void loadParameters (int __argc, char * * __argv) { void loadParameters (int __argc, char * * __argv)
{
eoParser parser (__argc, __argv); eoParser parser (__argc, __argv);

View file

@ -40,11 +40,12 @@
PartRouteEval :: PartRouteEval (float __from, PartRouteEval :: PartRouteEval (float __from,
float __to float __to
) : from (__from), ) : from (__from),
to (__to) { to (__to)
{
} }
void PartRouteEval :: operator () (Route & __route) { void PartRouteEval :: operator () (Route & __route)
{
unsigned len = 0 ; unsigned len = 0 ;

View file

@ -42,20 +42,21 @@
#include "route.h" #include "route.h"
/** Route Evaluator */ /** Route Evaluator */
class PartRouteEval : public eoEvalFunc <Route> { class PartRouteEval : public eoEvalFunc <Route>
{
public : public :
/** Constructor */ /** Constructor */
PartRouteEval (float __from, float __to) ; PartRouteEval (float __from, float __to) ;
void operator () (Route & __route) ; void operator () (Route & __route) ;
private : private :
float from, to ; float from, to ;
} ; } ;
#endif #endif

View file

@ -41,7 +41,8 @@
#include "partial_mapped_xover.h" #include "partial_mapped_xover.h"
#include "mix.h" #include "mix.h"
void PartialMappedXover :: repair (Route & __route, unsigned __cut1, unsigned __cut2) { void PartialMappedXover :: repair (Route & __route, unsigned __cut1, unsigned __cut2)
{
unsigned v [__route.size ()] ; // Number of times a cities are visited ... unsigned v [__route.size ()] ; // Number of times a cities are visited ...
@ -61,13 +62,15 @@ void PartialMappedXover :: repair (Route & __route, unsigned __cut1, unsigned __
for (unsigned i = 0 ; i < __route.size () ; i ++) for (unsigned i = 0 ; i < __route.size () ; i ++)
if (i < __cut1 || i >= __cut2) if (i < __cut1 || i >= __cut2)
if (v [__route [i]] > 1) { if (v [__route [i]] > 1)
{
__route [i] = vert.back () ; __route [i] = vert.back () ;
vert.pop_back () ; vert.pop_back () ;
} }
} }
bool PartialMappedXover :: operator () (Route & __route1, Route & __route2) { bool PartialMappedXover :: operator () (Route & __route1, Route & __route2)
{
unsigned cut1 = rng.random (__route1.size ()), cut2 = rng.random (__route2.size ()) ; unsigned cut1 = rng.random (__route1.size ()), cut2 = rng.random (__route2.size ()) ;

View file

@ -42,15 +42,16 @@
#include "route.h" #include "route.h"
/** Partial Mapped Crossover */ /** Partial Mapped Crossover */
class PartialMappedXover : public eoQuadOp <Route> { class PartialMappedXover : public eoQuadOp <Route>
{
public : public :
bool operator () (Route & __route1, Route & __route2) ; bool operator () (Route & __route1, Route & __route2) ;
private : private :
void repair (Route & __route, unsigned __cut1, unsigned __cut2) ; void repair (Route & __route, unsigned __cut1, unsigned __cut2) ;
} ; } ;
#endif #endif

View file

@ -36,7 +36,8 @@
#include "route.h" #include "route.h"
unsigned length (const Route & __route) { unsigned length (const Route & __route)
{
unsigned len = 0 ; unsigned len = 0 ;

Some files were not shown because too many files have changed in this diff Show more