particle-swarm-optimization main templates added

This commit is contained in:
tlegrand 2007-07-02 12:58:13 +00:00
commit bec7d02c50
33 changed files with 3733 additions and 0 deletions

203
eo/src/PO.h Normal file
View file

@ -0,0 +1,203 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// PO.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef PO_H
#define PO_H
//-----------------------------------------------------------------------------
#include <stdexcept>
#include <EO.h>
//-----------------------------------------------------------------------------
/** PO inheriting from EO is specially designed for PSO particle.POs have got a fitness,
which at the same time needs to be only an object with the operation less than (<)
defined. A best fitness also belongs to the particle.Fitness says how
good is the particle for a current iteration whereas the best fitness can be saved for
many iterations.
*/
template < class F > class PO:public EO < F >
{
public:
typedef typename PO < F >::Fitness Fitness;
/** Default constructor.
Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor.
*/
PO ():repFitness (Fitness ()), invalidFitness (true),
bestFitness (Fitness()){}
/// Return fitness value.
Fitness fitness () const
{
if (invalid ())
throw std::runtime_error ("invalid fitness in PO.h");
return repFitness;
}
/** Set fitness. At the same time, validates it.
* @param _fitness New fitness value.
*/
void fitness (const Fitness & _fitness)
{
repFitness = _fitness;
invalidFitness = false;
}
/** Return the best fitness.
* @return bestFitness
*/
Fitness best () const
{
if (invalid ())
throw std::runtime_error ("invalid best fitness in PO.h");
return bestFitness;
}
/** Set the best fitness.
* @param _bestFitness New best fitness found for the particle.
*/
void best (const Fitness & _bestFitness)
{
bestFitness = _bestFitness;
invalidBestFitness = false;
}
/** Return true If fitness value is invalid, false otherwise.
* @return true If fitness is invalid.
*/
bool invalid () const
{
return invalidFitness;
}
/** Invalidate the fitness.
* @return
*/
void invalidate ()
{
invalidFitness = true;
}
/** Return true If the best fitness value is invalid, false otherwise.
* @return true If the bestfitness is invalid.
*/
bool invalidBest () const
{
return invalidBestFitness;
}
/** Invalidate the best fitness.
* @return
*/
void invalidateBest ()
{
invalidBestFitness = true;
}
/** Return the class id.
* @return the class name as a std::string
*/
virtual std::string className () const
{
return "PO";
}
/** Returns true if
@return true if the fitness is higher
*/
bool operator< (const PO & _po2) const { return fitness () < _po2.fitness ();}
bool operator> (const PO & _po2) const { return !(fitness () <= _po2.fitness ());}
/**
* Write object. Called printOn since it prints the object _on_ a stream.
* @param _os A std::ostream.
*/
virtual void printOn(std::ostream& _os) const {
// the latest version of the code. Very similar to the old code
if (invalid()) {
_os << "INVALID ";
}
else
{
_os << repFitness << ' ' ;
}
if (invalidBest()) {
_os << "INVALID BEST";
}
else
{
_os << "best: " << bestFitness ;
}
}
/**
* Read object.\\
* Calls base class, just in case that one had something to do.
* The read and print methods should be compatible and have the same format.
* In principle, format is "plain": they just print a number
* @param _is a std::istream.
* @throw runtime_std::exception If a valid object can't be read.
*/
virtual void readFrom(std::istream& _is) {
// the new version of the reafFrom function.
// It can distinguish between valid and invalid fitness values.
std::string fitness_str;
int pos = _is.tellg();
_is >> fitness_str;
if (fitness_str == "INVALID")
{
invalidFitness = true;
}
else
{
invalidFitness = false;
_is.seekg(pos); // rewind
_is >> repFitness;
}
}
private:
Fitness repFitness; // value of fitness for this particle
bool invalidFitness; // true if the value of the fitness is invalid
Fitness bestFitness; // value of the best fitness found for the particle
bool invalidBestFitness; // true if the value of the best fitness is invalid
};
//-----------------------------------------------------------------------------
#endif /*PO_H */

42
eo/src/eoBinaryFlight.h Normal file
View file

@ -0,0 +1,42 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoBinaryFlight.h
// (c) OPAC Team, 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOBINARYFLIGHT_H
#define EOBINARYFLIGHT_H
//-----------------------------------------------------------------------------
#include <eoFlight.h>
//-----------------------------------------------------------------------------
/** Abstract class for binary flight. Positions are updated but are expected to be binary.
* A function must be used to decide, according to continuous velocities, of the
* new positions (0,1 ... ?)
*/
template < class POT > class eoBinaryFlight:public eoFlight < POT >{};
#endif /*EOBINARYFLIGHT_H */

48
eo/src/eoBitParticle.h Normal file
View file

@ -0,0 +1,48 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoBitParticle.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOBITPARTICLE_H
#define _EOBITPARTICLE_H
#include <eoVectorParticle.h>
/** eoBitParticle: Implementation of a bit-coded particle.
* Positions and best positions are 0 or 1 but the velocity is a vector of double.
*/
template < class FitT> class eoBitParticle: public eoVectorParticle<FitT,bool,double>
{
public:
eoBitParticle(unsigned size = 0, bool positions = 0,double velocities = 0.0,bool bestPositions = 0): eoVectorParticle<FitT, bool,double> (size, positions,velocities,bestPositions) {}
virtual std::string className() const
{
return "eoBitParticle";
}
};
#endif /*_EOBITPARTICLE_H*/

View file

@ -0,0 +1,208 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoConstrictedVariableWeightVelocity.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H
#define EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H
//-----------------------------------------------------------------------------
#include <eoVelocity.h>
#include <eoTopology.h>
#include <eoWeightUpdater.h>
#include <utils/eoRealVectorBounds.h>
#include <eoRealBoundModifier.h>
//-----------------------------------------------------------------------------
/** Inertia variable weighted based velocity performer + constriction. Derivated from abstract eoVelocity,
* At step t: v(t+1)= K * ( w*v(t) + c1*r1* (xbest(t)-x(t)) + c2*r2* (gbest(t) - x(t)))
* w is updated each time the velocity performer is called and K is fixed
* (ci given and Ri chosen at random in [0;1]).
*/
template < class POT > class eoConstrictedVariableWeightVelocity:public eoVelocity < POT >
{
public:
/*
* Each element for the velocity evaluation is expected to be of type VelocityType.
*/
typedef typename POT::ParticleVelocityType VelocityType;
/** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _boundsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
eoWeightUpdater<VelocityType> & _weightUpdater,
const VelocityType & _c1,
const VelocityType & _c2 ,
eoRealVectorBounds & _bounds,
eoRealBoundModifier & _bndsModifier,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
weightUpdater(_weightUpdater),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(_bndsModifier),
gen(_gen){}
/** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
eoWeightUpdater<VelocityType> & _weightUpdater,
const VelocityType & _c1,
const VelocityType & _c2,
eoRealVectorBounds & _bounds,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
weightUpdater(_weightUpdater),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(dummyModifier),
gen(_gen){}
/** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology to get the global/local/other best*
* @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
eoWeightUpdater<VelocityType> & _weightUpdater,
const VelocityType & _c1,
const VelocityType & _c2,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
weightUpdater(_weightUpdater),
c1 (_c1),
c2 (_c2),
bounds(*(new eoRealVectorNoBounds(0))),
bndsModifier(dummyModifier),
gen(_gen)
{}
/**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy)
* - update the weight with the weightUpdater (use the dummy updater if there's no updater provided)
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
* @param _po - A particle
* @param _indice - The indice (into the topology) of the given particle
*/
void operator () (POT & _po,unsigned _indice)
{
VelocityType r1;
VelocityType r2;
VelocityType newVelocity;
// cast the learning factors to VelocityType
r1 = (VelocityType) rng.uniform (1) * c1;
r2 = (VelocityType) rng.uniform (1) * c2;
// need to resize the bounds even if there are dummy because of "isBounded" call
bounds.adjust_size(_po.size());
// update the inertia weight
weightUpdater(weight);
// assign the new velocities
for (unsigned j = 0; j < _po.size (); j++)
{
newVelocity= coeff * (weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]));
/* modify the bounds */
bndsModifier(bounds,j);
/* check bounds */
if (bounds.isMinBounded(j))
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
if (bounds.isMaxBounded(j))
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
_po.velocities[j]=newVelocity;
}
}
/**
* Update the neighborhood.
*/
void updateNeighborhood(POT & _po,unsigned _indice)
{
topology.updateNeighborhood(_po,_indice);
}
protected:
eoTopology < POT > & topology;
const VelocityType & coeff; // the fixed constriction coefficient
eoWeightUpdater<VelocityType> & weightUpdater; // the updater used to make the weight evoluate
const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier;
VelocityType weight;
eoRng & gen; // the random generator
// If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier;
};
#endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/

View file

@ -0,0 +1,191 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoConstrictedVelocity.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOCONSTRICTEDVELOCITY_H
#define EOCONSTRICTEDVELOCITY_H
//-----------------------------------------------------------------------------
#include <eoFunctor.h>
#include <utils/eoRNG.h>
#include <eoPop.h>
#include <utils/eoRealVectorBounds.h>
#include <eoTopology.h>
//-----------------------------------------------------------------------------
/** Constricted velocity performer. Derivated from abstract eoVelocity,
* At step t+1 : v(t+1)= C * [ v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t)) ]
* C is fixed for all the particles and all the generations.
* Default C = 2 * k / abs(2 - P - sqrt (P*(P-4)))
* (ci and C given;P=c1*r1 + c2*r2 ; Ri chosen at random * in [0;1])
*/
template < class POT > class eoConstrictedVelocity:public eoVelocity < POT >
{
public:
/*
* Each element for the velocity evaluation is expected to be of type VelocityType.
*/
typedef typename POT::ParticleVelocityType VelocityType;
/** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _boundsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
const VelocityType & _c1,
const VelocityType & _c2 ,
eoRealVectorBounds & _bounds,
eoRealBoundModifier & _bndsModifier,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(_bndsModifier),
gen(_gen){}
/** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
const VelocityType & _c1,
const VelocityType & _c2,
eoRealVectorBounds & _bounds,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(dummyModifier),
gen(_gen){}
/** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng
*/
eoConstrictedVelocity (eoTopology < POT > & _topology,
const VelocityType & _coeff,
const VelocityType & _c1,
const VelocityType & _c2,
eoRng & _gen = rng):
topology(_topology),
coeff(_coeff),
c1 (_c1),
c2 (_c2),
bounds(*(new eoRealVectorNoBounds(0))),
bndsModifier(dummyModifier),
gen(_gen){}
/**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy)
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
* @param _po - A particle
* @param _indice - The indice (into the topology) of the given particle
*/
void operator () (POT & _po,unsigned _indice)
{
VelocityType r1;
VelocityType r2;
VelocityType newVelocity;
// cast the learning factors to VelocityType
r1 = (VelocityType) rng.uniform (1) * c1;
r2 = (VelocityType) rng.uniform (1) * c2;
// need to resize the bounds even if there are dummy because of "isBounded" call
bounds.adjust_size(_po.size());
// assign the new velocities
for (unsigned j = 0; j < _po.size (); j++)
{
newVelocity= coeff * (_po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]));
/* modify the bounds */
bndsModifier(bounds,j);
/* check bounds */
if (bounds.isMinBounded(j))
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
if (bounds.isMaxBounded(j))
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
_po.velocities[j]=newVelocity;
}
}
/**
* Update the neighborhood of a particle.
*/
void updateNeighborhood(POT & _po,unsigned _indice)
{
topology.updateNeighborhood(_po,_indice);
}
protected:
eoTopology < POT > & topology;
const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2
const VelocityType & coeff; // the fixed constriction coefficient
eoRng & gen; // the random generator
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier;
// If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier;
};
#endif /*EOCONSTRICTEDVELOCITY_H */

51
eo/src/eoDummyFlight.h Normal file
View file

@ -0,0 +1,51 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoDummyFlight.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EODUMMYFLIGHT_H
#define EODUMMYFLIGHT_H
//-----------------------------------------------------------------------------
#include <eoFlight.h>
//-----------------------------------------------------------------------------
/**
* A dummy flight that does nothing !
*/
template < class POT > class eoDummyFlight:public eoFlight < POT >
{
public:
// Ctor
eoDummyFlight () {}
/**
* Dummy move: do nothing
*/
void operator () (POT & _po1) {}
};
#endif /*EODUMMYFLIGHT_H */

129
eo/src/eoEasyPSO.h Normal file
View file

@ -0,0 +1,129 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEasyPSO.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOEASYPSO_H
#define _EOEASYPSO_H
//-----------------------------------------------------------------------------
#include <eoContinue.h>
#include <eoPSO.h>
#include <eoVelocity.h>
#include <eoFlight.h>
#include <eoDummyFlight.h>
//-----------------------------------------------------------------------------
/** An easy-to-use particle swarm algorithm; you can use any particle,
* any flight, any topology... The main steps are :
* (The population is expected to be already evaluated)
* - for each generation and each particle pi
* - evaluate the velocities
* -- perform the fligth of pi
* -- evaluate pi
* -- update the neighborhoods
*/
template < class POT > class eoEasyPSO:public eoPSO < POT >
{
public:
/** Full constructor
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _velocity - An eoVelocity that defines how to compute the velocities
* @param _flight - An eoFlight that defines how to make the particle flying: that means how
* to modify the positions according to the velocities
*/
eoEasyPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
eoVelocity < POT > &_velocity,
eoFlight < POT > &_flight):
continuator (_continuator),
eval (_eval),
velocity (_velocity),
flight (_flight){}
/** Constructor without eoFlight. For special cases when the flight is performed withing the velocity.
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _velocity - An eoVelocity that defines how to compute the velocities
*/
eoEasyPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
eoVelocity < POT > &_velocity):
continuator (_continuator),
eval (_eval),
velocity (_velocity),
flight (dummyFlight){}
/// Apply a few iteration of flight to the population (=swarm).
virtual void operator () (eoPop < POT > &_pop)
{
try
{
do
{
// loop over all the particles for the current iteration
for (unsigned idx = 0; idx < _pop.size (); idx++)
{
// perform velocity evaluation
velocity (_pop[idx],idx);
// apply the flight
flight (_pop[idx]);
// evaluate the position
eval (_pop[idx]);
// update the topology (particle and local/global best(s))
velocity.updateNeighborhood(_pop[idx],idx);
}
}while (continuator (_pop));
}
catch (std::exception & e)
{
std::string s = e.what ();
s.append (" in eoEasyPSO");
throw std::runtime_error (s);
}
}
private:
eoContinue < POT > &continuator;
eoEvalFunc < POT > &eval;
eoVelocity < POT > &velocity;
eoFlight < POT > &flight;
// if the flight does not need to be used, use the dummy flight instance
eoDummyFlight<POT> dummyFlight;
};
#endif /*_EOEASYPSO_H*/

View file

@ -0,0 +1,190 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoFixedInertiaWeightedVelocity.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOFIXEDINERTIAWEIGHTEDVELOCITY_H
#define EOFIXEDINERTIAWEIGHTEDVELOCITY_H
//-----------------------------------------------------------------------------
#include <eoFunctor.h>
#include <utils/eoRNG.h>
#include <eoPop.h>
#include <utils/eoRealVectorBounds.h>
#include <eoTopology.h>
//-----------------------------------------------------------------------------
/** Inertia weight based velocity performer. Derivated from abstract eoVelocity,
* At step t+1 : v(t+1)= w * v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t))
* w is fixed for all the particles and all the generations.
* (ci and w given; Ri chosen at random * in [0;1])
*/
template < class POT > class eoFixedInertiaWeightedVelocity:public eoVelocity < POT >
{
public:
/*
* Each element for the velocity evaluation is expected to be of type VelocityType.
*/
typedef typename POT::ParticleVelocityType VelocityType;
/** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _boundsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng
*/
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
const VelocityType & _weight,
const VelocityType & _c1,
const VelocityType & _c2 ,
eoRealVectorBounds & _bounds,
eoRealBoundModifier & _bndsModifier,
eoRng & _gen = rng):
topology(_topology),
weight(_weight),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(_bndsModifier),
gen(_gen){}
/** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng
*/
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
const VelocityType & _weight,
const VelocityType & _c1,
const VelocityType & _c2,
eoRealVectorBounds & _bounds,
eoRng & _gen = rng):
topology(_topology),
weight(_weight),
c1 (_c1),
c2 (_c2),
bounds(_bounds),
bndsModifier(dummyModifier),
gen(_gen){}
/** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng
*/
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
const VelocityType & _weight,
const VelocityType & _c1,
const VelocityType & _c2,
eoRng & _gen = rng):
topology(_topology),
weight(_weight),
c1 (_c1),
c2 (_c2),
bounds(*(new eoRealVectorNoBounds(0))),
bndsModifier(dummyModifier),
gen(_gen)
{}
/**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy)
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
* @param _po - A particle
* @param _indice - The indice (into the topology) of the given particle
*/
void operator () (POT & _po,unsigned _indice)
{
VelocityType r1;
VelocityType r2;
VelocityType newVelocity;
// cast the learning factors to VelocityType
r1 = (VelocityType) rng.uniform (1) * c1;
r2 = (VelocityType) rng.uniform (1) * c2;
// need to resize the bounds even if there are dummy because of "isBounded" call
bounds.adjust_size(_po.size());
// assign the new velocities
for (unsigned j = 0; j < _po.size (); j++)
{
newVelocity= weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]);
/* modify the bounds */
bndsModifier(bounds,j);
/* check bounds */
if (bounds.isMinBounded(j))
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
if (bounds.isMaxBounded(j))
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
_po.velocities[j]=newVelocity;
}
}
/**
* Update the neighborhood.
*/
void updateNeighborhood(POT & _po,unsigned _indice)
{
topology.updateNeighborhood(_po,_indice);
}
protected:
eoTopology < POT > & topology;
const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2
const VelocityType & weight; // the fixed weight
eoRng & gen; // the random generator
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier;
// If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier;
};
#endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */

54
eo/src/eoFlight.h Normal file
View file

@ -0,0 +1,54 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoFlight.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOFLIGHT_H
#define EOFLIGHT_H
//-----------------------------------------------------------------------------
#include <eoFunctor.h>
#include <utils/eoRealVectorBounds.h>
//-----------------------------------------------------------------------------
/** Abstract class for PSO flight.
* All the flights must derivated from eoFlight.
*/
template < class POT > class eoFlight:public eoUF < POT &, void >
{
public:
/**
* Apply the flight to a whole population.
*/
virtual void apply (eoPop < POT > &_pop)
{
for (unsigned i = 0; i < _pop.size (); i++)
{
operator ()(_pop[i]);
}
}
};
#endif /*EOFLIGHT_H */

View file

@ -0,0 +1,68 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoGaussRealWeightUp.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOGAUSSREALWEIGHTUP_H
#define EOGAUSSREALWEIGHTUP_H
//-----------------------------------------------------------------------------
#include <eoWeightUpdater.h>
#include <utils/eoRNG.h>
//-----------------------------------------------------------------------------
/**
* Update an inertia weight by assigning it a Gaussian randomized value.
*/
class eoGaussRealWeightUp:public eoWeightUpdater<double>
{
public:
/**
* Default constructor
* @param _mean - Mean for Gaussian distribution
* @param _stdev - Standard deviation for Gaussian distribution
*/
eoGaussRealWeightUp(
double _mean=0,
double _stdev=1.0
):mean(_mean),stdev(_stdev){}
/**
* Assign Gaussian deviation to _weight
* @param _weight - The modified weight as a double
*/
void operator() (double & _weight)
{
_weight=rng.normal(mean,stdev);
}
protected:
double mean,stdev;
};
#endif/*EOGAUSSREALWEIGHTUP_H*/

184
eo/src/eoLSPSO.h Normal file
View file

@ -0,0 +1,184 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoLSPSO.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOLSPSO_H
#define _EOLSPSO_H
//-----------------------------------------------------------------------------
#include <eoPSO.h>
#include <eoContinue.h>
#include <eoStandardFlight.h>
#include <eoLinearTopology.h>
#include <eoStandardVelocity.h>
#include <utils/eoRealVectorBounds.h>
#include <eoRealBoundModifier.h>
//-----------------------------------------------------------------------------
/**
* A Linear ("L"inear topology) Standard ("S"tandard velocity) PSO.
* You can use it with or without bounds on the velocity.
* No bound for the flight (no bounds for the positions).
*
*/
template < class POT > class eoLSPSO:public eoPSO < POT >
{
public:
typedef typename POT::ParticleVelocityType VelocityType;
/** Full constructor
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _neighborhoodSize - The size of each neighborhood of the linear topology
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _boundsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only)
*/
eoLSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2 ,
const unsigned _neighborhoodSize,
eoRealVectorBounds & _bounds,
eoRealBoundModifier & _bndsModifier):
continuator (_continuator),
eval (_eval),
topology(eoLinearTopology<POT>(_neighborhoodSize)),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2,_bounds,_bndsModifier)),
neighborhoodSize(_neighborhoodSize),
bounds(_bounds),
boundsModifier(_bndsModifier)
{}
/** Constructor without bound modifier.
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _neighborhoodSize - The size of each neighborhood of the linear topology
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
*/
eoLSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2 ,
const unsigned _neighborhoodSize,
eoRealVectorBounds & _bounds):
continuator (_continuator),
eval (_eval),
topology(eoLinearTopology<POT>(_neighborhoodSize)),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2,_bounds)),
neighborhoodSize(_neighborhoodSize),
bounds(_bounds),
boundsModifier(dummyModifier)
{}
/** Constructor without bounds nor bound modifier.
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _neighborhoodSize - The size of each neighborhood of the linear topology
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
*/
eoLSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2,
const unsigned _neighborhoodSize):
continuator (_continuator),
eval (_eval),
topology(eoLinearTopology<POT>(_neighborhoodSize)),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2)),
neighborhoodSize(_neighborhoodSize),
bounds(*(new eoRealVectorNoBounds(0))),
boundsModifier(dummyModifier)
{}
/// Apply a few iteration of flight to the population (=swarm).
virtual void operator () (eoPop < POT > &_pop)
{
try
{
// setup the topology (done once)
topology.setup(_pop);
do
{
// loop over all the particles for the current iteration
for (unsigned idx = 0; idx < _pop.size (); idx++)
{
// perform velocity evaluation
velocity (_pop[idx],idx);
// apply the flight
flight (_pop[idx]);
// evaluate the position
eval (_pop[idx]);
// update the topology (particle and the global bests)
velocity.updateNeighborhood(_pop[idx],idx);
}
} while (continuator (_pop));
}catch (std::exception & e)
{
std::string s = e.what ();
s.append (" in eoLSPSO");
throw std::runtime_error (s);
}
}
protected:
eoContinue < POT > &continuator;
eoEvalFunc < POT > &eval;
eoStandardVelocity < POT > velocity;
eoStandardFlight < POT > flight;
const unsigned neighborhoodSize;
eoLinearTopology<POT> topology;
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & boundsModifier;
// If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier;
};
#endif /*_EOLSPSO_H*/

View file

@ -0,0 +1,75 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoLinearDecreasingWeightUp.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOLINEARDECREASINGWEIGHTUP_H
#define EOLINEARDECREASINGWEIGHTUP_H
//-----------------------------------------------------------------------------
#include <eoWeightUpdater.h>
//-----------------------------------------------------------------------------
/**
* Linear (inertia) weight updater. Update a weight according to:
* w(t)=(w(0)-w(Nt))*(Nt -t)/Nt + w(Nt) where
* t is the current generation/event
* Nt is the total number of generations/event
* w(0) is the initial weight
* w(Nt) is the last inertia weight
*/
template <class WeightType, class StopCriteriaType> class eoLinearDecreasingWeightUp:public eoWeightUpdater<WeightType>
{
public:
/**
* Ctor
*/
eoLinearDecreasingWeightUp(
const StopCriteriaType & _stop,
const WeightType & _initialValue,
const WeightType & _finalValue,
eoValueParam<StopCriteriaType> & _counter):
stop(_stop),
initialValue(_initialValue),
finalValue(_finalValue),
counter(_counter){}
/**
* Update the given weight
*/
void operator() (WeightType & _weight)
{
_weight=(initialValue-finalValue)* (WeightType)(stop-counter.value())/(WeightType)stop + finalValue;
}
protected:
const StopCriteriaType & stop;
const WeightType & initialValue,finalValue;
eoValueParam<StopCriteriaType> & counter; // a counter of the number of past events (should say "generations")
};
#endif/*EOLINEARDECREASINGWEIGHTUP_H*/

199
eo/src/eoLinearTopology.h Normal file
View file

@ -0,0 +1,199 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoLinearTopology.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOLINEARTOPOLOGY_H_
#define EOLINEARTOPOLOGY_H_
//-----------------------------------------------------------------------------
#include <eoPop.h>
#include <eoTopology.h>
#include <eoSocialNeighborhood.h>
//-----------------------------------------------------------------------------
/**
* One of the local best strategies. Each particle has a fixed number of neighbours, ans
* the neighborhood is social.
* The topology is never modified during the flight.
*/
template < class POT > class eoLinearTopology:public eoTopology <
POT >
{
public:
/**
* Build the topology made of _neighborhoodSize neighborhoods.
* @param _neighborhoods - The size of each neighborhood.
*/
eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){}
/**
* Build the neighborhoods contained in the topology.
* @param _pop - The population used to build the neighborhoods.
* If it remains several particle (because _pop.size()%neighborhoodSize !=0), there are inserted
* in the last neighborhood. So it may be possible to have a bigger neighborhood.
*/
void setup(const eoPop<POT> & _pop)
{
if (!isSetup)
{
// consitency check
if (neighborhoodSize >= _pop.size()){
std::string s;
s.append (" Invalid neighborhood size in eoLinearTopology ");
throw std::runtime_error (s);
}
unsigned howManyNeighborhood=_pop.size()/ neighborhoodSize;
// build all the neighborhoods
for (unsigned i=0;i< howManyNeighborhood;i++)
{
eoSocialNeighborhood<POT> currentNghd;
currentNghd.best(_pop[i*neighborhoodSize]);
for (unsigned k=i*neighborhoodSize;k < neighborhoodSize*(i+1);k++)
{
currentNghd.put(k);
if (_pop[k].fitness() > currentNghd.best().fitness())
currentNghd.best(_pop[k]);
}
neighborhoods.push_back(currentNghd);
}
// assign the last neighborhood to the remaining particles
if (_pop.size()%neighborhoodSize !=0)
{
for (unsigned z=_pop.size()-1;z >= (_pop.size()-_pop.size()%neighborhoodSize);z--){
neighborhoods.back().put(z);
if (_pop[z].fitness() > neighborhoods.back().best().fitness())
neighborhoods.back().best(_pop[z]);
}
}
isSetup=true;
}
else
{
// Should activate this part ?
/*
std::string s;
s.append (" Linear topology already setup in eoLinearTopology");
throw std::runtime_error (s);
*/
}
}
/**
* Retrieve the neighboorhood of a particle.
* @return _indice - The particle indice (in the population)
*/
unsigned retrieveNeighborhoodByIndice(unsigned _indice)
{
unsigned i=0;
for (i=0;i< neighborhoods.size();i++)
{
if (neighborhoods[i].contains(_indice))
{
return i;
}
}
return i;
}
/**
* Update the neighborhood: update the particle's best fitness and the best particle
* of the corresponding neighborhood.
*/
void updateNeighborhood(POT & _po,unsigned _indice)
{
// update the best fitness of the particle
if (_po.fitness() > _po.best())
{
_po.best(_po.fitness());
}
// update the best in its neighborhood
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
if (_po.fitness() > neighborhoods[theGoodNhbd].best().fitness())
{
neighborhoods[theGoodNhbd].best(_po);
}
}
/**
* Return the best informative of a particle. Could be itself.
* @param _indice - The indice of a particle in the population
* @return POT & - The best particle in the neighborhood of the particle whose indice is _indice
*/
POT & best (unsigned _indice)
{
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
return (neighborhoods[theGoodNhbd].best());
}
/**
* Print the structure of the topology on the standrad output.
*/
void printOn()
{
for (unsigned i=0;i< neighborhoods.size();i++)
{
std::cout << "{ " ;
for (unsigned j=0;j< neighborhoods[i].size();j++)
{
std::cout << neighborhoods[i].get(j) << " ";
}
std::cout << "}" << std::endl;
}
}
protected:
std::vector<eoSocialNeighborhood<POT> > neighborhoods;
unsigned neighborhoodSize; // the size of each neighborhood
bool isSetup;
};
#endif /*EOLINEARTOPOLOGY_H_ */

66
eo/src/eoNeighborhood.h Normal file
View file

@ -0,0 +1,66 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoNeighborhood.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EONEIGHBORHOOD_H_
#define EONEIGHBORHOOD_H_
/**
* Abstract class for neighborboods. Used for particle swarm optimization
* topology strategies. Can be social or physical.
*/
template < class POT > class eoNeighborhood
{
public:
virtual void put(unsigned _oneIndice)=0;
virtual bool contains(unsigned _oneIndice)=0;
virtual unsigned size()=0;
virtual unsigned get(unsigned _index)=0;
virtual POT & best()=0;
virtual void best(POT _particle)=0;
/// Virtual dtor
virtual ~eoNeighborhood() {};
};
#endif /* EONEIGHBORHOOD_H_ */

40
eo/src/eoPSO.h Normal file
View file

@ -0,0 +1,40 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoPSO.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOPSO_H
#define _EOPSO_H
//-----------------------------------------------------------------------------
#include <eoAlgo.h>
//-----------------------------------------------------------------------------
/**
This is a generic class for particle swarm algorithms. There
is only one operator defined, which takes a population and does stuff to
it. It needn't be a complete algorithm, can be also a step of an
algorithm. Only used for mono-objective cases.
*/
template < class POT > class eoPSO:public eoAlgo < POT >{};
#endif /*_EOPSO_H*/

View file

@ -0,0 +1,77 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoParticleBestInit.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOPARTICLEBESTINIT_H
#define _EOPARTICLEBESTINIT_H
//-----------------------------------------------------------------------------
#include <eoFunctor.h>
//-----------------------------------------------------------------------------
/**
* Abstract class for particle best position initialization.
*/
template < class POT > class eoParticleBestInit:public eoUF < POT &, void >
{
public:
/** Apply the initialization to a whole given population */
virtual void apply (eoPop < POT > &_pop)
{
for (unsigned i = 0; i < _pop.size (); i++)
{
operator ()(_pop[i]);
}
}
};
/**
* Initializes the best positions of a particle as its current positions and set the
* particle best fitness.
*/
template < class POT > class eoFirstIsBestInit:public eoParticleBestInit <POT>
{
public:
/** Default CTor */
eoFirstIsBestInit (){}
void operator () (POT & _po1)
{
for (unsigned i = 0; i < _po1.size (); i++)
_po1.bestPositions[i] = _po1[i];
// set the fitness
_po1.best(_po1.fitness());
}
};
#endif /*_EOPARTICLEBESTINIT_H */

View file

@ -0,0 +1,76 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRandomRealWeightUp.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EORANDOMREALWEIGHTUP_H
#define EORANDOMREALWEIGHTUP_H
//-----------------------------------------------------------------------------
#include <eoWeightUpdater.h>
#include <utils/eoRNG.h>
//-----------------------------------------------------------------------------
/**
* Update an inertia weight by assigning it an (uniform) random value.
*/
class eoRandomRealWeightUp:public eoWeightUpdater<double>
{
public:
/**
* Default constructor
* @param _min - The minimum bound for the weight
* @param _max - The maximum bound for the weight
*/
eoRandomRealWeightUp(
double _min,
double _max
):min(_min),max(_max)
{
// consistency check
if (min > max)
{
std::string s;
s.append (" min > max in eoRandomRealWeightUp");
throw std::runtime_error (s);
}
}
/**
* Generate an real random number in [min,max] and assign it to _weight
* @param _weight - The assigned (real) weight
*/
void operator() (double & _weight)
{
_weight=rng.uniform(max-min)+min;
}
protected:
double min,max;
};
#endif/*EORANDOMREALWEIGHTUP_H*/

View file

@ -0,0 +1,97 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRealBoundModifier.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef EOREALBOUNDMODIFIER_H
#define EOREALBOUNDMODIFIER_H
//-----------------------------------------------------------------------------
#include <eoFunctor.h>
#include <utils/eoRealVectorBounds.h>
//-----------------------------------------------------------------------------
/**
* Abstract class for eoRealVectorBounds modifier.
* Used to modify the bounds included into the eoRealVectorBounds object.
*/
class eoRealBoundModifier: public eoBF < eoRealBaseVectorBounds &,unsigned,void > {};
/**
* An eoRealBoundModifier that modify nothing !
*/
class eoDummyRealBoundModifier: public eoRealBoundModifier
{
public:
eoDummyRealBoundModifier (){}
void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i){}
};
/**
* Modify an eoReal(Base)VectorBounds :
* At iteration t, the interval I(t)=[min,max] is updated as:
* I(t)=[min,(1-(t/Nt)^alpha)*max] where
* - t, the current iteration, is given with an eoValueParam<unsigned>
* - Nt is the stopping criteria <=> the total number of iterations
* - alpha a coefficient
*
*/
class eoExpDecayingBoundModifier: public eoRealBoundModifier
{
public:
/**
* Constructor
* @param _stopCriteria - The total number of iterations
* @param _alpha
* @param _genCounter - An eoValueParam<unsigned> that gives the current iteration
*/
eoExpDecayingBoundModifier (unsigned _stopCriteria,
double _alpha,
eoValueParam<unsigned> & _genCounter):
stopCriteria(_stopCriteria),
alpha(_alpha),
genCounter(_genCounter){}
void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i)
{
double newMaxBound=(1-pow((double)genCounter.value()/stopCriteria,alpha))*_bnds.maximum(_i);
// should delete the old eoRealBounds ?
_bnds[_i]=new eoRealInterval(_bnds.minimum(_i),std::max(_bnds.minimum(_i),newMaxBound));
}
protected:
unsigned stopCriteria;
double alpha;
eoValueParam<unsigned> & genCounter;
};
#endif/*EOREALBOUNDMODIFIER_H*/

47
eo/src/eoRealParticle.h Normal file
View file

@ -0,0 +1,47 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRealParticle.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOREALPARTICLE_H
#define _EOREALPARTICLE_H
#include <eoVectorParticle.h>
/** eoRealParticle: Implementation of a real-coded particle. Positions, velocities and best positions are real-coded.
*/
template < class FitT> class eoRealParticle: public eoVectorParticle<FitT,double,double>
{
public:
eoRealParticle(unsigned size = 0, double positions = 0.0,double velocities = 0.0,double bestPositions = 0.0): eoVectorParticle<FitT, double,double> (size, positions,velocities,bestPositions) {}
virtual std::string className() const
{
return "eoRealParticle";
}
};
#endif /*_EOREALPARTICLE_H*/

168
eo/src/eoSSPSO.h Normal file
View file

@ -0,0 +1,168 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSSPSO.h
// (c) OPAC 2007
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOSSPSO_H
#define _EOSSPSO_H
//-----------------------------------------------------------------------------
#include <eoPSO.h>
#include <eoContinue.h>
#include <eoStandardFlight.h>
#include <eoStarTopology.h>
#include <eoStandardVelocity.h>
#include <utils/eoRealVectorBounds.h>
#include <eoRealBoundModifier.h>
//-----------------------------------------------------------------------------
/**
* A Star ("S"tar topology) Standard ("S"tandard velocity) PSO.
* You can use it with or without bounds on the velocity.
* No bound for the flight (no bounds for the positions).
*
*/
template < class POT > class eoSSPSO:public eoPSO < POT >
{
public:
typedef typename POT::ParticleVelocityType VelocityType;
/** Full constructor
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _boundsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only)
*/
eoSSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2 ,
eoRealVectorBounds & _bounds,
eoRealBoundModifier & _bndsModifier):
continuator (_continuator),
eval (_eval),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2,_bounds,_bndsModifier)),
bounds(_bounds),
boundsModifier(_bndsModifier)
{}
/** Constructor without bound modifier.
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
*/
eoSSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2 ,
eoRealVectorBounds & _bounds):
continuator (_continuator),
eval (_eval),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2,_bounds)),
bounds(_bounds),
boundsModifier(dummyModifier)
{}
/** Constructor without bounds nor bound modifier.
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
*/
eoSSPSO (
eoContinue < POT > &_continuator,
eoEvalFunc < POT > &_eval,
const VelocityType & _c1,
const VelocityType & _c2):
continuator (_continuator),
eval (_eval),
velocity(eoStandardVelocity<POT>(topology,_c1,_c2)),
bounds(*(new eoRealVectorNoBounds(0))),
boundsModifier(dummyModifier)
{}
/// Apply a few iteration of flight to the population (=swarm).
virtual void operator () (eoPop < POT > &_pop)
{
try
{
// setup the topology (done once)
topology.setup(_pop);
do
{
// loop over all the particles for the current iteration
for (unsigned idx = 0; idx < _pop.size (); idx++)
{
// perform velocity evaluation
velocity (_pop[idx],idx);
// apply the flight
flight (_pop[idx]);
// evaluate the position
eval (_pop[idx]);
// update the topology (particle and the global bests)
velocity.updateNeighborhood(_pop[idx],idx);
}
} while (continuator (_pop));
}catch (std::exception & e)
{
std::string s = e.what ();
s.append (" in eoSSPSO");
throw std::runtime_error (s);
}
}
protected:
eoContinue < POT > &continuator;
eoEvalFunc < POT > &eval;
eoStandardVelocity < POT > velocity;
eoStandardFlight < POT > flight;
eoStarTopology<POT> topology;
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & boundsModifier;
// If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier;
};
#endif /*_EOSSPSO_H*/

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