indent all

git-svn-id: svn://scm.gforge.inria.fr/svnroot/paradiseo@232 331e1502-861f-0410-8da2-ba01fb791d7f
This commit is contained in:
liefooga 2007-04-13 15:05:07 +00:00
commit c8049ca6cd
51 changed files with 3899 additions and 3898 deletions

View file

@ -24,264 +24,264 @@
* The template argument MOEOFitness is an object reflecting the quality of the solution in term of convergence (the fitness of a solution is always to be maximized).
* The template argument MOEODiversity is an object reflecting the quality of the solution in term of diversity (the diversity of a solution is always to be maximized).
* All template arguments must have a void and a copy constructor.
* Besides, note that, contrary to the mono-objective case (and to EO) where the fitness value of a solution is confused with its objective value,
* Besides, note that, contrary to the mono-objective case (and to EO) where the fitness value of a solution is confused with its objective value,
* the fitness value differs of the objectives values in the multi-objective case.
*/
template < class MOEOObjectiveVector, class MOEOFitness, class MOEODiversity >
template < class MOEOObjectiveVector, class MOEOFitness, class MOEODiversity >
class MOEO : public EO < MOEOObjectiveVector >
{
public:
/** the objective vector type of a solution */
typedef MOEOObjectiveVector ObjectiveVector;
/** the fitness type of a solution */
typedef MOEOFitness Fitness;
/** the diversity type of a solution */
typedef MOEODiversity Diversity;
/**
* Ctor
*/
MOEO()
{
// default values for every parameters
objectiveVectorValue = ObjectiveVector();
fitnessValue = Fitness();
diversityValue = Diversity();
// invalidate all
invalidate();
}
/**
* Virtual dtor
*/
virtual ~MOEO() {};
/**
* Returns the objective vector of the current solution
*/
ObjectiveVector objectiveVector() const
{
if ( invalidObjectiveVector() )
{
throw std::runtime_error("invalid objective vector");
}
return objectiveVectorValue;
}
/**
* Sets the objective vector of the current solution
* @param _objectiveVectorValue the new objective vector
*/
void objectiveVector(const ObjectiveVector & _objectiveVectorValue)
{
objectiveVectorValue = _objectiveVectorValue;
invalidObjectiveVectorValue = false;
}
/**
* Sets the objective vector as invalid
*/
void invalidateObjectiveVector()
{
invalidObjectiveVectorValue = true;
}
/**
* Returns true if the objective vector is invalid, false otherwise
*/
bool invalidObjectiveVector() const
{
return invalidObjectiveVectorValue;
}
/**
* Returns the fitness value of the current solution
*/
Fitness fitness() const
{
if ( invalidFitness() )
{
throw std::runtime_error("invalid fitness (MOEO)");
}
return fitnessValue;
}
/**
* Sets the fitness value of the current solution
* @param _fitnessValue the new fitness value
*/
void fitness(const Fitness & _fitnessValue)
{
fitnessValue = _fitnessValue;
invalidFitnessValue = false;
}
/**
* Sets the fitness value as invalid
*/
void invalidateFitness()
{
invalidFitnessValue = true;
}
/**
* Returns true if the fitness value is invalid, false otherwise
*/
bool invalidFitness() const
{
return invalidFitnessValue;
}
/**
* Returns the diversity value of the current solution
*/
Diversity diversity() const
{
if ( invalidDiversity() )
{
throw std::runtime_error("invalid diversity");
}
return diversityValue;
}
/**
* Sets the diversity value of the current solution
* @param _diversityValue the new diversity value
*/
void diversity(const Diversity & _diversityValue)
{
diversityValue = _diversityValue;
invalidDiversityValue = false;
}
/**
* Sets the diversity value as invalid
*/
void invalidateDiversity()
{
invalidDiversityValue = true;
}
/**
* Returns true if the diversity value is invalid, false otherwise
*/
bool invalidDiversity() const
{
return invalidDiversityValue;
}
/**
* Sets the objective vector, the fitness value and the diversity value as invalid
*/
void invalidate()
{
invalidateObjectiveVector();
invalidateFitness();
invalidateDiversity();
}
/**
* Returns true if the fitness value is invalid, false otherwise
*/
bool invalid() const
{
return invalidObjectiveVector();
}
/**
* Returns true if the objective vector of the current solution is smaller than the objective vector of _other on the first objective,
* then on the second, and so on (can be usefull for sorting/printing).
* You should implement another function in the sub-class of MOEO to have another sorting mecanism.
* @param _other the other MOEO object to compare with
*/
bool operator<(const MOEO & _other) const
{
return objectiveVector() < _other.objectiveVector();
}
/**
* Return the class id (the class name as a std::string)
*/
virtual std::string className() const
{
return "MOEO";
}
/**
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
{
if ( invalidObjectiveVector() )
{
_os << "INVALID\t";
}
else
{
_os << objectiveVectorValue << '\t';
}
}
/**
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
{
std::string objectiveVector_str;
int pos = _is.tellg();
_is >> objectiveVector_str;
if (objectiveVector_str == "INVALID")
{
invalidateObjectiveVector();
}
else
{
invalidObjectiveVectorValue = false;
_is.seekg(pos); // rewind
_is >> objectiveVectorValue;
}
}
/** the objective vector type of a solution */
typedef MOEOObjectiveVector ObjectiveVector;
/** the fitness type of a solution */
typedef MOEOFitness Fitness;
/** the diversity type of a solution */
typedef MOEODiversity Diversity;
/**
* Ctor
*/
MOEO()
{
// default values for every parameters
objectiveVectorValue = ObjectiveVector();
fitnessValue = Fitness();
diversityValue = Diversity();
// invalidate all
invalidate();
}
/**
* Virtual dtor
*/
virtual ~MOEO() {};
/**
* Returns the objective vector of the current solution
*/
ObjectiveVector objectiveVector() const
{
if ( invalidObjectiveVector() )
{
throw std::runtime_error("invalid objective vector");
}
return objectiveVectorValue;
}
/**
* Sets the objective vector of the current solution
* @param _objectiveVectorValue the new objective vector
*/
void objectiveVector(const ObjectiveVector & _objectiveVectorValue)
{
objectiveVectorValue = _objectiveVectorValue;
invalidObjectiveVectorValue = false;
}
/**
* Sets the objective vector as invalid
*/
void invalidateObjectiveVector()
{
invalidObjectiveVectorValue = true;
}
/**
* Returns true if the objective vector is invalid, false otherwise
*/
bool invalidObjectiveVector() const
{
return invalidObjectiveVectorValue;
}
/**
* Returns the fitness value of the current solution
*/
Fitness fitness() const
{
if ( invalidFitness() )
{
throw std::runtime_error("invalid fitness (MOEO)");
}
return fitnessValue;
}
/**
* Sets the fitness value of the current solution
* @param _fitnessValue the new fitness value
*/
void fitness(const Fitness & _fitnessValue)
{
fitnessValue = _fitnessValue;
invalidFitnessValue = false;
}
/**
* Sets the fitness value as invalid
*/
void invalidateFitness()
{
invalidFitnessValue = true;
}
/**
* Returns true if the fitness value is invalid, false otherwise
*/
bool invalidFitness() const
{
return invalidFitnessValue;
}
/**
* Returns the diversity value of the current solution
*/
Diversity diversity() const
{
if ( invalidDiversity() )
{
throw std::runtime_error("invalid diversity");
}
return diversityValue;
}
/**
* Sets the diversity value of the current solution
* @param _diversityValue the new diversity value
*/
void diversity(const Diversity & _diversityValue)
{
diversityValue = _diversityValue;
invalidDiversityValue = false;
}
/**
* Sets the diversity value as invalid
*/
void invalidateDiversity()
{
invalidDiversityValue = true;
}
/**
* Returns true if the diversity value is invalid, false otherwise
*/
bool invalidDiversity() const
{
return invalidDiversityValue;
}
/**
* Sets the objective vector, the fitness value and the diversity value as invalid
*/
void invalidate()
{
invalidateObjectiveVector();
invalidateFitness();
invalidateDiversity();
}
/**
* Returns true if the fitness value is invalid, false otherwise
*/
bool invalid() const
{
return invalidObjectiveVector();
}
/**
* Returns true if the objective vector of the current solution is smaller than the objective vector of _other on the first objective,
* then on the second, and so on (can be usefull for sorting/printing).
* You should implement another function in the sub-class of MOEO to have another sorting mecanism.
* @param _other the other MOEO object to compare with
*/
bool operator<(const MOEO & _other) const
{
return objectiveVector() < _other.objectiveVector();
}
/**
* Return the class id (the class name as a std::string)
*/
virtual std::string className() const
{
return "MOEO";
}
/**
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
{
if ( invalidObjectiveVector() )
{
_os << "INVALID\t";
}
else
{
_os << objectiveVectorValue << '\t';
}
}
/**
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
{
std::string objectiveVector_str;
int pos = _is.tellg();
_is >> objectiveVector_str;
if (objectiveVector_str == "INVALID")
{
invalidateObjectiveVector();
}
else
{
invalidObjectiveVectorValue = false;
_is.seekg(pos); // rewind
_is >> objectiveVectorValue;
}
}
private:
/** the objective vector of this solution */
ObjectiveVector objectiveVectorValue;
/** true if the objective vector is invalid */
bool invalidObjectiveVectorValue;
/** the fitness value of this solution */
Fitness fitnessValue;
/** true if the fitness value is invalid */
bool invalidFitnessValue;
/** the diversity value of this solution */
Diversity diversityValue;
/** true if the diversity value is invalid */
bool invalidDiversityValue;
/** the objective vector of this solution */
ObjectiveVector objectiveVectorValue;
/** true if the objective vector is invalid */
bool invalidObjectiveVectorValue;
/** the fitness value of this solution */
Fitness fitnessValue;
/** true if the fitness value is invalid */
bool invalidFitnessValue;
/** the diversity value of this solution */
Diversity diversityValue;
/** true if the diversity value is invalid */
bool invalidDiversityValue;
};

View file

@ -43,7 +43,7 @@ eoCheckPoint < MOEOT > & do_make_checkpoint_moeo (eoParser & _parser, eoState &
{
eoCheckPoint < MOEOT > & checkpoint = _state.storeFunctor(new eoCheckPoint < MOEOT > (_continue));
/* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
// get number of obectives
unsigned nObj = ObjectiveVector::nObjectives();
@ -63,17 +63,17 @@ eoCheckPoint < MOEOT > & do_make_checkpoint_moeo (eoParser & _parser, eoState &
// shoudl we empty it if exists
eoValueParam<bool>& eraseParam = _parser.getORcreateParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output");
bool dirOK = false; // not tested yet
// Dump of the whole population
//-----------------------------
bool printPop = _parser.getORcreateParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output").value();
eoSortedPopStat<MOEOT> * popStat;
if ( printPop ) // we do want pop dump
{
popStat = & _state.storeFunctor(new eoSortedPopStat<MOEOT>);
checkpoint.add(*popStat);
popStat = & _state.storeFunctor(new eoSortedPopStat<MOEOT>);
checkpoint.add(*popStat);
}
//////////////////////////////////
// State savers
//////////////////////////////
@ -82,36 +82,36 @@ eoCheckPoint < MOEOT > & do_make_checkpoint_moeo (eoParser & _parser, eoState &
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
if (_parser.isItThere(saveFrequencyParam))
{
// first make sure dirName is OK
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
// first make sure dirName is OK
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
#ifdef _MSVC
std::string stmp = dirName + "\generations";
std::string stmp = dirName + "\generations";
#else
std::string stmp = dirName + "/generations";
std::string stmp = dirName + "/generations";
#endif
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
_state.storeFunctor(stateSaver1);
checkpoint.add(*stateSaver1);
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
_state.storeFunctor(stateSaver1);
checkpoint.add(*stateSaver1);
}
// save state every T seconds
eoValueParam<unsigned>& saveTimeIntervalParam = _parser.getORcreateParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" );
if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
{
// first make sure dirName is OK
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
// first make sure dirName is OK
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC
std::string stmp = dirName + "\time";
std::string stmp = dirName + "\time";
#else
std::string stmp = dirName + "/time";
std::string stmp = dirName + "/time";
#endif
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
_state.storeFunctor(stateSaver2);
checkpoint.add(*stateSaver2);
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
_state.storeFunctor(stateSaver2);
checkpoint.add(*stateSaver2);
}
///////////////////
// Archive
//////////////////
@ -119,58 +119,58 @@ eoCheckPoint < MOEOT > & do_make_checkpoint_moeo (eoParser & _parser, eoState &
bool updateArch = _parser.getORcreateParam(true, "updateArch", "Update the archive at each gen.", '\0', "Evolution Engine").value();
if (updateArch)
{
moeoArchiveUpdater < MOEOT > * updater = new moeoArchiveUpdater < MOEOT > (_archive, _pop);
_state.storeFunctor(updater);
checkpoint.add(*updater);
moeoArchiveUpdater < MOEOT > * updater = new moeoArchiveUpdater < MOEOT > (_archive, _pop);
_state.storeFunctor(updater);
checkpoint.add(*updater);
}
// store the objective vectors contained in the archive every generation
bool storeArch = _parser.getORcreateParam(false, "storeArch", "Store the archive's objective vectors at each gen.", '\0', "Output").value();
if (storeArch)
{
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC
std::string stmp = dirName + "\arch";
std::string stmp = dirName + "\arch";
#else
std::string stmp = dirName + "/arch";
std::string stmp = dirName + "/arch";
#endif
moeoArchiveObjectiveVectorSavingUpdater < MOEOT > * save_updater = new moeoArchiveObjectiveVectorSavingUpdater < MOEOT > (_archive, stmp);
_state.storeFunctor(save_updater);
checkpoint.add(*save_updater);
moeoArchiveObjectiveVectorSavingUpdater < MOEOT > * save_updater = new moeoArchiveObjectiveVectorSavingUpdater < MOEOT > (_archive, stmp);
_state.storeFunctor(save_updater);
checkpoint.add(*save_updater);
}
// store the contribution of the non-dominated solutions
bool cont = _parser.getORcreateParam(false, "contribution", "Store the contribution of the archive at each gen.", '\0', "Output").value();
if (cont)
{
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC
std::string stmp = dirName + "\contribution";
std::string stmp = dirName + "\contribution";
#else
std::string stmp = dirName + "/contribution";
std::string stmp = dirName + "/contribution";
#endif
moeoContributionMetric < ObjectiveVector > * contribution = new moeoContributionMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * contribution_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*contribution, _archive, stmp);
_state.storeFunctor(contribution_updater);
checkpoint.add(*contribution_updater);
moeoContributionMetric < ObjectiveVector > * contribution = new moeoContributionMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * contribution_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*contribution, _archive, stmp);
_state.storeFunctor(contribution_updater);
checkpoint.add(*contribution_updater);
}
// store the entropy of the non-dominated solutions
bool ent = _parser.getORcreateParam(false, "entropy", "Store the entropy of the archive at each gen.", '\0', "Output").value();
if (ent)
{
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC
std::string stmp = dirName + "\entropy";
std::string stmp = dirName + "\entropy";
#else
std::string stmp = dirName + "/entropy";
std::string stmp = dirName + "/entropy";
#endif
moeoEntropyMetric < ObjectiveVector > * entropy = new moeoEntropyMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * entropy_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*entropy, _archive, stmp);
_state.storeFunctor(entropy_updater);
checkpoint.add(*entropy_updater);
moeoEntropyMetric < ObjectiveVector > * entropy = new moeoEntropyMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * entropy_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*entropy, _archive, stmp);
_state.storeFunctor(entropy_updater);
checkpoint.add(*entropy_updater);
}
// and that's it for the (control and) output
return checkpoint;
}

View file

@ -19,7 +19,7 @@
#include <eoFitContinue.h>
#include <eoTimeContinue.h>
#ifndef _MSC_VER
#include <eoCtrlCContinue.h>
#include <eoCtrlCContinue.h>
#endif
#include <utils/eoParser.h>
#include <utils/eoState.h>
@ -33,11 +33,11 @@
template <class MOEOT>
eoCombinedContinue<MOEOT> * make_combinedContinue(eoCombinedContinue<MOEOT> *_combined, eoContinue<MOEOT> *_cont)
{
if (_combined) // already exists
_combined->add(*_cont);
else
_combined = new eoCombinedContinue<MOEOT>(*_cont);
return _combined;
if (_combined) // already exists
_combined->add(*_cont);
else
_combined = new eoCombinedContinue<MOEOT>(*_cont);
return _combined;
}
@ -50,56 +50,56 @@ eoCombinedContinue<MOEOT> * make_combinedContinue(eoCombinedContinue<MOEOT> *_co
template <class MOEOT>
eoContinue<MOEOT> & do_make_continue_moeo(eoParser& _parser, eoState& _state, eoEvalFuncCounter<MOEOT> & _eval)
{
// the combined continue - to be filled
eoCombinedContinue<MOEOT> *continuator = NULL;
// First the eoGenContinue - need a default value so you can run blind
// but we also need to be able to avoid it <--> 0
eoValueParam<unsigned>& maxGenParam = _parser.createParam(unsigned(100), "maxGen", "Maximum number of generations (0 = none)",'G',"Stopping criterion");
if (maxGenParam.value()) // positive: -> define and store
{
eoGenContinue<MOEOT> *genCont = new eoGenContinue<MOEOT>(maxGenParam.value());
_state.storeFunctor(genCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, genCont);
}
// maxEval
eoValueParam<unsigned long>& maxEvalParam = _parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion");
if (maxEvalParam.value())
{
eoEvalContinue<MOEOT> *evalCont = new eoEvalContinue<MOEOT>(_eval, maxEvalParam.value());
_state.storeFunctor(evalCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, evalCont);
}
// maxTime
eoValueParam<unsigned long>& maxTimeParam = _parser.getORcreateParam((unsigned long)0, "maxTime", "Maximum running time in seconds (0 = none)", 'T', "Stopping criterion");
if (maxTimeParam.value()) // positive: -> define and store
{
eoTimeContinue<MOEOT> *timeCont = new eoTimeContinue<MOEOT>(maxTimeParam.value());
_state.storeFunctor(timeCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, timeCont);
}
// CtrlC
// the combined continue - to be filled
eoCombinedContinue<MOEOT> *continuator = NULL;
// First the eoGenContinue - need a default value so you can run blind
// but we also need to be able to avoid it <--> 0
eoValueParam<unsigned>& maxGenParam = _parser.createParam(unsigned(100), "maxGen", "Maximum number of generations (0 = none)",'G',"Stopping criterion");
if (maxGenParam.value()) // positive: -> define and store
{
eoGenContinue<MOEOT> *genCont = new eoGenContinue<MOEOT>(maxGenParam.value());
_state.storeFunctor(genCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, genCont);
}
// maxEval
eoValueParam<unsigned long>& maxEvalParam = _parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion");
if (maxEvalParam.value())
{
eoEvalContinue<MOEOT> *evalCont = new eoEvalContinue<MOEOT>(_eval, maxEvalParam.value());
_state.storeFunctor(evalCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, evalCont);
}
// maxTime
eoValueParam<unsigned long>& maxTimeParam = _parser.getORcreateParam((unsigned long)0, "maxTime", "Maximum running time in seconds (0 = none)", 'T', "Stopping criterion");
if (maxTimeParam.value()) // positive: -> define and store
{
eoTimeContinue<MOEOT> *timeCont = new eoTimeContinue<MOEOT>(maxTimeParam.value());
_state.storeFunctor(timeCont);
// and "add" to combined
continuator = make_combinedContinue<MOEOT>(continuator, timeCont);
}
// CtrlC
#ifndef _MSC_VER
// the CtrlC interception (Linux only I'm afraid)
eoCtrlCContinue<MOEOT> *ctrlCCont;
eoValueParam<bool>& ctrlCParam = _parser.createParam(true, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion");
if (_parser.isItThere(ctrlCParam))
{
ctrlCCont = new eoCtrlCContinue<MOEOT>;
// store
_state.storeFunctor(ctrlCCont);
// add to combinedContinue
continuator = make_combinedContinue<MOEOT>(continuator, ctrlCCont);
}
{
ctrlCCont = new eoCtrlCContinue<MOEOT>;
// store
_state.storeFunctor(ctrlCCont);
// add to combinedContinue
continuator = make_combinedContinue<MOEOT>(continuator, ctrlCCont);
}
#endif
// now check that there is at least one!
if (!continuator)
throw std::runtime_error("You MUST provide a stopping criterion");
// OK, it's there: store in the eoState
_state.storeFunctor(continuator);
// and return
throw std::runtime_error("You MUST provide a stopping criterion");
// OK, it's there: store in the eoState
_state.storeFunctor(continuator);
// and return
return *continuator;
}

View file

@ -53,189 +53,189 @@
template < class MOEOT >
moeoEA < MOEOT > & do_make_ea_moeo(eoParser & _parser, eoState & _state, eoEvalFunc < MOEOT > & _eval, eoContinue < MOEOT > & _continue, eoGenOp < MOEOT > & _op, moeoArchive < MOEOT > & _archive)
{
/* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/* the fitness assignment strategy */
string & fitnessParam = _parser.createParam(string("FastNonDominatedSorting"), "fitness",
"Fitness assignment scheme: Dummy, FastNonDominatedSorting or IndicatorBased", 'F',
"Evolution Engine").value();
string & indicatorParam = _parser.createParam(string("Epsilon"), "indicator",
"Binary indicator for IndicatorBased: Epsilon, Hypervolume", 'i',
"Evolution Engine").value();
double rho = _parser.createParam(1.1, "rho", "reference point for the hypervolume indicator", 'r',
"Evolution Engine").value();
double kappa = _parser.createParam(0.05, "kappa", "Scaling factor kappa for IndicatorBased", 'k',
"Evolution Engine").value();
moeoFitnessAssignment < MOEOT > * fitnessAssignment;
if (fitnessParam == string("Dummy"))
{
fitnessAssignment = new moeoDummyFitnessAssignment < MOEOT> ();
}
else if (fitnessParam == string("FastNonDominatedSorting"))
{
fitnessAssignment = new moeoFastNonDominatedSortingFitnessAssignment < MOEOT> ();
}
else if (fitnessParam == string("IndicatorBased"))
{
// metric
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > *metric;
if (indicatorParam == string("Epsilon"))
{
metric = new moeoAdditiveEpsilonBinaryMetric < ObjectiveVector >;
}
else if (indicatorParam == string("Hypervolume"))
{
metric = new moeoHypervolumeBinaryMetric < ObjectiveVector > (rho);
}
else
{
string stmp = string("Invalid binary quality indicator: ") + indicatorParam;
throw std::runtime_error(stmp.c_str());
}
fitnessAssignment = new moeoIndicatorBasedFitnessAssignment < MOEOT> (metric, kappa);
}
/* the fitness assignment strategy */
string & fitnessParam = _parser.createParam(string("FastNonDominatedSorting"), "fitness",
"Fitness assignment scheme: Dummy, FastNonDominatedSorting or IndicatorBased", 'F',
"Evolution Engine").value();
string & indicatorParam = _parser.createParam(string("Epsilon"), "indicator",
"Binary indicator for IndicatorBased: Epsilon, Hypervolume", 'i',
"Evolution Engine").value();
double rho = _parser.createParam(1.1, "rho", "reference point for the hypervolume indicator", 'r',
"Evolution Engine").value();
double kappa = _parser.createParam(0.05, "kappa", "Scaling factor kappa for IndicatorBased", 'k',
"Evolution Engine").value();
moeoFitnessAssignment < MOEOT > * fitnessAssignment;
if (fitnessParam == string("Dummy"))
{
fitnessAssignment = new moeoDummyFitnessAssignment < MOEOT> ();
}
else if (fitnessParam == string("FastNonDominatedSorting"))
{
fitnessAssignment = new moeoFastNonDominatedSortingFitnessAssignment < MOEOT> ();
}
else if (fitnessParam == string("IndicatorBased"))
{
// metric
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > *metric;
if (indicatorParam == string("Epsilon"))
{
metric = new moeoAdditiveEpsilonBinaryMetric < ObjectiveVector >;
}
else if (indicatorParam == string("Hypervolume"))
{
metric = new moeoHypervolumeBinaryMetric < ObjectiveVector > (rho);
}
else
{
string stmp = string("Invalid binary quality indicator: ") + indicatorParam;
throw std::runtime_error(stmp.c_str());
}
fitnessAssignment = new moeoIndicatorBasedFitnessAssignment < MOEOT> (metric, kappa);
}
else
{
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(fitnessAssignment);
/* the diversity assignment strategy */
string & diversityParam = _parser.createParam(string("Dummy"), "diversity",
"Diversity assignment scheme: Dummy or CrowdingDistance", 'D', "Evolution Engine").value();
moeoDiversityAssignment < MOEOT > * diversityAssignment;
if (diversityParam == string("CrowdingDistance"))
{
diversityAssignment = new moeoCrowdingDistanceDiversityAssignment < MOEOT> ();
}
else if (diversityParam == string("Dummy"))
{
diversityAssignment = new moeoDummyDiversityAssignment < MOEOT> ();
}
/* the diversity assignment strategy */
string & diversityParam = _parser.createParam(string("Dummy"), "diversity",
"Diversity assignment scheme: Dummy or CrowdingDistance", 'D', "Evolution Engine").value();
moeoDiversityAssignment < MOEOT > * diversityAssignment;
if (diversityParam == string("CrowdingDistance"))
{
diversityAssignment = new moeoCrowdingDistanceDiversityAssignment < MOEOT> ();
}
else if (diversityParam == string("Dummy"))
{
diversityAssignment = new moeoDummyDiversityAssignment < MOEOT> ();
}
else
{
string stmp = string("Invalid diversity assignment strategy: ") + diversityParam;
throw std::runtime_error(stmp.c_str());
string stmp = string("Invalid diversity assignment strategy: ") + diversityParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(diversityAssignment);
/* the comparator strategy */
string & comparatorParam = _parser.createParam(string("FitnessThenDiversity"), "comparator",
"Comparator scheme: FitnessThenDiversity or DiversityThenFitness", 'C', "Evolution Engine").value();
moeoComparator < MOEOT > * comparator;
if (comparatorParam == string("FitnessThenDiversity"))
{
comparator = new moeoFitnessThenDiversityComparator < MOEOT> ();
}
else if (comparatorParam == string("DiversityThenFitness"))
{
comparator = new moeoDiversityThenFitnessComparator < MOEOT> ();
}
string & comparatorParam = _parser.createParam(string("FitnessThenDiversity"), "comparator",
"Comparator scheme: FitnessThenDiversity or DiversityThenFitness", 'C', "Evolution Engine").value();
moeoComparator < MOEOT > * comparator;
if (comparatorParam == string("FitnessThenDiversity"))
{
comparator = new moeoFitnessThenDiversityComparator < MOEOT> ();
}
else if (comparatorParam == string("DiversityThenFitness"))
{
comparator = new moeoDiversityThenFitnessComparator < MOEOT> ();
}
else
{
string stmp = string("Invalid comparator strategy: ") + comparatorParam;
throw std::runtime_error(stmp.c_str());
string stmp = string("Invalid comparator strategy: ") + comparatorParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(comparator);
/* the selection strategy */
eoValueParam < eoParamParamType > & selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection",
"Selection scheme: DetTour(T), StochTour(t) or Random", 'S', "Evolution Engine");
eoParamParamType & ppSelect = selectionParam.value();
moeoSelectOne < MOEOT > * select;
if (ppSelect.first == string("DetTour"))
{
unsigned tSize;
if (!ppSelect.second.size()) // no parameter added
{
cerr << "WARNING, no parameter passed to DetTour, using 2" << endl;
tSize = 2;
// put back 2 in parameter for consistency (and status file)
ppSelect.second.push_back(string("2"));
}
else // parameter passed by user as DetTour(T)
{
tSize = atoi(ppSelect.second[0].c_str());
}
select = new moeoDetTournamentSelect < MOEOT > (*comparator, tSize);
}
else if (ppSelect.first == string("StochTour"))
{
double tRate;
if (!ppSelect.second.size()) // no parameter added
{
cerr << "WARNING, no parameter passed to StochTour, using 1" << endl;
tRate = 1;
// put back 1 in parameter for consistency (and status file)
ppSelect.second.push_back(string("1"));
}
else // parameter passed by user as StochTour(T)
{
tRate = atof(ppSelect.second[0].c_str());
}
select = new moeoStochTournamentSelect < MOEOT > (*comparator, tRate);
}
else if (ppSelect.first == string("Roulette"))
{
// TO DO !
// ...
}
else if (ppSelect.first == string("Random"))
{
select = new moeoRandomSelect <MOEOT > ();
}
else
{
string stmp = string("Invalid selection strategy: ") + ppSelect.first;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(select);
/* the replacement strategy */
string & replacementParam = _parser.createParam(string("Elitist"), "replacement",
"Replacement scheme: Elitist, Environmental or Generational", 'R', "Evolution Engine").value();
moeoReplacement < MOEOT > * replace;
if (replacementParam == string("Elitist"))
{
replace = new moeoElitistReplacement < MOEOT> (*fitnessAssignment, *diversityAssignment, *comparator);
}
else if (replacementParam == string("Environmental"))
{
replace = new moeoEnvironmentalReplacement < MOEOT> (*fitnessAssignment, *diversityAssignment, *comparator);
}
else if (replacementParam == string("Generational"))
{
replace = new moeoGenerationalReplacement < MOEOT> ();
}
eoValueParam < eoParamParamType > & selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection",
"Selection scheme: DetTour(T), StochTour(t) or Random", 'S', "Evolution Engine");
eoParamParamType & ppSelect = selectionParam.value();
moeoSelectOne < MOEOT > * select;
if (ppSelect.first == string("DetTour"))
{
unsigned tSize;
if (!ppSelect.second.size()) // no parameter added
{
cerr << "WARNING, no parameter passed to DetTour, using 2" << endl;
tSize = 2;
// put back 2 in parameter for consistency (and status file)
ppSelect.second.push_back(string("2"));
}
else // parameter passed by user as DetTour(T)
{
tSize = atoi(ppSelect.second[0].c_str());
}
select = new moeoDetTournamentSelect < MOEOT > (*comparator, tSize);
}
else if (ppSelect.first == string("StochTour"))
{
double tRate;
if (!ppSelect.second.size()) // no parameter added
{
cerr << "WARNING, no parameter passed to StochTour, using 1" << endl;
tRate = 1;
// put back 1 in parameter for consistency (and status file)
ppSelect.second.push_back(string("1"));
}
else // parameter passed by user as StochTour(T)
{
tRate = atof(ppSelect.second[0].c_str());
}
select = new moeoStochTournamentSelect < MOEOT > (*comparator, tRate);
}
else if (ppSelect.first == string("Roulette"))
{
// TO DO !
// ...
}
else if (ppSelect.first == string("Random"))
{
select = new moeoRandomSelect <MOEOT > ();
}
else
{
string stmp = string("Invalid replacement strategy: ") + replacementParam;
throw std::runtime_error(stmp.c_str());
string stmp = string("Invalid selection strategy: ") + ppSelect.first;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(select);
/* the replacement strategy */
string & replacementParam = _parser.createParam(string("Elitist"), "replacement",
"Replacement scheme: Elitist, Environmental or Generational", 'R', "Evolution Engine").value();
moeoReplacement < MOEOT > * replace;
if (replacementParam == string("Elitist"))
{
replace = new moeoElitistReplacement < MOEOT> (*fitnessAssignment, *diversityAssignment, *comparator);
}
else if (replacementParam == string("Environmental"))
{
replace = new moeoEnvironmentalReplacement < MOEOT> (*fitnessAssignment, *diversityAssignment, *comparator);
}
else if (replacementParam == string("Generational"))
{
replace = new moeoGenerationalReplacement < MOEOT> ();
}
else
{
string stmp = string("Invalid replacement strategy: ") + replacementParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(replace);
/* the number of offspring */
eoValueParam < eoHowMany > & offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring",
"Number of offspring (percentage or absolute)", 'O', "Evolution Engine");
// the general breeder
eoGeneralBreeder < MOEOT > * breed = new eoGeneralBreeder < MOEOT > (*select, _op, offspringRateParam.value());
_state.storeFunctor(breed);
// the eoEasyEA
moeoEA < MOEOT > * algo = new moeoEasyEA < MOEOT > (_continue, _eval, *breed, *replace, *fitnessAssignment, *diversityAssignment);
_state.storeFunctor(algo);
return *algo;
/* the number of offspring */
eoValueParam < eoHowMany > & offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring",
"Number of offspring (percentage or absolute)", 'O', "Evolution Engine");
// the general breeder
eoGeneralBreeder < MOEOT > * breed = new eoGeneralBreeder < MOEOT > (*select, _op, offspringRateParam.value());
_state.storeFunctor(breed);
// the eoEasyEA
moeoEA < MOEOT > * algo = new moeoEasyEA < MOEOT > (_continue, _eval, *breed, *replace, *fitnessAssignment, *diversityAssignment);
_state.storeFunctor(algo);
return *algo;
}
#endif /*MAKE_EA_MOEO_H_*/

View file

@ -41,80 +41,80 @@
*/
template < class MOEOT, class Move >
moeoLS < MOEOT, eoPop<MOEOT> & > & do_make_ls_moeo (
eoParser & _parser,
eoState & _state,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
eoContinue < MOEOT > & _continue,
eoMonOp < MOEOT > & _op,
eoMonOp < MOEOT > & _opInit,
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
moeoArchive < MOEOT > & _archive
)
eoParser & _parser,
eoState & _state,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
eoContinue < MOEOT > & _continue,
eoMonOp < MOEOT > & _op,
eoMonOp < MOEOT > & _opInit,
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
moeoArchive < MOEOT > & _archive
)
{
/* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/* the fitness assignment strategy */
string & fitnessParam = _parser.getORcreateParam(string("IndicatorBased"), "fitness",
"Fitness assignment strategy parameter: IndicatorBased...", 'F',
"Evolution Engine").value();
string & indicatorParam = _parser.getORcreateParam(string("Epsilon"), "indicator",
"Binary indicator to use with the IndicatorBased assignment: Epsilon, Hypervolume", 'i',
"Evolution Engine").value();
double rho = _parser.getORcreateParam(1.1, "rho", "reference point for the hypervolume indicator",
'r', "Evolution Engine").value();
double kappa = _parser.getORcreateParam(0.05, "kappa", "Scaling factor kappa for IndicatorBased",
'k', "Evolution Engine").value();
moeoIndicatorBasedFitnessAssignment < MOEOT > * fitnessAssignment;
if (fitnessParam == string("IndicatorBased"))
{
// metric
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > *metric;
if (indicatorParam == string("Epsilon"))
{
metric = new moeoAdditiveEpsilonBinaryMetric < ObjectiveVector >;
}
else if (indicatorParam == string("Hypervolume"))
{
metric = new moeoHypervolumeBinaryMetric < ObjectiveVector > (rho);
}
else
{
string stmp = string("Invalid binary quality indicator: ") + indicatorParam;
throw std::runtime_error(stmp.c_str());
}
fitnessAssignment = new moeoIndicatorBasedFitnessAssignment < MOEOT> (metric, kappa);
}
else
{
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(fitnessAssignment);
// number of iterations
unsigned n = _parser.getORcreateParam(1, "n", "Number of iterations for population Initialization", 'n', "Evolution Engine").value();
// LS
string & lsParam = _parser.getORcreateParam(string("I-IBMOLS"), "ls",
"Local Search: IBMOLS, I-IBMOLS (Iterated-IBMOLS)...", 'L',
"Evolution Engine").value();
moeoLS < MOEOT, eoPop<MOEOT> & > * ls;
if (lsParam == string("IBMOLS"))
{
ls = new moeoIndicatorBasedLS < MOEOT, Move > (_moveInit, _nextMove, _eval, _moveIncrEval, *fitnessAssignment, _continue);;
}
else if (lsParam == string("I-IBMOLS"))
{
ls = new moeoIteratedIBMOLS < MOEOT, Move > (_moveInit, _nextMove, _eval, _moveIncrEval, *fitnessAssignment, _continue, _op, _opInit, n);
}
else
{
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(ls);
// that's it !
return *ls;
/* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/* the fitness assignment strategy */
string & fitnessParam = _parser.getORcreateParam(string("IndicatorBased"), "fitness",
"Fitness assignment strategy parameter: IndicatorBased...", 'F',
"Evolution Engine").value();
string & indicatorParam = _parser.getORcreateParam(string("Epsilon"), "indicator",
"Binary indicator to use with the IndicatorBased assignment: Epsilon, Hypervolume", 'i',
"Evolution Engine").value();
double rho = _parser.getORcreateParam(1.1, "rho", "reference point for the hypervolume indicator",
'r', "Evolution Engine").value();
double kappa = _parser.getORcreateParam(0.05, "kappa", "Scaling factor kappa for IndicatorBased",
'k', "Evolution Engine").value();
moeoIndicatorBasedFitnessAssignment < MOEOT > * fitnessAssignment;
if (fitnessParam == string("IndicatorBased"))
{
// metric
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > *metric;
if (indicatorParam == string("Epsilon"))
{
metric = new moeoAdditiveEpsilonBinaryMetric < ObjectiveVector >;
}
else if (indicatorParam == string("Hypervolume"))
{
metric = new moeoHypervolumeBinaryMetric < ObjectiveVector > (rho);
}
else
{
string stmp = string("Invalid binary quality indicator: ") + indicatorParam;
throw std::runtime_error(stmp.c_str());
}
fitnessAssignment = new moeoIndicatorBasedFitnessAssignment < MOEOT> (metric, kappa);
}
else
{
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(fitnessAssignment);
// number of iterations
unsigned n = _parser.getORcreateParam(1, "n", "Number of iterations for population Initialization", 'n', "Evolution Engine").value();
// LS
string & lsParam = _parser.getORcreateParam(string("I-IBMOLS"), "ls",
"Local Search: IBMOLS, I-IBMOLS (Iterated-IBMOLS)...", 'L',
"Evolution Engine").value();
moeoLS < MOEOT, eoPop<MOEOT> & > * ls;
if (lsParam == string("IBMOLS"))
{
ls = new moeoIndicatorBasedLS < MOEOT, Move > (_moveInit, _nextMove, _eval, _moveIncrEval, *fitnessAssignment, _continue);;
}
else if (lsParam == string("I-IBMOLS"))
{
ls = new moeoIteratedIBMOLS < MOEOT, Move > (_moveInit, _nextMove, _eval, _moveIncrEval, *fitnessAssignment, _continue, _op, _opInit, n);
}
else
{
string stmp = string("Invalid fitness assignment strategy: ") + fitnessParam;
throw std::runtime_error(stmp.c_str());
}
_state.storeFunctor(ls);
// that's it !
return *ls;
}
#endif /*MAKE_LS_MOEO_H_*/

View file

@ -19,69 +19,69 @@
#include <utils/eoUpdater.h>
#include <metric/moeoMetric.h>
/**
* This class allows to save the progression of a binary metric comparing the objective vectors of the current population (or archive)
* with the objective vectors of the population (or archive) of the generation (n-1) into a file
/**
* This class allows to save the progression of a binary metric comparing the objective vectors of the current population (or archive)
* with the objective vectors of the population (or archive) of the generation (n-1) into a file
*/
template < class MOEOT >
class moeoBinaryMetricSavingUpdater : public eoUpdater
{
{
public:
/**
* The objective vector type of a solution
*/
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor
* @param _metric the binary metric comparing two Pareto sets
* @param _pop the main population
* @param _filename the target filename
*/
moeoBinaryMetricSavingUpdater (moeoVectorVsVectorBinaryMetric < ObjectiveVector, double > & _metric, const eoPop < MOEOT > & _pop, std::string _filename) :
metric(_metric), pop(_pop), filename(_filename), counter(1)
{}
/**
* The objective vector type of a solution
*/
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Saves the metric's value for the current generation
*/
void operator()() {
if (pop.size()) {
if (firstGen) {
firstGen = false;
}
else {
// creation of the two Pareto sets
std::vector < ObjectiveVector > from;
std::vector < ObjectiveVector > to;
for (unsigned i=0; i<pop.size(); i++)
from.push_back(pop[i].objectiveVector());
for (unsigned i=0 ; i<oldPop.size(); i++)
to.push_back(oldPop[i].objectiveVector());
// writing the result into the file
std::ofstream f (filename.c_str(), std::ios::app);
f << counter++ << ' ' << metric(from,to) << std::endl;
f.close();
}
oldPop = pop;
}
}
/**
* Ctor
* @param _metric the binary metric comparing two Pareto sets
* @param _pop the main population
* @param _filename the target filename
*/
moeoBinaryMetricSavingUpdater (moeoVectorVsVectorBinaryMetric < ObjectiveVector, double > & _metric, const eoPop < MOEOT > & _pop, std::string _filename) :
metric(_metric), pop(_pop), filename(_filename), counter(1)
{}
/**
* Saves the metric's value for the current generation
*/
void operator()() {
if (pop.size()) {
if (firstGen) {
firstGen = false;
}
else {
// creation of the two Pareto sets
std::vector < ObjectiveVector > from;
std::vector < ObjectiveVector > to;
for (unsigned i=0; i<pop.size(); i++)
from.push_back(pop[i].objectiveVector());
for (unsigned i=0 ; i<oldPop.size(); i++)
to.push_back(oldPop[i].objectiveVector());
// writing the result into the file
std::ofstream f (filename.c_str(), std::ios::app);
f << counter++ << ' ' << metric(from,to) << std::endl;
f.close();
}
oldPop = pop;
}
}
private:
/** binary metric comparing two Pareto sets */
moeoVectorVsVectorBinaryMetric < ObjectiveVector, double > & metric;
/** main population */
const eoPop < MOEOT > & pop;
/** (n-1) population */
eoPop< MOEOT > oldPop;
/** target filename */
std::string filename;
/** is it the first generation ? */
bool firstGen;
/** counter */
unsigned counter;
/** binary metric comparing two Pareto sets */
moeoVectorVsVectorBinaryMetric < ObjectiveVector, double > & metric;
/** main population */
const eoPop < MOEOT > & pop;
/** (n-1) population */
eoPop< MOEOT > oldPop;
/** target filename */
std::string filename;
/** is it the first generation ? */
bool firstGen;
/** counter */
unsigned counter;
};

View file

@ -24,74 +24,74 @@ class moeoContributionMetric : public moeoVectorVsVectorBinaryMetric < Objective
{
public:
/**
* Returns the contribution of the Pareto set '_set1' relatively to the Pareto set '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
double operator()(const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned c = card_C(_set1, _set2);
unsigned w1 = card_W(_set1, _set2);
unsigned n1 = card_N(_set1, _set2);
unsigned w2 = card_W(_set2, _set1);
unsigned n2 = card_N(_set2, _set1);
return (double) (c / 2.0 + w1 + n1) / (c + w1 + n1 + w2 + n2);
}
/**
* Returns the contribution of the Pareto set '_set1' relatively to the Pareto set '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
double operator()(const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned c = card_C(_set1, _set2);
unsigned w1 = card_W(_set1, _set2);
unsigned n1 = card_N(_set1, _set2);
unsigned w2 = card_W(_set2, _set1);
unsigned n2 = card_N(_set2, _set1);
return (double) (c / 2.0 + w1 + n1) / (c + w1 + n1 + w2 + n2);
}
private:
/**
* Returns the number of solutions both in '_set1' and '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_C (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned c=0;
for (unsigned i=0; i<_set1.size(); i++)
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i] == _set2[j]) {
c++;
break;
}
return c;
}
/**
* Returns the number of solutions both in '_set1' and '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_C (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned c=0;
for (unsigned i=0; i<_set1.size(); i++)
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i] == _set2[j]) {
c++;
break;
}
return c;
}
/**
* Returns the number of solutions in '_set1' dominating at least one solution of '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_W (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned w=0;
for (unsigned i=0; i<_set1.size(); i++)
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i].dominates(_set2[j])) {
w++;
break;
}
return w;
}
/**
* Returns the number of solutions in '_set1' dominating at least one solution of '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_W (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned w=0;
for (unsigned i=0; i<_set1.size(); i++)
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i].dominates(_set2[j])) {
w++;
break;
}
return w;
}
/**
* Returns the number of solutions in '_set1' having no relation of dominance with those from '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_N (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned n=0;
for (unsigned i=0; i<_set1.size(); i++) {
bool domin_rel = false;
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i].dominates(_set2[j]) || _set2[j].dominates(_set1 [i])) {
domin_rel = true;
break;
}
if (! domin_rel)
n++;
}
return n;
}
/**
* Returns the number of solutions in '_set1' having no relation of dominance with those from '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
unsigned card_N (const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
unsigned n=0;
for (unsigned i=0; i<_set1.size(); i++) {
bool domin_rel = false;
for (unsigned j=0; j<_set2.size(); j++)
if (_set1[i].dominates(_set2[j]) || _set2[j].dominates(_set1 [i])) {
domin_rel = true;
break;
}
if (! domin_rel)
n++;
}
return n;
}
};

View file

@ -24,153 +24,153 @@ class moeoEntropyMetric : public moeoVectorVsVectorBinaryMetric < ObjectiveVecto
{
public:
/**
* Returns the entropy of the Pareto set '_set1' relatively to the Pareto set '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
double operator()(const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
// normalization
std::vector< ObjectiveVector > set1 = _set1;
std::vector< ObjectiveVector > set2= _set2;
removeDominated (set1);
removeDominated (set2);
prenormalize (set1);
normalize (set1);
normalize (set2);
// making of PO*
std::vector< ObjectiveVector > star; // rotf :-)
computeUnion (set1, set2, star);
removeDominated (star);
// making of PO1 U PO*
std::vector< ObjectiveVector > union_set1_star; // rotf again ...
computeUnion (set1, star, union_set1_star);
unsigned C = union_set1_star.size();
float omega=0;
float entropy=0;
for (unsigned i=0 ; i<C ; i++) {
unsigned N_i = howManyInNicheOf (union_set1_star, union_set1_star[i], star.size());
unsigned n_i = howManyInNicheOf (set1, union_set1_star[i], star.size());
if (n_i > 0) {
omega += 1.0 / N_i;
entropy += (float) n_i / (N_i * C) * log (((float) n_i / C) / log (2.0));
}
}
entropy /= - log (omega);
entropy *= log (2.0);
return entropy;
}
/**
* Returns the entropy of the Pareto set '_set1' relatively to the Pareto set '_set2'
* @param _set1 the first Pareto set
* @param _set2 the second Pareto set
*/
double operator()(const std::vector < ObjectiveVector > & _set1, const std::vector < ObjectiveVector > & _set2) {
// normalization
std::vector< ObjectiveVector > set1 = _set1;
std::vector< ObjectiveVector > set2= _set2;
removeDominated (set1);
removeDominated (set2);
prenormalize (set1);
normalize (set1);
normalize (set2);
// making of PO*
std::vector< ObjectiveVector > star; // rotf :-)
computeUnion (set1, set2, star);
removeDominated (star);
// making of PO1 U PO*
std::vector< ObjectiveVector > union_set1_star; // rotf again ...
computeUnion (set1, star, union_set1_star);
unsigned C = union_set1_star.size();
float omega=0;
float entropy=0;
for (unsigned i=0 ; i<C ; i++) {
unsigned N_i = howManyInNicheOf (union_set1_star, union_set1_star[i], star.size());
unsigned n_i = howManyInNicheOf (set1, union_set1_star[i], star.size());
if (n_i > 0) {
omega += 1.0 / N_i;
entropy += (float) n_i / (N_i * C) * log (((float) n_i / C) / log (2.0));
}
}
entropy /= - log (omega);
entropy *= log (2.0);
return entropy;
}
private:
/** vector of min values */
std::vector<double> vect_min_val;
/** vector of max values */
std::vector<double> vect_max_val;
/** vector of min values */
std::vector<double> vect_min_val;
/** vector of max values */
std::vector<double> vect_max_val;
/**
* Removes the dominated individuals contained in _f
* @param _f a Pareto set
*/
void removeDominated(std::vector < ObjectiveVector > & _f) {
for (unsigned i=0 ; i<_f.size(); i++) {
bool dom = false;
for (unsigned j=0; j<_f.size(); j++)
if (i != j && _f[j].dominates(_f[i])) {
dom = true;
break;
}
if (dom) {
_f[i] = _f.back();
_f.pop_back();
i--;
}
}
}
/**
* Prenormalization
* @param _f a Pareto set
*/
void prenormalize (const std::vector< ObjectiveVector > & _f) {
vect_min_val.clear();
vect_max_val.clear();
for (unsigned char i=0 ; i<ObjectiveVector::nObjectives(); i++) {
float min_val = _f.front()[i], max_val = min_val;
for (unsigned j=1 ; j<_f.size(); j++) {
if (_f[j][i] < min_val)
min_val = _f[j][i];
if (_f[j][i]>max_val)
max_val = _f[j][i];
}
vect_min_val.push_back(min_val);
vect_max_val.push_back (max_val);
}
}
/**
* Normalization
* @param _f a Pareto set
*/
void normalize (std::vector< ObjectiveVector > & _f) {
for (unsigned i=0 ; i<ObjectiveVector::nObjectives(); i++)
for (unsigned j=0; j<_f.size(); j++)
_f[j][i] = (_f[j][i] - vect_min_val[i]) / (vect_max_val[i] - vect_min_val[i]);
}
/**
* Computation of the union of _f1 and _f2 in _f
* @param _f1 the first Pareto set
* @param _f2 the second Pareto set
* @param _f the final Pareto set
*/
void computeUnion(const std::vector< ObjectiveVector > & _f1, const std::vector< ObjectiveVector > & _f2, std::vector< ObjectiveVector > & _f) {
_f = _f1 ;
for (unsigned i=0; i<_f2.size(); i++) {
bool b = false;
for (unsigned j=0; j<_f1.size(); j ++)
if (_f1[j] == _f2[i]) {
b = true;
break;
}
if (! b)
_f.push_back(_f2[i]);
}
}
/**
* How many in niche
*/
unsigned howManyInNicheOf (const std::vector< ObjectiveVector > & _f, const ObjectiveVector & _s, unsigned _size) {
unsigned n=0;
for (unsigned i=0 ; i<_f.size(); i++) {
if (euclidianDistance(_f[i], _s) < (_s.size() / (double) _size))
n++;
}
return n;
}
/**
* Euclidian distance
*/
double euclidianDistance (const ObjectiveVector & _set1, const ObjectiveVector & _to, unsigned _deg = 2) {
double dist=0;
for (unsigned i=0; i<_set1.size(); i++)
dist += pow(fabs(_set1[i] - _to[i]), (int)_deg);
return pow(dist, 1.0 / _deg);
}
/**
* Removes the dominated individuals contained in _f
* @param _f a Pareto set
*/
void removeDominated(std::vector < ObjectiveVector > & _f) {
for (unsigned i=0 ; i<_f.size(); i++) {
bool dom = false;
for (unsigned j=0; j<_f.size(); j++)
if (i != j && _f[j].dominates(_f[i])) {
dom = true;
break;
}
if (dom) {
_f[i] = _f.back();
_f.pop_back();
i--;
}
}
}
/**
* Prenormalization
* @param _f a Pareto set
*/
void prenormalize (const std::vector< ObjectiveVector > & _f) {
vect_min_val.clear();
vect_max_val.clear();
for (unsigned char i=0 ; i<ObjectiveVector::nObjectives(); i++) {
float min_val = _f.front()[i], max_val = min_val;
for (unsigned j=1 ; j<_f.size(); j++) {
if (_f[j][i] < min_val)
min_val = _f[j][i];
if (_f[j][i]>max_val)
max_val = _f[j][i];
}
vect_min_val.push_back(min_val);
vect_max_val.push_back (max_val);
}
}
/**
* Normalization
* @param _f a Pareto set
*/
void normalize (std::vector< ObjectiveVector > & _f) {
for (unsigned i=0 ; i<ObjectiveVector::nObjectives(); i++)
for (unsigned j=0; j<_f.size(); j++)
_f[j][i] = (_f[j][i] - vect_min_val[i]) / (vect_max_val[i] - vect_min_val[i]);
}
/**
* Computation of the union of _f1 and _f2 in _f
* @param _f1 the first Pareto set
* @param _f2 the second Pareto set
* @param _f the final Pareto set
*/
void computeUnion(const std::vector< ObjectiveVector > & _f1, const std::vector< ObjectiveVector > & _f2, std::vector< ObjectiveVector > & _f) {
_f = _f1 ;
for (unsigned i=0; i<_f2.size(); i++) {
bool b = false;
for (unsigned j=0; j<_f1.size(); j ++)
if (_f1[j] == _f2[i]) {
b = true;
break;
}
if (! b)
_f.push_back(_f2[i]);
}
}
/**
* How many in niche
*/
unsigned howManyInNicheOf (const std::vector< ObjectiveVector > & _f, const ObjectiveVector & _s, unsigned _size) {
unsigned n=0;
for (unsigned i=0 ; i<_f.size(); i++) {
if (euclidianDistance(_f[i], _s) < (_s.size() / (double) _size))
n++;
}
return n;
}
/**
* Euclidian distance
*/
double euclidianDistance (const ObjectiveVector & _set1, const ObjectiveVector & _to, unsigned _deg = 2) {
double dist=0;
for (unsigned i=0; i<_set1.size(); i++)
dist += pow(fabs(_set1[i] - _to[i]), (int)_deg);
return pow(dist, 1.0 / _deg);
}
};

View file

@ -19,7 +19,7 @@
* Base class for performance metrics (also known as quality indicators).
*/
class moeoMetric : public eoFunctorBase
{};
{};
/**
@ -27,7 +27,7 @@ class moeoMetric : public eoFunctorBase
*/
template < class A, class R >
class moeoUnaryMetric : public eoUF < A, R >, public moeoMetric
{};
{};
/**
@ -35,7 +35,7 @@ class moeoUnaryMetric : public eoUF < A, R >, public moeoMetric
*/
template < class A1, class A2, class R >
class moeoBinaryMetric : public eoBF < A1, A2, R >, public moeoMetric
{};
{};
/**
@ -43,7 +43,7 @@ class moeoBinaryMetric : public eoBF < A1, A2, R >, public moeoMetric
*/
template < class ObjectiveVector, class R >
class moeoSolutionUnaryMetric : public moeoUnaryMetric < const ObjectiveVector &, R >
{};
{};
/**
@ -51,7 +51,7 @@ class moeoSolutionUnaryMetric : public moeoUnaryMetric < const ObjectiveVector &
*/
template < class ObjectiveVector, class R >
class moeoVectorUnaryMetric : public moeoUnaryMetric < const std::vector < ObjectiveVector > &, R >
{};
{};
/**
@ -59,7 +59,7 @@ class moeoVectorUnaryMetric : public moeoUnaryMetric < const std::vector < Objec
*/
template < class ObjectiveVector, class R >
class moeoSolutionVsSolutionBinaryMetric : public moeoBinaryMetric < const ObjectiveVector &, const ObjectiveVector &, R >
{};
{};
/**
@ -67,7 +67,7 @@ class moeoSolutionVsSolutionBinaryMetric : public moeoBinaryMetric < const Objec
*/
template < class ObjectiveVector, class R >
class moeoVectorVsVectorBinaryMetric : public moeoBinaryMetric < const std::vector < ObjectiveVector > &, const std::vector < ObjectiveVector > &, R >
{};
{};
#endif /*MOEOMETRIC_H_*/

View file

@ -26,118 +26,118 @@ template < class ObjectiveVector, class R >
class moeoNormalizedSolutionVsSolutionBinaryMetric : public moeoSolutionVsSolutionBinaryMetric < ObjectiveVector, R >
{
public:
/** very small value to avoid the extreme case where the min bound == the max bound */
const static double tiny = 1e-6;
/** very small value to avoid the extreme case where the min bound == the max bound */
const static double tiny = 1e-6;
/**
* Default ctr for any moeoNormalizedSolutionVsSolutionBinaryMetric object
*/
moeoNormalizedSolutionVsSolutionBinaryMetric()
{
bounds.resize(ObjectiveVector::Traits::nObjectives());
}
/**
* Sets the lower bound (_min) and the upper bound (_max) for the objective _obj
* _min lower bound
* _max upper bound
* _obj the objective index
*/
void setup(double _min, double _max, unsigned _obj)
{
if (_min == _max)
{
_min -= tiny;
_max += tiny;
}
bounds[_obj] = eoRealInterval(_min, _max);
}
/**
* Sets the lower bound and the upper bound for the objective _obj using a eoRealInterval object
* _realInterval the eoRealInterval object
* _obj the objective index
*/
virtual void setup(eoRealInterval _realInterval, unsigned _obj)
{
bounds[_obj] = _realInterval;
}
/**
* Default ctr for any moeoNormalizedSolutionVsSolutionBinaryMetric object
*/
moeoNormalizedSolutionVsSolutionBinaryMetric()
{
bounds.resize(ObjectiveVector::Traits::nObjectives());
}
/**
* Sets the lower bound (_min) and the upper bound (_max) for the objective _obj
* _min lower bound
* _max upper bound
* _obj the objective index
*/
void setup(double _min, double _max, unsigned _obj)
{
if (_min == _max)
{
_min -= tiny;
_max += tiny;
}
bounds[_obj] = eoRealInterval(_min, _max);
}
/**
* Sets the lower bound and the upper bound for the objective _obj using a eoRealInterval object
* _realInterval the eoRealInterval object
* _obj the objective index
*/
virtual void setup(eoRealInterval _realInterval, unsigned _obj)
{
bounds[_obj] = _realInterval;
}
protected:
/** the bounds for every objective (bounds[i] = bounds for the objective i) */
std::vector < eoRealInterval > bounds;
/** the bounds for every objective (bounds[i] = bounds for the objective i) */
std::vector < eoRealInterval > bounds;
};
/**
* Additive epsilon binary metric allowing to compare two objective vectors as proposed in
* Zitzler E., Thiele L., Laumanns M., Fonseca C. M., Grunert da Fonseca V.:
* Zitzler E., Thiele L., Laumanns M., Fonseca C. M., Grunert da Fonseca V.:
* Performance Assessment of Multiobjective Optimizers: An Analysis and Review. IEEE Transactions on Evolutionary Computation 7(2), pp.117132 (2003).
*/
template < class ObjectiveVector >
class moeoAdditiveEpsilonBinaryMetric : public moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double >
{
public:
/**
* Returns the minimal distance by which the objective vector _o1 must be translated in all objectives
* so that it weakly dominates the objective vector _o2
* @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector
* @param _o2 the second objective vector
*/
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{
// computation of the epsilon value for the first objective
double result = epsilon(_o1, _o2, 0);
// computation of the epsilon value for the other objectives
double tmp;
for (unsigned i=1; i<ObjectiveVector::Traits::nObjectives(); i++)
{
tmp = epsilon(_o1, _o2, i);
result = std::max(result, tmp);
}
// returns the maximum epsilon value
return result;
}
/**
* Returns the minimal distance by which the objective vector _o1 must be translated in all objectives
* so that it weakly dominates the objective vector _o2
* @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector
* @param _o2 the second objective vector
*/
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{
// computation of the epsilon value for the first objective
double result = epsilon(_o1, _o2, 0);
// computation of the epsilon value for the other objectives
double tmp;
for (unsigned i=1; i<ObjectiveVector::Traits::nObjectives(); i++)
{
tmp = epsilon(_o1, _o2, i);
result = std::max(result, tmp);
}
// returns the maximum epsilon value
return result;
}
private:
/** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/**
* Returns the epsilon value by which the objective vector _o1 must be translated in the objective _obj
* so that it dominates the objective vector _o2
* @param _o1 the first objective vector
* @param _o2 the second objective vector
* @param _obj the index of the objective
*/
double epsilon(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj)
{
double result;
// if the objective _obj have to be minimized
if (ObjectiveVector::Traits::minimizing(_obj))
{
// _o1[_obj] - _o2[_obj]
result = ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() );
}
// if the objective _obj have to be maximized
else
{
// _o2[_obj] - _o1[_obj]
result = ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() );
}
return result;
}
/** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/**
* Returns the epsilon value by which the objective vector _o1 must be translated in the objective _obj
* so that it dominates the objective vector _o2
* @param _o1 the first objective vector
* @param _o2 the second objective vector
* @param _obj the index of the objective
*/
double epsilon(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj)
{
double result;
// if the objective _obj have to be minimized
if (ObjectiveVector::Traits::minimizing(_obj))
{
// _o1[_obj] - _o2[_obj]
result = ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() );
}
// if the objective _obj have to be maximized
else
{
// _o2[_obj] - _o1[_obj]
result = ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() );
}
return result;
}
};
@ -146,7 +146,7 @@ private:
* Hypervolume binary metric allowing to compare two objective vectors as proposed in
* Zitzler E., Künzli S.: Indicator-Based Selection in Multiobjective Search. In Parallel Problem Solving from Nature (PPSN VIII).
* Lecture Notes in Computer Science 3242, Springer, Birmingham, UK pp.832842 (2004).
* This indicator is based on the hypervolume concept introduced in
* This indicator is based on the hypervolume concept introduced in
* Zitzler, E., Thiele, L.: Multiobjective Optimization Using Evolutionary Algorithms - A Comparative Case Study.
* Parallel Problem Solving from Nature (PPSN-V), pp.292-301 (1998).
*/
@ -155,111 +155,111 @@ class moeoHypervolumeBinaryMetric : public moeoNormalizedSolutionVsSolutionBinar
{
public:
/**
* Ctor
* @param _rho value used to compute the reference point from the worst values for each objective (default : 1.1)
*/
moeoHypervolumeBinaryMetric(double _rho = 1.1) : rho(_rho)
{
// not-a-maximization problem check
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
if (ObjectiveVector::Traits::maximizing(i))
{
throw std::runtime_error("Hypervolume binary metric not yet implemented for a maximization problem in moeoHypervolumeBinaryMetric");
}
}
// consistency check
if (rho < 1)
{
cout << "Warning, value used to compute the reference point rho for the hypervolume calculation must not be smaller than 1" << endl;
cout << "Adjusted to 1" << endl;
rho = 1;
}
}
/**
* Returns the volume of the space that is dominated by _o2 but not by _o1 with respect to a reference point computed using rho.
* @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector
* @param _o2 the second objective vector
*/
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{
double result;
// if _o1 dominates _o2
if ( paretoComparator(_o1,_o2) )
{
result = - hypervolume(_o1, _o2, ObjectiveVector::Traits::nObjectives()-1);
}
else
{
result = hypervolume(_o2, _o1, ObjectiveVector::Traits::nObjectives()-1);
}
return result;
}
/**
* Ctor
* @param _rho value used to compute the reference point from the worst values for each objective (default : 1.1)
*/
moeoHypervolumeBinaryMetric(double _rho = 1.1) : rho(_rho)
{
// not-a-maximization problem check
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
if (ObjectiveVector::Traits::maximizing(i))
{
throw std::runtime_error("Hypervolume binary metric not yet implemented for a maximization problem in moeoHypervolumeBinaryMetric");
}
}
// consistency check
if (rho < 1)
{
cout << "Warning, value used to compute the reference point rho for the hypervolume calculation must not be smaller than 1" << endl;
cout << "Adjusted to 1" << endl;
rho = 1;
}
}
/**
* Returns the volume of the space that is dominated by _o2 but not by _o1 with respect to a reference point computed using rho.
* @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector
* @param _o2 the second objective vector
*/
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{
double result;
// if _o1 dominates _o2
if ( paretoComparator(_o1,_o2) )
{
result = - hypervolume(_o1, _o2, ObjectiveVector::Traits::nObjectives()-1);
}
else
{
result = hypervolume(_o2, _o1, ObjectiveVector::Traits::nObjectives()-1);
}
return result;
}
private:
/** value used to compute the reference point from the worst values for each objective */
double rho;
/** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/** Functor to compare two objective vectors according to Pareto dominance relation */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/**
* Returns the volume of the space that is dominated by _o2 but not by _o1 with respect to a reference point computed using rho for the objective _obj.
* @param _o1 the first objective vector
* @param _o2 the second objective vector
* @param _obj the objective index
* @param _flag used for iteration, if _flag=true _o2 is not talen into account (default : false)
*/
double hypervolume(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj, const bool _flag = false)
{
double result;
double range = rho * bounds[_obj].range();
double max = bounds[_obj].minimum() + range;
// value of _1 for the objective _obj
double v1 = _o1[_obj];
// value of _2 for the objective _obj (if _flag=true, v2=max)
double v2;
if (_flag)
{
v2 = max;
}
else
{
v2 = _o2[_obj];
}
// computation of the volume
if (_obj == 0)
{
if (v1 < v2)
{
result = (v2 - v1) / range;
}
else
{
result = 0;
}
}
else
{
if (v1 < v2)
{
result = ( hypervolume(_o1, _o2, _obj-1, true) * (v2 - v1) / range ) + ( hypervolume(_o1, _o2, _obj-1) * (max - v2) / range );
}
else
{
result = hypervolume(_o1, _o2, _obj-1) * (max - v2) / range;
}
}
return result;
}
/** value used to compute the reference point from the worst values for each objective */
double rho;
/** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/** Functor to compare two objective vectors according to Pareto dominance relation */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/**
* Returns the volume of the space that is dominated by _o2 but not by _o1 with respect to a reference point computed using rho for the objective _obj.
* @param _o1 the first objective vector
* @param _o2 the second objective vector
* @param _obj the objective index
* @param _flag used for iteration, if _flag=true _o2 is not talen into account (default : false)
*/
double hypervolume(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj, const bool _flag = false)
{
double result;
double range = rho * bounds[_obj].range();
double max = bounds[_obj].minimum() + range;
// value of _1 for the objective _obj
double v1 = _o1[_obj];
// value of _2 for the objective _obj (if _flag=true, v2=max)
double v2;
if (_flag)
{
v2 = max;
}
else
{
v2 = _o2[_obj];
}
// computation of the volume
if (_obj == 0)
{
if (v1 < v2)
{
result = (v2 - v1) / range;
}
else
{
result = 0;
}
}
else
{
if (v1 < v2)
{
result = ( hypervolume(_o1, _o2, _obj-1, true) * (v2 - v1) / range ) + ( hypervolume(_o1, _o2, _obj-1) * (max - v2) / range );
}
else
{
result = hypervolume(_o1, _o2, _obj-1) * (max - v2) / range;
}
}
return result;
}
};

View file

@ -24,155 +24,155 @@ class moeoArchive : public eoPop < MOEOT >
{
public:
using std::vector < MOEOT > :: size;
using std::vector < MOEOT > :: operator[];
using std::vector < MOEOT > :: back;
using std::vector < MOEOT > :: pop_back;
/**
* The type of an objective vector for a solution
*/
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Default ctor.
* The moeoObjectiveVectorComparator used to compare solutions is based on Pareto dominance
*/
moeoArchive() : eoPop < MOEOT >(), comparator(paretoComparator)
{}
/**
* Ctor
* @param _comparator the moeoObjectiveVectorComparator used to compare solutions
*/
moeoArchive(moeoObjectiveVectorComparator < ObjectiveVector > & _comparator) : eoPop < MOEOT >(), comparator(_comparator)
{}
/**
* Returns true if the current archive dominates _objectiveVector according to the moeoObjectiveVectorComparator given in the constructor
* @param _objectiveVector the objective vector to compare with the current archive
*/
bool dominates (const ObjectiveVector & _objectiveVector) const
{
for (unsigned i = 0; i<size(); i++)
{
if ( comparator(operator[](i).fitness(), _objectiveVector) )
{
return true;
}
}
return false;
}
/**
* Returns true if the current archive already contains a solution with the same objective values than _objectiveVector
* @param _objectiveVector the objective vector to compare with the current archive
*/
bool contains (const ObjectiveVector & _objectiveVector) const
{
for (unsigned i = 0; i<size(); i++)
{
if (operator[](i).objectiveVector() == _objectiveVector)
{
return true;
}
}
return false;
}
/**
* Updates the archive with a given individual _moeo
* @param _moeo the given individual
*/
void update (const MOEOT & _moeo)
{
// first step: removing the dominated solutions from the archive
for (unsigned j=0; j<size();)
{
// if _moeo dominates the jth solution contained in the archive
if ( comparator(_moeo.objectiveVector(), operator[](j).objectiveVector()) )
{
operator[](j) = back();
pop_back();
}
else if (_moeo.objectiveVector() == operator[](j).objectiveVector())
{
operator[](j) = back();
pop_back();
}
else
{
j++;
}
}
// second step: is _moeo dominated?
bool dom = false;
for (unsigned j=0; j<size(); j++)
{
// if the jth solution contained in the archive dominates _moeo
if ( comparator(operator[](j).objectiveVector(), _moeo.objectiveVector()) )
{
dom = true;
break;
}
}
if (!dom)
{
push_back(_moeo);
}
}
/**
* Updates the archive with a given population _pop
* @param _pop the given population
*/
void update (const eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
update(_pop[i]);
}
}
using std::vector < MOEOT > :: size;
using std::vector < MOEOT > :: operator[];
using std::vector < MOEOT > :: back;
using std::vector < MOEOT > :: pop_back;
/**
* Returns true if the current archive contains the same objective vectors
* than the given archive _arch
* @param _arch the given archive
*/
bool equals (const moeoArchive < MOEOT > & _arch)
{
for (unsigned i=0; i<size(); i++)
{
if (! _arch.contains(operator[](i).objectiveVector()))
{
return false;
}
}
for (unsigned i=0; i<_arch.size() ; i++)
{
if (! contains(_arch[i].objectiveVector()))
{
return false;
}
}
return true;
}
/**
* The type of an objective vector for a solution
*/
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Default ctor.
* The moeoObjectiveVectorComparator used to compare solutions is based on Pareto dominance
*/
moeoArchive() : eoPop < MOEOT >(), comparator(paretoComparator)
{}
/**
* Ctor
* @param _comparator the moeoObjectiveVectorComparator used to compare solutions
*/
moeoArchive(moeoObjectiveVectorComparator < ObjectiveVector > & _comparator) : eoPop < MOEOT >(), comparator(_comparator)
{}
/**
* Returns true if the current archive dominates _objectiveVector according to the moeoObjectiveVectorComparator given in the constructor
* @param _objectiveVector the objective vector to compare with the current archive
*/
bool dominates (const ObjectiveVector & _objectiveVector) const
{
for (unsigned i = 0; i<size(); i++)
{
if ( comparator(operator[](i).fitness(), _objectiveVector) )
{
return true;
}
}
return false;
}
/**
* Returns true if the current archive already contains a solution with the same objective values than _objectiveVector
* @param _objectiveVector the objective vector to compare with the current archive
*/
bool contains (const ObjectiveVector & _objectiveVector) const
{
for (unsigned i = 0; i<size(); i++)
{
if (operator[](i).objectiveVector() == _objectiveVector)
{
return true;
}
}
return false;
}
/**
* Updates the archive with a given individual _moeo
* @param _moeo the given individual
*/
void update (const MOEOT & _moeo)
{
// first step: removing the dominated solutions from the archive
for (unsigned j=0; j<size();)
{
// if _moeo dominates the jth solution contained in the archive
if ( comparator(_moeo.objectiveVector(), operator[](j).objectiveVector()) )
{
operator[](j) = back();
pop_back();
}
else if (_moeo.objectiveVector() == operator[](j).objectiveVector())
{
operator[](j) = back();
pop_back();
}
else
{
j++;
}
}
// second step: is _moeo dominated?
bool dom = false;
for (unsigned j=0; j<size(); j++)
{
// if the jth solution contained in the archive dominates _moeo
if ( comparator(operator[](j).objectiveVector(), _moeo.objectiveVector()) )
{
dom = true;
break;
}
}
if (!dom)
{
push_back(_moeo);
}
}
/**
* Updates the archive with a given population _pop
* @param _pop the given population
*/
void update (const eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
update(_pop[i]);
}
}
/**
* Returns true if the current archive contains the same objective vectors
* than the given archive _arch
* @param _arch the given archive
*/
bool equals (const moeoArchive < MOEOT > & _arch)
{
for (unsigned i=0; i<size(); i++)
{
if (! _arch.contains(operator[](i).objectiveVector()))
{
return false;
}
}
for (unsigned i=0; i<_arch.size() ; i++)
{
if (! contains(_arch[i].objectiveVector()))
{
return false;
}
}
return true;
}
private:
/** The moeoObjectiveVectorComparator used to compare solutions */
moeoObjectiveVectorComparator < ObjectiveVector > & comparator;
/** A moeoObjectiveVectorComparator based on Pareto dominance (used as default) */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/** The moeoObjectiveVectorComparator used to compare solutions */
moeoObjectiveVectorComparator < ObjectiveVector > & comparator;
/** A moeoObjectiveVectorComparator based on Pareto dominance (used as default) */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
};

View file

@ -29,41 +29,41 @@ class moeoArchiveFitnessSavingUpdater : public eoUpdater
{
public:
/**
* Ctor
* @param _arch local archive
* @param _filename target filename
* @param _id own ID
*/
moeoArchiveFitnessSavingUpdater (moeoArchive<EOT> & _arch, const std::string & _filename = "Res/Arch", int _id = -1) : arch(_arch), filename(_filename), id(_id), counter(0)
{}
/**
* Ctor
* @param _arch local archive
* @param _filename target filename
* @param _id own ID
*/
moeoArchiveFitnessSavingUpdater (moeoArchive<EOT> & _arch, const std::string & _filename = "Res/Arch", int _id = -1) : arch(_arch), filename(_filename), id(_id), counter(0)
{}
/**
* Saves the fitness of the archive's members into the file
*/
void operator()() {
char buff[MAX_BUFFER_SIZE];
if (id == -1)
sprintf (buff, "%s.%u", filename.c_str(), counter ++);
else
sprintf (buff, "%s.%u.%u", filename.c_str(), id, counter ++);
std::ofstream f(buff);
for (unsigned i = 0; i < arch.size (); i++)
f << arch[i].objectiveVector() << std::endl;
f.close ();
}
/**
* Saves the fitness of the archive's members into the file
*/
void operator()() {
char buff[MAX_BUFFER_SIZE];
if (id == -1)
sprintf (buff, "%s.%u", filename.c_str(), counter ++);
else
sprintf (buff, "%s.%u.%u", filename.c_str(), id, counter ++);
std::ofstream f(buff);
for (unsigned i = 0; i < arch.size (); i++)
f << arch[i].objectiveVector() << std::endl;
f.close ();
}
private:
/** local archive */
moeoArchive<EOT> & arch;
/** target filename */
std::string filename;
/** own ID */
int id;
/** counter */
unsigned counter;
/** local archive */
moeoArchive<EOT> & arch;
/** target filename */
std::string filename;
/** own ID */
int id;
/** counter */
unsigned counter;
};

View file

@ -24,30 +24,30 @@ template < class EOT >
class moeoArchiveUpdater : public eoUpdater
{
public:
/**
* Ctor
* @param _arch an archive of non-dominated solutions
* @param _pop the main population
*/
moeoArchiveUpdater(moeoArchive <EOT> & _arch, const eoPop<EOT> & _pop) : arch(_arch), pop(_pop)
{}
/**
* Updates the archive with newly found non-dominated solutions contained in the main population
*/
void operator()() {
arch.update(pop);
}
/**
* Ctor
* @param _arch an archive of non-dominated solutions
* @param _pop the main population
*/
moeoArchiveUpdater(moeoArchive <EOT> & _arch, const eoPop<EOT> & _pop) : arch(_arch), pop(_pop)
{}
/**
* Updates the archive with newly found non-dominated solutions contained in the main population
*/
void operator()() {
arch.update(pop);
}
private:
/** the archive of non-dominated solutions */
moeoArchive<EOT> & arch;
/** the main population */
const eoPop<EOT> & pop;
/** the archive of non-dominated solutions */
moeoArchive<EOT> & arch;
/** the main population */
const eoPop<EOT> & pop;
};

View file

@ -17,50 +17,50 @@
#include <moeoLS.h>
/**
* This class allows to embed a set of local searches that are sequentially applied,
* This class allows to embed a set of local searches that are sequentially applied,
* and so working and updating the same archive of non-dominated solutions.
*/
template < class MOEOT, class Type >
class moeoCombinedLS : public moeoLS < MOEOT, Type >
{
public:
/**
* Ctor
* @param _eval the full evaluator of a solution
* @param _first_mols the first multi-objective local search to add
*/
moeoCombinedLS(moeoLS < MOEOT, Type > & _first_mols)
{
combinedLS.push_back (& _first_mols);
}
/**
* Adds a new local search to combine
* @param _mols the multi-objective local search to add
*/
void add(moeoLS < MOEOT, Type > & _mols)
{
combinedLS.push_back(& _mols);
}
/**
* Gives a new solution in order to explore the neigborhood.
* The new non-dominated solutions are added to the archive
* @param _moeo the solution
* @param _arch the archive of non-dominated solutions
*/
void operator () (Type _type, moeoArchive < MOEOT > & _arch)
{
for (unsigned i=0; i<combinedLS.size(); i++)
combinedLS[i] -> operator()(_type, _arch);
}
/**
* Ctor
* @param _eval the full evaluator of a solution
* @param _first_mols the first multi-objective local search to add
*/
moeoCombinedLS(moeoLS < MOEOT, Type > & _first_mols)
{
combinedLS.push_back (& _first_mols);
}
/**
* Adds a new local search to combine
* @param _mols the multi-objective local search to add
*/
void add(moeoLS < MOEOT, Type > & _mols)
{
combinedLS.push_back(& _mols);
}
/**
* Gives a new solution in order to explore the neigborhood.
* The new non-dominated solutions are added to the archive
* @param _moeo the solution
* @param _arch the archive of non-dominated solutions
*/
void operator () (Type _type, moeoArchive < MOEOT > & _arch)
{
for (unsigned i=0; i<combinedLS.size(); i++)
combinedLS[i] -> operator()(_type, _arch);
}
private:
/** the vector that contains the combined LS */
std::vector< moeoLS < MOEOT, Type > * > combinedLS;
/** the vector that contains the combined LS */
std::vector< moeoLS < MOEOT, Type > * > combinedLS;
};

View file

@ -20,7 +20,7 @@
*/
template < class MOEOT >
class moeoComparator : public eoBF < const MOEOT &, const MOEOT &, const bool >
{};
{};
/**
@ -30,15 +30,15 @@ template < class MOEOT >
class moeoObjectiveComparator : public moeoComparator < MOEOT >
{
public:
/**
* Returns true if _moeo1 is greater than _moeo2 on the first objective, then on the second, and so on
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return _moeo1.objectiveVector() > _moeo2.objectiveVector();
}
/**
* Returns true if _moeo1 is greater than _moeo2 on the first objective, then on the second, and so on
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return _moeo1.objectiveVector() > _moeo2.objectiveVector();
}
};
/**
@ -48,31 +48,31 @@ template < class MOEOT >
class moeoOneObjectiveComparator : public moeoComparator < MOEOT >
{
public:
/**
* Ctor.
* @param _obj the index of objective
*/
moeoOneObjectiveComparator(unsigned _obj) : obj(_obj)
{
if (obj > MOEOT::ObjectiveVector::nObjectives())
{
throw std::runtime_error("Problem with the index of objective in moeoOneObjectiveComparator");
}
}
/**
* Returns true if _moeo1 is greater than _moeo2 on the obj objective
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return _moeo1.objectiveVector()[obj] > _moeo2.objectiveVector()[obj];
}
/**
* Ctor.
* @param _obj the index of objective
*/
moeoOneObjectiveComparator(unsigned _obj) : obj(_obj)
{
if (obj > MOEOT::ObjectiveVector::nObjectives())
{
throw std::runtime_error("Problem with the index of objective in moeoOneObjectiveComparator");
}
}
/**
* Returns true if _moeo1 is greater than _moeo2 on the obj objective
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return _moeo1.objectiveVector()[obj] > _moeo2.objectiveVector()[obj];
}
private:
unsigned obj;
unsigned obj;
};
@ -84,22 +84,22 @@ template < class MOEOT >
class moeoFitnessThenDiversityComparator : public moeoComparator < MOEOT >
{
public:
/**
* Returns true if _moeo1 is greater than _moeo2 according to their fitness values, then according to their diversity values
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
if (_moeo1.fitness() == _moeo2.fitness())
{
return _moeo1.diversity() > _moeo2.diversity();
}
else
{
return _moeo1.fitness() > _moeo2.fitness();
}
}
/**
* Returns true if _moeo1 is greater than _moeo2 according to their fitness values, then according to their diversity values
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
if (_moeo1.fitness() == _moeo2.fitness())
{
return _moeo1.diversity() > _moeo2.diversity();
}
else
{
return _moeo1.fitness() > _moeo2.fitness();
}
}
};
@ -110,22 +110,22 @@ template < class MOEOT >
class moeoDiversityThenFitnessComparator : public moeoComparator < MOEOT >
{
public:
/**
* Returns true if _moeo1 is greater than _moeo2 according to their diversity values, then according to their fitness values
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
if (_moeo1.diversity() == _moeo2.diversity())
{
return _moeo1.fitness() > _moeo2.fitness();
}
else
{
return _moeo1.diversity() > _moeo2.diversity();
}
}
/**
* Returns true if _moeo1 is greater than _moeo2 according to their diversity values, then according to their fitness values
* @param _moeo1 the first solution
* @param _moeo2 the second solution
*/
const bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
if (_moeo1.diversity() == _moeo2.diversity())
{
return _moeo1.fitness() > _moeo2.fitness();
}
else
{
return _moeo1.diversity() > _moeo2.diversity();
}
}
};

View file

@ -23,20 +23,20 @@ class moeoConvertPopToObjectiveVectors : public eoUF < const eoPop < MOEOT >, co
{
public:
/**
* Returns a vector of the objective vectors from the population _pop
* @param _pop the population
*/
const std::vector < ObjectiveVector > operator()(const eoPop < MOEOT > _pop)
{
std::vector < ObjectiveVector > result;
result.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
result.push_back(_pop[i].objectiveVector());
}
return result;
}
/**
* Returns a vector of the objective vectors from the population _pop
* @param _pop the population
*/
const std::vector < ObjectiveVector > operator()(const eoPop < MOEOT > _pop)
{
std::vector < ObjectiveVector > result;
result.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
result.push_back(_pop[i].objectiveVector());
}
return result;
}
};
#endif /*MOEOPOPTOOBJECTIVEVECTORS_H_*/

View file

@ -18,7 +18,7 @@
#include <moeoDiversityAssignment.h>
/**
* Diversity assignment sheme based on crowding distance proposed in:
* Diversity assignment sheme based on crowding distance proposed in:
* K. Deb, A. Pratap, S. Agarwal, T. Meyarivan, "A Fast and Elitist Multi-Objective Genetic Algorithm: NSGA-II", IEEE Transactions on Evolutionary Computation, vol. 6, no. 2 (2002).
* This strategy is, for instance, used in NSGA-II.
*/
@ -27,89 +27,89 @@ class moeoCrowdingDistanceDiversityAssignment : public moeoDiversityAssignment <
{
public:
/** the objective vector type of the solutions */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Returns a big value (regarded as infinite)
*/
double inf() const
{
return std::numeric_limits<double>::max();
}
/**
* Computes diversity values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// number of objectives for the problem under consideration
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
if (_pop.size() <= 2)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].diversity(inf());
}
}
else
{
setDistances(_pop);
}
}
/** the objective vector type of the solutions */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Returns a big value (regarded as infinite)
*/
double inf() const
{
return std::numeric_limits<double>::max();
}
/**
* Computes diversity values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// number of objectives for the problem under consideration
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
if (_pop.size() <= 2)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].diversity(inf());
}
}
else
{
setDistances(_pop);
}
}
/**
* @warning NOT IMPLEMENTED, DO NOTHING !
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objVec the objective vector
* @warning NOT IMPLEMENTED, DO NOTHING !
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
cout << "WARNING : updateByDeleting not implemented in moeoCrowdingDiversityAssignment" << endl;
}
/**
* @warning NOT IMPLEMENTED, DO NOTHING !
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objVec the objective vector
* @warning NOT IMPLEMENTED, DO NOTHING !
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
cout << "WARNING : updateByDeleting not implemented in moeoCrowdingDiversityAssignment" << endl;
}
private:
/**
* Sets the distance values
* @param _pop the population
*/
void setDistances (eoPop < MOEOT > & _pop)
{
double min, max, distance;
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
// set diversity to 0
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].diversity(0);
}
// for each objective
for (unsigned obj=0; obj<nObjectives; obj++)
{
// comparator
moeoOneObjectiveComparator < MOEOT > comp(obj);
// sort
std::sort(_pop.begin(), _pop.end(), comp);
// min & max
min = _pop[0].objectiveVector()[obj];
max = _pop[_pop.size()-1].objectiveVector()[obj];
// set the diversity value to infiny for min and max
_pop[0].diversity(inf());
_pop[_pop.size()-1].diversity(inf());
for (unsigned i=1; i<_pop.size()-1; i++)
{
distance = (_pop[i+1].objectiveVector()[obj] - _pop[i-1].objectiveVector()[obj]) / (max-min);
_pop[i].diversity(_pop[i].diversity() + distance);
}
}
}
/**
* Sets the distance values
* @param _pop the population
*/
void setDistances (eoPop < MOEOT > & _pop)
{
double min, max, distance;
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
// set diversity to 0
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].diversity(0);
}
// for each objective
for (unsigned obj=0; obj<nObjectives; obj++)
{
// comparator
moeoOneObjectiveComparator < MOEOT > comp(obj);
// sort
std::sort(_pop.begin(), _pop.end(), comp);
// min & max
min = _pop[0].objectiveVector()[obj];
max = _pop[_pop.size()-1].objectiveVector()[obj];
// set the diversity value to infiny for min and max
_pop[0].diversity(inf());
_pop[_pop.size()-1].diversity(inf());
for (unsigned i=1; i<_pop.size()-1; i++)
{
distance = (_pop[i+1].objectiveVector()[obj] - _pop[i-1].objectiveVector()[obj]) / (max-min);
_pop[i].diversity(_pop[i].diversity() + distance);
}
}
}
};

View file

@ -22,30 +22,30 @@
template < class MOEOT >
class moeoDiversityAssignment : public eoUF < eoPop < MOEOT > &, void >
{
public:
public:
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
virtual void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec) = 0;
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the individual _moeo into account.
* @param _pop the population
* @param _moeo the individual
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
updateByDeleting(_pop, _moeo.objectiveVector());
}
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
virtual void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec) = 0;
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the individual _moeo into account.
* @param _pop the population
* @param _moeo the individual
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
updateByDeleting(_pop, _moeo.objectiveVector());
}
};
@ -57,37 +57,37 @@ class moeoDummyDiversityAssignment : public moeoDiversityAssignment < MOEOT >
{
public:
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Sets the diversity to '0' for every individuals of the population _pop if it is invalid
* @param _pop the population
*/
void operator () (eoPop < MOEOT > & _pop)
{
for (unsigned idx = 0; idx<_pop.size (); idx++)
{
if (_pop[idx].invalidDiversity())
{
// set the diversity to 0
_pop[idx].diversity(0.0);
}
}
}
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
// nothing to do... ;-)
}
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Sets the diversity to '0' for every individuals of the population _pop if it is invalid
* @param _pop the population
*/
void operator () (eoPop < MOEOT > & _pop)
{
for (unsigned idx = 0; idx<_pop.size (); idx++)
{
if (_pop[idx].invalidDiversity())
{
// set the diversity to 0
_pop[idx].diversity(0.0);
}
}
}
/**
* Updates the diversity values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
// nothing to do... ;-)
}
};
#endif /*MOEODIVERSITYASSIGNMENT_H_*/

View file

@ -27,93 +27,93 @@
/**
* An easy class to design multi-objective evolutionary algorithms.
*/
template < class MOEOT >
template < class MOEOT >
class moeoEasyEA: public moeoEA < MOEOT >
{
public:
/**
* Ctor.
* @param _continuator the stopping criteria
* @param _eval the evaluation functions
* @param _breed the breeder
* @param _replace the replacment strategy
* @param _fitnessEval the fitness evaluation scheme
* @param _diversityEval the diversity evaluation scheme
* @param _evalFitAndDivBeforeSelection put this parameter to 'true' if you want to re-evalue the fitness and the diversity of the population before the selection process
*/
moeoEasyEA(eoContinue < MOEOT > & _continuator, eoEvalFunc < MOEOT > & _eval, eoBreed < MOEOT > & _breed, eoReplacement < MOEOT > & _replace,
moeoFitnessAssignment < MOEOT > & _fitnessEval, moeoDiversityAssignment < MOEOT > & _diversityEval, bool _evalFitAndDivBeforeSelection = false)
:
continuator(_continuator), eval (_eval), loopEval(_eval), popEval(loopEval), breed(_breed), replace(_replace), fitnessEval(_fitnessEval),
diversityEval(_diversityEval), evalFitAndDivBeforeSelection(_evalFitAndDivBeforeSelection)
{}
/**
* Ctor.
* @param _continuator the stopping criteria
* @param _eval the evaluation functions
* @param _breed the breeder
* @param _replace the replacment strategy
* @param _fitnessEval the fitness evaluation scheme
* @param _diversityEval the diversity evaluation scheme
* @param _evalFitAndDivBeforeSelection put this parameter to 'true' if you want to re-evalue the fitness and the diversity of the population before the selection process
*/
moeoEasyEA(eoContinue < MOEOT > & _continuator, eoEvalFunc < MOEOT > & _eval, eoBreed < MOEOT > & _breed, eoReplacement < MOEOT > & _replace,
moeoFitnessAssignment < MOEOT > & _fitnessEval, moeoDiversityAssignment < MOEOT > & _diversityEval, bool _evalFitAndDivBeforeSelection = false)
:
continuator(_continuator), eval (_eval), loopEval(_eval), popEval(loopEval), breed(_breed), replace(_replace), fitnessEval(_fitnessEval),
diversityEval(_diversityEval), evalFitAndDivBeforeSelection(_evalFitAndDivBeforeSelection)
{}
/**
* Applies a few generation of evolution to the population _pop.
* @param _pop the population
*/
virtual void operator()(eoPop < MOEOT > & _pop)
{
eoPop < MOEOT > offspring, empty_pop;
popEval(empty_pop, _pop); // A first eval of pop.
bool firstTime = true;
do
{
try
{
unsigned pSize = _pop.size();
offspring.clear(); // new offspring
// fitness and diversity assignment (if you want to or if it is the first generation)
if (evalFitAndDivBeforeSelection || firstTime)
{
firstTime = false;
fitnessEval(_pop);
diversityEval(_pop);
}
breed(_pop, offspring);
popEval(_pop, offspring); // eval of parents + offspring if necessary
replace(_pop, offspring); // after replace, the new pop. is in _pop
if (pSize > _pop.size())
{
throw std::runtime_error("Population shrinking!");
}
else if (pSize < _pop.size())
{
throw std::runtime_error("Population growing!");
}
}
catch (std::exception& e)
{
std::string s = e.what();
s.append( " in moeoEasyEA");
throw std::runtime_error( s );
}
} while (continuator(_pop));
}
/**
* Applies a few generation of evolution to the population _pop.
* @param _pop the population
*/
virtual void operator()(eoPop < MOEOT > & _pop)
{
eoPop < MOEOT > offspring, empty_pop;
popEval(empty_pop, _pop); // A first eval of pop.
bool firstTime = true;
do
{
try
{
unsigned pSize = _pop.size();
offspring.clear(); // new offspring
// fitness and diversity assignment (if you want to or if it is the first generation)
if (evalFitAndDivBeforeSelection || firstTime)
{
firstTime = false;
fitnessEval(_pop);
diversityEval(_pop);
}
breed(_pop, offspring);
popEval(_pop, offspring); // eval of parents + offspring if necessary
replace(_pop, offspring); // after replace, the new pop. is in _pop
if (pSize > _pop.size())
{
throw std::runtime_error("Population shrinking!");
}
else if (pSize < _pop.size())
{
throw std::runtime_error("Population growing!");
}
}
catch (std::exception& e)
{
std::string s = e.what();
s.append( " in moeoEasyEA");
throw std::runtime_error( s );
}
} while (continuator(_pop));
}
protected:
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/** the evaluation functions */
eoEvalFunc < MOEOT > & eval;
/** to evaluate the whole population */
eoPopLoopEval < MOEOT > loopEval;
/** to evaluate the whole population */
eoPopEvalFunc < MOEOT > & popEval;
/** the breeder */
eoBreed < MOEOT > & breed;
/** the replacment strategy */
eoReplacement < MOEOT > & replace;
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & fitnessEval;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & diversityEval;
/** if this parameter is set to 'true', the fitness and the diversity of the whole population will be re-evaluated before the selection process */
bool evalFitAndDivBeforeSelection;
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/** the evaluation functions */
eoEvalFunc < MOEOT > & eval;
/** to evaluate the whole population */
eoPopLoopEval < MOEOT > loopEval;
/** to evaluate the whole population */
eoPopEvalFunc < MOEOT > & popEval;
/** the breeder */
eoBreed < MOEOT > & breed;
/** the replacment strategy */
eoReplacement < MOEOT > & replace;
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & fitnessEval;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & diversityEval;
/** if this parameter is set to 'true', the fitness and the diversity of the whole population will be re-evaluated before the selection process */
bool evalFitAndDivBeforeSelection;
};

View file

@ -28,117 +28,117 @@ template < class MOEOT > class moeoElitistReplacement:public moeoReplacement < M
{
public:
/**
* Full constructor.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (_comparator)
{}
/**
* Full constructor.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (_comparator)
{}
/**
* Constructor without comparator. A moeoFitThenDivComparator is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Constructor without comparator. A moeoFitThenDivComparator is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Constructor without moeoDiversityAssignement. A dummy diversity is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (_comparator)
{}
/**
* Constructor without moeoDiversityAssignement. A dummy diversity is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (_comparator)
{}
/**
* Constructor without moeoDiversityAssignement nor moeoComparator.
* A moeoFitThenDivComparator and a dummy diversity are used as default.
* @param _evalFitness the fitness assignment strategy
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Constructor without moeoDiversityAssignement nor moeoComparator.
* A moeoFitThenDivComparator and a dummy diversity are used as default.
* @param _evalFitness the fitness assignment strategy
*/
moeoElitistReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Replaces the first population by adding the individuals of the second one, sorting with a moeoComparator and resizing the whole population obtained.
* @param _parents the population composed of the parents (the population you want to replace)
* @param _offspring the offspring population
*/
void operator () (eoPop < MOEOT > &_parents, eoPop < MOEOT > &_offspring)
{
unsigned sz = _parents.size ();
// merges offspring and parents into a global population
_parents.reserve (_parents.size () + _offspring.size ());
copy (_offspring.begin (), _offspring.end (), back_inserter (_parents));
//remove the doubles in the whole pop
/****************************************************************************
eoRemoveDoubles < MOEOT > r;
r(_parents);
****************************************************************************/
// evaluates the fitness and the diversity of this global population
evalFitness (_parents);
evalDiversity (_parents);
// sorts the whole population according to the comparator
Cmp cmp(comparator);
std::sort(_parents.begin(), _parents.end(), cmp);
// finally, resize this global population
_parents.resize (sz);
// and clear the offspring population
_offspring.clear ();
}
/**
* Replaces the first population by adding the individuals of the second one, sorting with a moeoComparator and resizing the whole population obtained.
* @param _parents the population composed of the parents (the population you want to replace)
* @param _offspring the offspring population
*/
void operator () (eoPop < MOEOT > &_parents, eoPop < MOEOT > &_offspring)
{
unsigned sz = _parents.size ();
// merges offspring and parents into a global population
_parents.reserve (_parents.size () + _offspring.size ());
copy (_offspring.begin (), _offspring.end (), back_inserter (_parents));
//remove the doubles in the whole pop
/****************************************************************************
eoRemoveDoubles < MOEOT > r;
r(_parents);
****************************************************************************/
// evaluates the fitness and the diversity of this global population
evalFitness (_parents);
evalDiversity (_parents);
// sorts the whole population according to the comparator
Cmp cmp(comparator);
std::sort(_parents.begin(), _parents.end(), cmp);
// finally, resize this global population
_parents.resize (sz);
// and clear the offspring population
_offspring.clear ();
}
protected:
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & evalFitness;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & evalDiversity;
/** the comparator (used to compare 2 individuals) */
moeoComparator < MOEOT > & comparator;
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & evalFitness;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & evalDiversity;
/** the comparator (used to compare 2 individuals) */
moeoComparator < MOEOT > & comparator;
/**
* This class is used to compare solutions in order to sort the population.
*/
class Cmp
{
public:
/**
* Ctor.
* @param _comparator the comparator
*/
Cmp(moeoComparator < MOEOT > & _comparator) : comparator(_comparator)
{}
/**
* Returns true if _moeo1 is greater than _moeo2 according to the comparator
* _moeo1 the first individual
* _moeo2 the first individual
*/
bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return comparator(_moeo1,_moeo2);
}
private:
/** the comparator */
moeoComparator < MOEOT > & comparator;
};
/**
* This class is used to compare solutions in order to sort the population.
*/
class Cmp
{
public:
/**
* Ctor.
* @param _comparator the comparator
*/
Cmp(moeoComparator < MOEOT > & _comparator) : comparator(_comparator)
{}
/**
* Returns true if _moeo1 is greater than _moeo2 according to the comparator
* _moeo1 the first individual
* _moeo2 the first individual
*/
bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return comparator(_moeo1,_moeo2);
}
private:
/** the comparator */
moeoComparator < MOEOT > & comparator;
};
};

View file

@ -19,130 +19,130 @@
#include <moeoDiversityAssignment.h>
/**
* Environmental replacement strategy that consists in keeping the N best individuals by deleting individuals 1 by 1
* Environmental replacement strategy that consists in keeping the N best individuals by deleting individuals 1 by 1
* and by updating the fitness and diversity values after each deletion.
*/
template < class MOEOT > class moeoEnvironmentalReplacement:public moeoReplacement < MOEOT >
{
public:
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Full constructor.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (_comparator)
{}
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Constructor without comparator. A moeoFitThenDivComparator is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Full constructor.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (_comparator)
{}
/**
* Constructor without moeoDiversityAssignement. A dummy diversity is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (_comparator)
{}
/**
* Constructor without comparator. A moeoFitThenDivComparator is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _evalDiversity the diversity assignment strategy
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoDiversityAssignment < MOEOT > & _evalDiversity) :
evalFitness (_evalFitness), evalDiversity (_evalDiversity), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Constructor without moeoDiversityAssignement nor moeoComparator.
* A moeoFitThenDivComparator and a dummy diversity are used as default.
* @param _evalFitness the fitness assignment strategy
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Constructor without moeoDiversityAssignement. A dummy diversity is used as default.
* @param _evalFitness the fitness assignment strategy
* @param _comparator the comparator (used to compare 2 individuals)
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness, moeoComparator < MOEOT > & _comparator) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (_comparator)
{}
/**
* Replaces the first population by adding the individuals of the second one, sorting with a moeoComparator and resizing the whole population obtained.
* @param _parents the population composed of the parents (the population you want to replace)
* @param _offspring the offspring population
*/
void operator () (eoPop < MOEOT > &_parents, eoPop < MOEOT > &_offspring)
{
unsigned sz = _parents.size();
// merges offspring and parents into a global population
_parents.reserve (_parents.size() + _offspring.size());
copy (_offspring.begin(), _offspring.end(), back_inserter(_parents));
// evaluates the fitness and the diversity of this global population
evalFitness (_parents);
evalDiversity (_parents);
// remove individuals 1 by 1 and update the fitness values
Cmp cmp(comparator);
ObjectiveVector worstObjVec;
while (_parents.size() > sz)
{
std::sort (_parents.begin(), _parents.end(), cmp);
worstObjVec = _parents[_parents.size()-1].objectiveVector();
_parents.resize(_parents.size()-1);
evalFitness.updateByDeleting(_parents, worstObjVec);
evalDiversity.updateByDeleting(_parents, worstObjVec);
}
// clear the offspring population
_offspring.clear ();
}
/**
* Constructor without moeoDiversityAssignement nor moeoComparator.
* A moeoFitThenDivComparator and a dummy diversity are used as default.
* @param _evalFitness the fitness assignment strategy
*/
moeoEnvironmentalReplacement (moeoFitnessAssignment < MOEOT > & _evalFitness) :
evalFitness (_evalFitness), evalDiversity (*(new moeoDummyDiversityAssignment < MOEOT >)), comparator (*(new moeoFitnessThenDiversityComparator < MOEOT >))
{}
/**
* Replaces the first population by adding the individuals of the second one, sorting with a moeoComparator and resizing the whole population obtained.
* @param _parents the population composed of the parents (the population you want to replace)
* @param _offspring the offspring population
*/
void operator () (eoPop < MOEOT > &_parents, eoPop < MOEOT > &_offspring)
{
unsigned sz = _parents.size();
// merges offspring and parents into a global population
_parents.reserve (_parents.size() + _offspring.size());
copy (_offspring.begin(), _offspring.end(), back_inserter(_parents));
// evaluates the fitness and the diversity of this global population
evalFitness (_parents);
evalDiversity (_parents);
// remove individuals 1 by 1 and update the fitness values
Cmp cmp(comparator);
ObjectiveVector worstObjVec;
while (_parents.size() > sz)
{
std::sort (_parents.begin(), _parents.end(), cmp);
worstObjVec = _parents[_parents.size()-1].objectiveVector();
_parents.resize(_parents.size()-1);
evalFitness.updateByDeleting(_parents, worstObjVec);
evalDiversity.updateByDeleting(_parents, worstObjVec);
}
// clear the offspring population
_offspring.clear ();
}
protected:
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & evalFitness;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & evalDiversity;
/** the comparator (used to compare 2 individuals) */
moeoComparator < MOEOT > & comparator;
/** the fitness assignment strategy */
moeoFitnessAssignment < MOEOT > & evalFitness;
/** the diversity assignment strategy */
moeoDiversityAssignment < MOEOT > & evalDiversity;
/** the comparator (used to compare 2 individuals) */
moeoComparator < MOEOT > & comparator;
/**
* This class is used to compare solutions in order to sort the population.
*/
class Cmp
{
public:
/**
* Ctor.
* @param _comparator the comparator
*/
Cmp(moeoComparator < MOEOT > & _comparator) : comparator(_comparator)
{}
/**
* Returns true if _moeo1 is greater than _moeo2 according to the comparator
* _moeo1 the first individual
* _moeo2 the first individual
*/
bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return comparator(_moeo1,_moeo2);
}
private:
/** the comparator */
moeoComparator < MOEOT > & comparator;
};
/**
* This class is used to compare solutions in order to sort the population.
*/
class Cmp
{
public:
/**
* Ctor.
* @param _comparator the comparator
*/
Cmp(moeoComparator < MOEOT > & _comparator) : comparator(_comparator)
{}
/**
* Returns true if _moeo1 is greater than _moeo2 according to the comparator
* _moeo1 the first individual
* _moeo2 the first individual
*/
bool operator()(const MOEOT & _moeo1, const MOEOT & _moeo2)
{
return comparator(_moeo1,_moeo2);
}
private:
/** the comparator */
moeoComparator < MOEOT > & comparator;
};
};

View file

@ -19,7 +19,7 @@
#include <moeoObjectiveVectorComparator.h>
/**
* Fitness assignment sheme based on Pareto-dominance count proposed in:
* Fitness assignment sheme based on Pareto-dominance count proposed in:
* N. Srinivas, K. Deb, "Multiobjective Optimization Using Nondominated Sorting in Genetic Algorithms", Evolutionary Computation vol. 2, no. 3, pp. 221-248 (1994)
* and in:
* K. Deb, A. Pratap, S. Agarwal, T. Meyarivan, "A Fast and Elitist Multi-Objective Genetic Algorithm: NSGA-II", IEEE Transactions on Evolutionary Computation, vol. 6, no. 2 (2002).
@ -30,180 +30,180 @@ class moeoFastNonDominatedSortingFitnessAssignment : public moeoParetoBasedFitne
{
public:
/** the objective vector type of the solutions */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Default ctor
*/
moeoFastNonDominatedSortingFitnessAssignment() : comparator(paretoComparator)
{}
/**
* Ctor where you can choose your own way to compare objective vectors
* @param _comparator the functor used to compare objective vectors
*/
moeoFastNonDominatedSortingFitnessAssignment(moeoObjectiveVectorComparator < ObjectiveVector > & _comparator) : comparator(_comparator)
{}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// number of objectives for the problem under consideration
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
if (nObjectives == 1)
{
// one objective
oneObjective(_pop);
}
else if (nObjectives == 2)
{
// two objectives (the two objectives function is still to implement)
mObjectives(_pop);
}
else if (nObjectives > 2)
{
// more than two objectives
mObjectives(_pop);
}
else
{
// problem with the number of objectives
throw std::runtime_error("Problem with the number of objectives in moeoNonDominatedSortingFitnessAssignment");
}
// a higher fitness is better, so the values need to be inverted
double max = _pop[0].fitness();
for (unsigned i=1 ; i<_pop.size() ; i++)
{
max = std::max(max, _pop[i].fitness());
}
for (unsigned i=0 ; i<_pop.size() ; i++)
{
_pop[i].fitness(max - _pop[i].fitness());
}
}
/** the objective vector type of the solutions */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* @warning NOT IMPLEMENTED, DO NOTHING !
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
* @warning NOT IMPLEMENTED, DO NOTHING !
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
cout << "WARNING : updateByDeleting not implemented in moeoNonDominatedSortingFitnessAssignment" << endl;
}
/**
* Default ctor
*/
moeoFastNonDominatedSortingFitnessAssignment() : comparator(paretoComparator)
{}
/**
* Ctor where you can choose your own way to compare objective vectors
* @param _comparator the functor used to compare objective vectors
*/
moeoFastNonDominatedSortingFitnessAssignment(moeoObjectiveVectorComparator < ObjectiveVector > & _comparator) : comparator(_comparator)
{}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// number of objectives for the problem under consideration
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
if (nObjectives == 1)
{
// one objective
oneObjective(_pop);
}
else if (nObjectives == 2)
{
// two objectives (the two objectives function is still to implement)
mObjectives(_pop);
}
else if (nObjectives > 2)
{
// more than two objectives
mObjectives(_pop);
}
else
{
// problem with the number of objectives
throw std::runtime_error("Problem with the number of objectives in moeoNonDominatedSortingFitnessAssignment");
}
// a higher fitness is better, so the values need to be inverted
double max = _pop[0].fitness();
for (unsigned i=1 ; i<_pop.size() ; i++)
{
max = std::max(max, _pop[i].fitness());
}
for (unsigned i=0 ; i<_pop.size() ; i++)
{
_pop[i].fitness(max - _pop[i].fitness());
}
}
/**
* @warning NOT IMPLEMENTED, DO NOTHING !
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
* @warning NOT IMPLEMENTED, DO NOTHING !
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
cout << "WARNING : updateByDeleting not implemented in moeoNonDominatedSortingFitnessAssignment" << endl;
}
private:
/** Functor to compare two objective vectors */
moeoObjectiveVectorComparator < ObjectiveVector > & comparator;
/** Functor to compare two objective vectors according to Pareto dominance relation */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/**
* Sets the fitness values for mono-objective problems
* @param _pop the population
*/
void oneObjective (eoPop < MOEOT > & _pop)
{
// Functor to compare two solutions on the first objective, then on the second, and so on
moeoObjectiveComparator < MOEOT > objComparator;
std::sort(_pop.begin(), _pop.end(), objComparator);
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(i+1);
}
}
/**
* Sets the fitness values for bi-objective problems with a complexity of O(n log n), where n stands for the population size
* @param _pop the population
*/
void twoObjectives (eoPop < MOEOT > & _pop)
{
//... TO DO !
}
/**
* Sets the fitness values for problems with more than two objectives with a complexity of O(n² log n), where n stands for the population size
* @param _pop the population
*/
void mObjectives (eoPop < MOEOT > & _pop)
{
// S[i] = indexes of the individuals dominated by _pop[i]
std::vector < std::vector<unsigned> > S(_pop.size());
// n[i] = number of individuals that dominate the individual _pop[i]
std::vector < unsigned > n(_pop.size(), 0);
// fronts: F[i] = indexes of the individuals contained in the ith front
std::vector < std::vector<unsigned> > F(_pop.size()+1);
// used to store the number of the first front
F[1].reserve(_pop.size());
for (unsigned p=0; p<_pop.size(); p++)
{
for (unsigned q=0; q<_pop.size(); q++)
{
// if p dominates q
if ( comparator(_pop[p].objectiveVector(), _pop[q].objectiveVector()) )
{
// add q to the set of solutions dominated by p
S[p].push_back(q);
}
// if q dominates p
else if ( comparator(_pop[q].objectiveVector(), _pop[p].objectiveVector()) )
{
// increment the domination counter of p
n[p]++;
}
}
// if no individual dominates p
if (n[p] == 0)
{
// p belongs to the first front
_pop[p].fitness(1);
F[1].push_back(p);
}
}
// front counter
unsigned counter=1;
unsigned p,q;
while (! F[counter].empty())
{
// used to store the number of the next front
F[counter+1].reserve(_pop.size());
for (unsigned i=0; i<F[counter].size(); i++)
{
p = F[counter][i];
for (unsigned j=0; j<S[p].size(); j++)
{
q = S[p][j];
n[q]--;
// if no individual dominates q anymore
if (n[q] == 0)
{
// q belongs to the next front
_pop[q].fitness(counter+1);
F[counter+1].push_back(q);
}
}
}
counter++;
}
}
/** Functor to compare two objective vectors */
moeoObjectiveVectorComparator < ObjectiveVector > & comparator;
/** Functor to compare two objective vectors according to Pareto dominance relation */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/**
* Sets the fitness values for mono-objective problems
* @param _pop the population
*/
void oneObjective (eoPop < MOEOT > & _pop)
{
// Functor to compare two solutions on the first objective, then on the second, and so on
moeoObjectiveComparator < MOEOT > objComparator;
std::sort(_pop.begin(), _pop.end(), objComparator);
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(i+1);
}
}
/**
* Sets the fitness values for bi-objective problems with a complexity of O(n log n), where n stands for the population size
* @param _pop the population
*/
void twoObjectives (eoPop < MOEOT > & _pop)
{
//... TO DO !
}
/**
* Sets the fitness values for problems with more than two objectives with a complexity of O(n² log n), where n stands for the population size
* @param _pop the population
*/
void mObjectives (eoPop < MOEOT > & _pop)
{
// S[i] = indexes of the individuals dominated by _pop[i]
std::vector < std::vector<unsigned> > S(_pop.size());
// n[i] = number of individuals that dominate the individual _pop[i]
std::vector < unsigned > n(_pop.size(), 0);
// fronts: F[i] = indexes of the individuals contained in the ith front
std::vector < std::vector<unsigned> > F(_pop.size()+1);
// used to store the number of the first front
F[1].reserve(_pop.size());
for (unsigned p=0; p<_pop.size(); p++)
{
for (unsigned q=0; q<_pop.size(); q++)
{
// if p dominates q
if ( comparator(_pop[p].objectiveVector(), _pop[q].objectiveVector()) )
{
// add q to the set of solutions dominated by p
S[p].push_back(q);
}
// if q dominates p
else if ( comparator(_pop[q].objectiveVector(), _pop[p].objectiveVector()) )
{
// increment the domination counter of p
n[p]++;
}
}
// if no individual dominates p
if (n[p] == 0)
{
// p belongs to the first front
_pop[p].fitness(1);
F[1].push_back(p);
}
}
// front counter
unsigned counter=1;
unsigned p,q;
while (! F[counter].empty())
{
// used to store the number of the next front
F[counter+1].reserve(_pop.size());
for (unsigned i=0; i<F[counter].size(); i++)
{
p = F[counter][i];
for (unsigned j=0; j<S[p].size(); j++)
{
q = S[p][j];
n[q]--;
// if no individual dominates q anymore
if (n[q] == 0)
{
// q belongs to the next front
_pop[q].fitness(counter+1);
F[counter+1].push_back(q);
}
}
}
counter++;
}
}
};

View file

@ -24,27 +24,27 @@ class moeoFitnessAssignment : public eoUF < eoPop < MOEOT > &, void >
{
public:
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
virtual void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec) = 0;
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the individual _moeo into account.
* @param _pop the population
* @param _moeo the individual
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
updateByDeleting(_pop, _moeo.objectiveVector());
}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
virtual void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec) = 0;
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the individual _moeo into account.
* @param _pop the population
* @param _moeo the individual
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
updateByDeleting(_pop, _moeo.objectiveVector());
}
};
@ -57,37 +57,37 @@ class moeoDummyFitnessAssignment : public moeoFitnessAssignment < MOEOT >
{
public:
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Sets the fitness to '0' for every individuals of the population _pop if it is invalid
* @param _pop the population
*/
void operator () (eoPop < MOEOT > & _pop)
{
for (unsigned idx = 0; idx<_pop.size (); idx++)
{
if (_pop[idx].invalidFitness())
{
// set the diversity to 0
_pop[idx].fitness(0.0);
}
}
}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
// nothing to do... ;-)
}
/** The type for objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Sets the fitness to '0' for every individuals of the population _pop if it is invalid
* @param _pop the population
*/
void operator () (eoPop < MOEOT > & _pop)
{
for (unsigned idx = 0; idx<_pop.size (); idx++)
{
if (_pop[idx].invalidFitness())
{
// set the diversity to 0
_pop[idx].fitness(0.0);
}
}
}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
// nothing to do... ;-)
}
};
@ -96,7 +96,7 @@ public:
*/
template < class MOEOT >
class moeoScalarFitnessAssignment : public moeoFitnessAssignment < MOEOT >
{};
{};
/**
@ -104,7 +104,7 @@ class moeoScalarFitnessAssignment : public moeoFitnessAssignment < MOEOT >
*/
template < class MOEOT >
class moeoCriterionBasedFitnessAssignment : public moeoFitnessAssignment < MOEOT >
{};
{};
/**
@ -112,7 +112,7 @@ class moeoCriterionBasedFitnessAssignment : public moeoFitnessAssignment < MOEOT
*/
template < class MOEOT >
class moeoParetoBasedFitnessAssignment : public moeoFitnessAssignment < MOEOT >
{};
{};
#endif /*MOEOFITNESSASSIGNMENT_H_*/

View file

@ -23,16 +23,16 @@ template < class MOEOT >
class moeoGenerationalReplacement : public moeoReplacement < MOEOT >, public eoGenerationalReplacement < MOEOT >
{
public:
/**
* Swaps _parents and _offspring
* @param _parents the parents population
* @param _offspring the offspring population
*/
void operator()(eoPop < MOEOT > & _parents, eoPop < MOEOT > & _offspring)
{
eoGenerationalReplacement < MOEOT >::operator ()(_parents, _offspring);
}
/**
* Swaps _parents and _offspring
* @param _parents the parents population
* @param _offspring the offspring population
*/
void operator()(eoPop < MOEOT > & _parents, eoPop < MOEOT > & _offspring)
{
eoGenerationalReplacement < MOEOT >::operator ()(_parents, _offspring);
}
};

View file

@ -21,7 +21,7 @@
#include <moeoLS.h>
/**
* This class allows to apply a multi-objective local search to a number of selected individuals contained in the archive
* This class allows to apply a multi-objective local search to a number of selected individuals contained in the archive
* at every generation until a stopping criteria is verified.
*/
template < class MOEOT >
@ -29,47 +29,47 @@ class moeoHybridLS : public eoUpdater
{
public:
/**
* Ctor
* @param _term stopping criteria
* @param _select selector
* @param _mols a multi-objective local search
* @param _arch the archive
*/
moeoHybridLS (eoContinue < MOEOT > & _term, eoSelect < MOEOT > & _select, moeoLS < MOEOT, MOEOT > & _mols, moeoArchive < MOEOT > & _arch) :
term(_term), select(_select), mols(_mols), arch(_arch)
{}
/**
* Ctor
* @param _term stopping criteria
* @param _select selector
* @param _mols a multi-objective local search
* @param _arch the archive
*/
moeoHybridLS (eoContinue < MOEOT > & _term, eoSelect < MOEOT > & _select, moeoLS < MOEOT, MOEOT > & _mols, moeoArchive < MOEOT > & _arch) :
term(_term), select(_select), mols(_mols), arch(_arch)
{}
/**
* Applies the multi-objective local search to selected individuals contained in the archive if the stopping criteria is not verified
*/
void operator () ()
{
if (! term (arch))
{
// selection of solutions
eoPop < MOEOT > selectedSolutions;
select(arch, selectedSolutions);
// apply the local search to every selected solution
for (unsigned i=0; i<selectedSolutions.size(); i++)
{
mols(selectedSolutions[i], arch);
}
}
}
/**
* Applies the multi-objective local search to selected individuals contained in the archive if the stopping criteria is not verified
*/
void operator () ()
{
if (! term (arch))
{
// selection of solutions
eoPop < MOEOT > selectedSolutions;
select(arch, selectedSolutions);
// apply the local search to every selected solution
for (unsigned i=0; i<selectedSolutions.size(); i++)
{
mols(selectedSolutions[i], arch);
}
}
}
private:
/** stopping criteria */
eoContinue < MOEOT > & term;
/** selector */
eoSelect < MOEOT > & select;
/** multi-objective local search */
moeoLS < MOEOT, MOEOT > & mols;
/** archive */
moeoArchive < MOEOT > & arch;
/** stopping criteria */
eoContinue < MOEOT > & term;
/** selector */
eoSelect < MOEOT > & select;
/** multi-objective local search */
moeoLS < MOEOT, MOEOT > & mols;
/** archive */
moeoArchive < MOEOT > & arch;
};

View file

@ -22,180 +22,180 @@
/**
* Fitness assignment sheme based an Indicator proposed in:
* E. Zitzler, S. Künzli, "Indicator-Based Selection in Multiobjective Search", Proc. 8th International Conference on Parallel Problem Solving from Nature (PPSN VIII), pp. 832-842, Birmingham, UK (2004).
* This strategy is, for instance, used in IBEA.
* This strategy is, for instance, used in IBEA.
*/
template < class MOEOT >
class moeoIndicatorBasedFitnessAssignment : public moeoParetoBasedFitnessAssignment < MOEOT >
{
public:
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor.
* @param _metric the quality indicator
* @param _kappa the scaling factor
*/
moeoIndicatorBasedFitnessAssignment(moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * _metric, const double _kappa) : metric(_metric), kappa(_kappa)
{}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// 1 - setting of the bounds
setup(_pop);
// 2 - computing every indicator values
computeValues(_pop);
// 3 - setting fitnesses
setFitnesses(_pop);
}
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
vector < double > v;
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_objVec, _pop[i].objectiveVector());
}
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness( _pop[i].fitness() + exp(-v[i]/kappa) );
}
}
/**
* Updates the fitness values of the whole population _pop by taking the adding of the objective vector _objVec into account
* and returns the fitness value of _objVec.
* @param _pop the population
* @param _objecVec the objective vector
*/
double updateByAdding(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
vector < double > v;
// update every fitness values to take the new individual into account
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_objVec, _pop[i].objectiveVector());
}
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness( _pop[i].fitness() - exp(-v[i]/kappa) );
}
// compute the fitness of the new individual
v.clear();
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_pop[i].objectiveVector(), _objVec);
}
double result = 0;
for (unsigned i=0; i<v.size(); i++)
{
result -= exp(-v[i]/kappa);
}
return result;
}
/**
* Ctor.
* @param _metric the quality indicator
* @param _kappa the scaling factor
*/
moeoIndicatorBasedFitnessAssignment(moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * _metric, const double _kappa) : metric(_metric), kappa(_kappa)
{}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// 1 - setting of the bounds
setup(_pop);
// 2 - computing every indicator values
computeValues(_pop);
// 3 - setting fitnesses
setFitnesses(_pop);
}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
vector < double > v;
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_objVec, _pop[i].objectiveVector());
}
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness( _pop[i].fitness() + exp(-v[i]/kappa) );
}
}
/**
* Updates the fitness values of the whole population _pop by taking the adding of the objective vector _objVec into account
* and returns the fitness value of _objVec.
* @param _pop the population
* @param _objecVec the objective vector
*/
double updateByAdding(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{
vector < double > v;
// update every fitness values to take the new individual into account
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_objVec, _pop[i].objectiveVector());
}
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness( _pop[i].fitness() - exp(-v[i]/kappa) );
}
// compute the fitness of the new individual
v.clear();
v.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
v[i] = (*metric)(_pop[i].objectiveVector(), _objVec);
}
double result = 0;
for (unsigned i=0; i<v.size(); i++)
{
result -= exp(-v[i]/kappa);
}
return result;
}
protected:
/** the quality indicator */
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * metric;
/** the scaling factor */
double kappa;
/** the computed indicator values */
std::vector < std::vector<double> > values;
/** the quality indicator */
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * metric;
/** the scaling factor */
double kappa;
/** the computed indicator values */
std::vector < std::vector<double> > values;
/**
* Sets the bounds for every objective using the min and the max value for every objective vector of _pop
* @param _pop the population
*/
void setup(const eoPop < MOEOT > & _pop)
{
double min, max;
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
min = _pop[0].objectiveVector()[i];
max = _pop[0].objectiveVector()[i];
for (unsigned j=1; j<_pop.size(); j++)
{
min = std::min(min, _pop[j].objectiveVector()[i]);
max = std::max(max, _pop[j].objectiveVector()[i]);
}
// setting of the bounds for the objective i
(*metric).setup(min, max, i);
}
}
/**
* Sets the bounds for every objective using the min and the max value for every objective vector of _pop
* @param _pop the population
*/
void setup(const eoPop < MOEOT > & _pop)
{
double min, max;
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
min = _pop[0].objectiveVector()[i];
max = _pop[0].objectiveVector()[i];
for (unsigned j=1; j<_pop.size(); j++)
{
min = std::min(min, _pop[j].objectiveVector()[i]);
max = std::max(max, _pop[j].objectiveVector()[i]);
}
// setting of the bounds for the objective i
(*metric).setup(min, max, i);
}
}
/**
* Compute every indicator value in values (values[i] = I(_v[i], _o))
* @param _pop the population
*/
void computeValues(const eoPop < MOEOT > & _pop)
{
values.clear();
values.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
values[i].resize(_pop.size());
for (unsigned j=0; j<_pop.size(); j++)
{
if (i != j)
{
values[i][j] = (*metric)(_pop[i].objectiveVector(), _pop[j].objectiveVector());
}
}
}
}
/**
* Compute every indicator value in values (values[i] = I(_v[i], _o))
* @param _pop the population
*/
void computeValues(const eoPop < MOEOT > & _pop)
{
values.clear();
values.resize(_pop.size());
for (unsigned i=0; i<_pop.size(); i++)
{
values[i].resize(_pop.size());
for (unsigned j=0; j<_pop.size(); j++)
{
if (i != j)
{
values[i][j] = (*metric)(_pop[i].objectiveVector(), _pop[j].objectiveVector());
}
}
}
}
/**
* Sets the fitness value of the whple population
* @param _pop the population
*/
void setFitnesses(eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(computeFitness(i));
}
}
/**
* Sets the fitness value of the whple population
* @param _pop the population
*/
void setFitnesses(eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(computeFitness(i));
}
}
/**
* Returns the fitness value of the _idx th individual of the population
* @param _idx the index
*/
double computeFitness(const unsigned _idx)
{
double result = 0;
for (unsigned i=0; i<values.size(); i++)
{
if (i != _idx)
{
result -= exp(-values[i][_idx]/kappa);
}
}
return result;
}
/**
* Returns the fitness value of the _idx th individual of the population
* @param _idx the index
*/
double computeFitness(const unsigned _idx)
{
double result = 0;
for (unsigned i=0; i<values.size(); i++)
{
if (i != _idx)
{
result -= exp(-values[i][_idx]/kappa);
}
}
return result;
}
};
#endif /*MOEOINDICATORBASEDFITNESSASSIGNMENT_H_*/

View file

@ -33,177 +33,177 @@ class moeoIndicatorBasedLS : public moeoLS < MOEOT, eoPop < MOEOT > & >
{
public:
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor.
* @param _moveInit the move initializer
* @param _nextMove the neighborhood explorer
* @param _eval the full evaluation
* @param _moveIncrEval the incremental evaluation
* @param _fitnessAssignment the fitness assignment strategy
* @param _continuator the stopping criteria
*/
moeoIndicatorBasedLS(
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
moeoIndicatorBasedFitnessAssignment < MOEOT > & _fitnessAssignment,
eoContinue < MOEOT > & _continuator
) :
moveInit(_moveInit),
nextMove(_nextMove),
eval(_eval),
moveIncrEval(_moveIncrEval),
fitnessAssignment (_fitnessAssignment),
continuator (_continuator)
{}
/**
* Ctor.
* @param _moveInit the move initializer
* @param _nextMove the neighborhood explorer
* @param _eval the full evaluation
* @param _moveIncrEval the incremental evaluation
* @param _fitnessAssignment the fitness assignment strategy
* @param _continuator the stopping criteria
*/
moeoIndicatorBasedLS(
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
moeoIndicatorBasedFitnessAssignment < MOEOT > & _fitnessAssignment,
eoContinue < MOEOT > & _continuator
) :
moveInit(_moveInit),
nextMove(_nextMove),
eval(_eval),
moveIncrEval(_moveIncrEval),
fitnessAssignment (_fitnessAssignment),
continuator (_continuator)
{}
/**
* Apply the local search until a local archive does not change or
* another stopping criteria is met and update the archive _arch with new non-dominated solutions.
* @param _pop the initial population
* @param _arch the (updated) archive
*/
void operator() (eoPop < MOEOT > & _pop, moeoArchive < MOEOT > & _arch)
{
// evaluation of the objective values
for (unsigned i=0; i<_pop.size(); i++)
{
eval(_pop[i]);
}
// fitness assignment for the whole population
fitnessAssignment(_pop);
// creation of a local archive
moeoArchive < MOEOT > archive;
// creation of another local archive (for the stopping criteria)
moeoArchive < MOEOT > previousArchive;
// update the archive with the initial population
archive.update(_pop);
unsigned counter=0;
do
{
previousArchive.update(archive);
oneStep(_pop);
archive.update(_pop);
counter++;
} while ( (! archive.equals(previousArchive)) && (continuator(_arch)) );
_arch.update(archive);
cout << "\t=> " << counter << " step(s)" << endl;
}
/**
* Apply the local search until a local archive does not change or
* another stopping criteria is met and update the archive _arch with new non-dominated solutions.
* @param _pop the initial population
* @param _arch the (updated) archive
*/
void operator() (eoPop < MOEOT > & _pop, moeoArchive < MOEOT > & _arch)
{
// evaluation of the objective values
for (unsigned i=0; i<_pop.size(); i++)
{
eval(_pop[i]);
}
// fitness assignment for the whole population
fitnessAssignment(_pop);
// creation of a local archive
moeoArchive < MOEOT > archive;
// creation of another local archive (for the stopping criteria)
moeoArchive < MOEOT > previousArchive;
// update the archive with the initial population
archive.update(_pop);
unsigned counter=0;
do
{
previousArchive.update(archive);
oneStep(_pop);
archive.update(_pop);
counter++;
} while ( (! archive.equals(previousArchive)) && (continuator(_arch)) );
_arch.update(archive);
cout << "\t=> " << counter << " step(s)" << endl;
}
private:
/** the move initializer */
moMoveInit < Move > & moveInit;
/** the neighborhood explorer */
moNextMove < Move > & nextMove;
/** the full evaluation */
eoEvalFunc < MOEOT > & eval;
/** the incremental evaluation */
moeoMoveIncrEval < Move > & moveIncrEval;
/** the fitness assignment strategy */
moeoIndicatorBasedFitnessAssignment < MOEOT > & fitnessAssignment;
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/** the move initializer */
moMoveInit < Move > & moveInit;
/** the neighborhood explorer */
moNextMove < Move > & nextMove;
/** the full evaluation */
eoEvalFunc < MOEOT > & eval;
/** the incremental evaluation */
moeoMoveIncrEval < Move > & moveIncrEval;
/** the fitness assignment strategy */
moeoIndicatorBasedFitnessAssignment < MOEOT > & fitnessAssignment;
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/**
* Apply one step of the local search to the population _pop
* @param _pop the population
*/
void oneStep (eoPop < MOEOT > & _pop)
{
// the move
Move move;
// the objective vector and the fitness of the current solution
ObjectiveVector x_objVec;
double x_fitness;
// the index, the objective vector and the fitness of the worst solution in the population (-1 implies that the worst is the newly created one)
int worst_idx;
ObjectiveVector worst_objVec;
double worst_fitness;
// the index current of the current solution to be explored
unsigned i=0;
// initilization of the move for the first individual
moveInit(move, _pop[i]);
while (i<_pop.size() && continuator(_pop))
{
// x = one neigbour of pop[i]
// evaluate x in the objective space
x_objVec = moveIncrEval(move, _pop[i]);
// update every fitness values to take x into account and compute the fitness of x
x_fitness = fitnessAssignment.updateByAdding(_pop, x_objVec);
// who is the worst individual ?
worst_idx = -1;
worst_objVec = x_objVec;
worst_fitness = x_fitness;
for (unsigned j=0; j<_pop.size(); j++)
{
if (_pop[j].fitness() < worst_fitness)
{
worst_idx = j;
worst_objVec = _pop[j].objectiveVector();
worst_fitness = _pop[j].fitness();
}
}
// the worst solution is the new one
if (worst_idx == -1)
{
// if all its neighbours have been explored,
// let's explore the neighborhoud of the next individual
if (! nextMove(move, _pop[i]))
{
i++;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
}
// the worst solution is located before _pop[i]
else if (worst_idx <= i)
{
// the new solution takes place insteed of _pop[worst_idx]
_pop[worst_idx] = _pop[i];
move(_pop[worst_idx]);
_pop[worst_idx].objectiveVector(x_objVec);
_pop[worst_idx].fitness(x_fitness);
// let's explore the neighborhoud of the next individual
i++;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
// the worst solution is located after _pop[i]
else if (worst_idx > i)
{
// the new solution takes place insteed of _pop[i+1] and _pop[worst_idx] is deleted
_pop[worst_idx] = _pop[i+1];
_pop[i+1] = _pop[i];
move(_pop[i+1]);
_pop[i+1].objectiveVector(x_objVec);
_pop[i+1].fitness(x_fitness);
// do not explore the neighbors of the new solution immediately
i = i+2;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
// update fitness values
fitnessAssignment.updateByDeleting(_pop, worst_objVec);
}
}
/**
* Apply one step of the local search to the population _pop
* @param _pop the population
*/
void oneStep (eoPop < MOEOT > & _pop)
{
// the move
Move move;
// the objective vector and the fitness of the current solution
ObjectiveVector x_objVec;
double x_fitness;
// the index, the objective vector and the fitness of the worst solution in the population (-1 implies that the worst is the newly created one)
int worst_idx;
ObjectiveVector worst_objVec;
double worst_fitness;
// the index current of the current solution to be explored
unsigned i=0;
// initilization of the move for the first individual
moveInit(move, _pop[i]);
while (i<_pop.size() && continuator(_pop))
{
// x = one neigbour of pop[i]
// evaluate x in the objective space
x_objVec = moveIncrEval(move, _pop[i]);
// update every fitness values to take x into account and compute the fitness of x
x_fitness = fitnessAssignment.updateByAdding(_pop, x_objVec);
// who is the worst individual ?
worst_idx = -1;
worst_objVec = x_objVec;
worst_fitness = x_fitness;
for (unsigned j=0; j<_pop.size(); j++)
{
if (_pop[j].fitness() < worst_fitness)
{
worst_idx = j;
worst_objVec = _pop[j].objectiveVector();
worst_fitness = _pop[j].fitness();
}
}
// the worst solution is the new one
if (worst_idx == -1)
{
// if all its neighbours have been explored,
// let's explore the neighborhoud of the next individual
if (! nextMove(move, _pop[i]))
{
i++;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
}
// the worst solution is located before _pop[i]
else if (worst_idx <= i)
{
// the new solution takes place insteed of _pop[worst_idx]
_pop[worst_idx] = _pop[i];
move(_pop[worst_idx]);
_pop[worst_idx].objectiveVector(x_objVec);
_pop[worst_idx].fitness(x_fitness);
// let's explore the neighborhoud of the next individual
i++;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
// the worst solution is located after _pop[i]
else if (worst_idx > i)
{
// the new solution takes place insteed of _pop[i+1] and _pop[worst_idx] is deleted
_pop[worst_idx] = _pop[i+1];
_pop[i+1] = _pop[i];
move(_pop[i+1]);
_pop[i+1].objectiveVector(x_objVec);
_pop[i+1].fitness(x_fitness);
// do not explore the neighbors of the new solution immediately
i = i+2;
if (i<_pop.size())
{
// initilization of the move for the next individual
moveInit(move, _pop[i]);
}
}
// update fitness values
fitnessAssignment.updateByDeleting(_pop, worst_objVec);
}
}
};

View file

@ -42,125 +42,125 @@ class moeoIteratedIBMOLS : public moeoLS < MOEOT, eoPop < MOEOT > & >
{
public:
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor.
* @param _moveInit the move initializer
* @param _nextMove the neighborhood explorer
* @param _eval the full evaluation
* @param _moveIncrEval the incremental evaluation
* @param _fitnessAssignment the fitness assignment strategy
* @param _continuator the stopping criteria
* @param _monOp the monary operator
* @param _randomMonOp the random monary operator (or random initializer)
* @param _nNoiseIterations the number of iterations to apply the random noise
*/
moeoIteratedIBMOLS(
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
moeoIndicatorBasedFitnessAssignment < MOEOT > & _fitnessAssignment,
eoContinue < MOEOT > & _continuator,
eoMonOp < MOEOT > & _monOp,
eoMonOp < MOEOT > & _randomMonOp,
unsigned _nNoiseIterations=1
) :
ibmols(_moveInit, _nextMove, _eval, _moveIncrEval, _fitnessAssignment, _continuator),
eval(_eval),
continuator(_continuator),
monOp(_monOp),
randomMonOp(_randomMonOp),
nNoiseIterations(_nNoiseIterations)
{}
/**
* Ctor.
* @param _moveInit the move initializer
* @param _nextMove the neighborhood explorer
* @param _eval the full evaluation
* @param _moveIncrEval the incremental evaluation
* @param _fitnessAssignment the fitness assignment strategy
* @param _continuator the stopping criteria
* @param _monOp the monary operator
* @param _randomMonOp the random monary operator (or random initializer)
* @param _nNoiseIterations the number of iterations to apply the random noise
*/
moeoIteratedIBMOLS(
moMoveInit < Move > & _moveInit,
moNextMove < Move > & _nextMove,
eoEvalFunc < MOEOT > & _eval,
moeoMoveIncrEval < Move > & _moveIncrEval,
moeoIndicatorBasedFitnessAssignment < MOEOT > & _fitnessAssignment,
eoContinue < MOEOT > & _continuator,
eoMonOp < MOEOT > & _monOp,
eoMonOp < MOEOT > & _randomMonOp,
unsigned _nNoiseIterations=1
) :
ibmols(_moveInit, _nextMove, _eval, _moveIncrEval, _fitnessAssignment, _continuator),
eval(_eval),
continuator(_continuator),
monOp(_monOp),
randomMonOp(_randomMonOp),
nNoiseIterations(_nNoiseIterations)
{}
/**
* Apply the local search iteratively until the stopping criteria is met.
* @param _pop the initial population
* @param _arch the (updated) archive
*/
void operator() (eoPop < MOEOT > & _pop, moeoArchive < MOEOT > & _arch)
{
/**
* Apply the local search iteratively until the stopping criteria is met.
* @param _pop the initial population
* @param _arch the (updated) archive
*/
void operator() (eoPop < MOEOT > & _pop, moeoArchive < MOEOT > & _arch)
{
_arch.update(_pop);
cout << endl << endl << "***** IBMOLS 1" << endl;
unsigned counter = 2;
ibmols(_pop, _arch);
while (continuator(_arch))
{
// generate new solutions from the archive
generateNewSolutions(_pop, _arch);
cout << endl << endl << "***** IBMOLS " << counter++ << endl;
// apply the local search (the global archive is updated in the sub-function)
ibmols(_pop, _arch);
}
_arch.update(_pop);
cout << endl << endl << "***** IBMOLS 1" << endl;
unsigned counter = 2;
ibmols(_pop, _arch);
while (continuator(_arch))
{
// generate new solutions from the archive
generateNewSolutions(_pop, _arch);
cout << endl << endl << "***** IBMOLS " << counter++ << endl;
// apply the local search (the global archive is updated in the sub-function)
ibmols(_pop, _arch);
}
}
}
private:
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/** the local search to iterate */
moeoIndicatorBasedLS < MOEOT, Move > ibmols;
/** the full evaluation */
eoEvalFunc < MOEOT > & eval;
/** the monary operator */
eoMonOp < MOEOT > & monOp;
/** the random monary operator (or random initializer) */
eoMonOp < MOEOT > & randomMonOp;
/** the number of iterations to apply the random noise */
unsigned nNoiseIterations;
/** the stopping criteria */
eoContinue < MOEOT > & continuator;
/** the local search to iterate */
moeoIndicatorBasedLS < MOEOT, Move > ibmols;
/** the full evaluation */
eoEvalFunc < MOEOT > & eval;
/** the monary operator */
eoMonOp < MOEOT > & monOp;
/** the random monary operator (or random initializer) */
eoMonOp < MOEOT > & randomMonOp;
/** the number of iterations to apply the random noise */
unsigned nNoiseIterations;
/**
* Creates new population randomly initialized and/or initialized from the archive _arch.
* @param _pop the output population
* @param _arch the archive
*/
void generateNewSolutions(eoPop < MOEOT > & _pop, const moeoArchive < MOEOT > & _arch)
{
// shuffle vector for the random selection of individuals
vector<unsigned> shuffle;
shuffle.resize(std::max(_pop.size(), _arch.size()));
// init shuffle
for (unsigned i=0; i<shuffle.size(); i++)
{
shuffle[i] = i;
}
// randomize shuffle
UF_random_generator <unsigned int> gen;
std::random_shuffle(shuffle.begin(), shuffle.end(), gen);
// start the creation of new solutions
for (unsigned i=0; i<_pop.size(); i++)
{
if (shuffle[i] < _arch.size())
// the given archive contains the individual i
{
// add it to the resulting pop
_pop[i] = _arch[shuffle[i]];
// then, apply the operator nIterationsNoise times
for (unsigned j=0; j<nNoiseIterations; j++)
{
monOp(_pop[i]);
}
}
else
// a randomly generated solution needs to be added
{
// random initialization
randomMonOp(_pop[i]);
}
// evaluation of the new individual
_pop[i].invalidate();
eval(_pop[i]);
}
}
/**
* Creates new population randomly initialized and/or initialized from the archive _arch.
* @param _pop the output population
* @param _arch the archive
*/
void generateNewSolutions(eoPop < MOEOT > & _pop, const moeoArchive < MOEOT > & _arch)
{
// shuffle vector for the random selection of individuals
vector<unsigned> shuffle;
shuffle.resize(std::max(_pop.size(), _arch.size()));
// init shuffle
for (unsigned i=0; i<shuffle.size(); i++)
{
shuffle[i] = i;
}
// randomize shuffle
UF_random_generator <unsigned int> gen;
std::random_shuffle(shuffle.begin(), shuffle.end(), gen);
// start the creation of new solutions
for (unsigned i=0; i<_pop.size(); i++)
{
if (shuffle[i] < _arch.size())
// the given archive contains the individual i
{
// add it to the resulting pop
_pop[i] = _arch[shuffle[i]];
// then, apply the operator nIterationsNoise times
for (unsigned j=0; j<nNoiseIterations; j++)
{
monOp(_pop[i]);
}
}
else
// a randomly generated solution needs to be added
{
// random initialization
randomMonOp(_pop[i]);
}
// evaluation of the new individual
_pop[i].invalidate();
eval(_pop[i]);
}
}
@ -168,47 +168,47 @@ private:
///////////////////////////////////////////////////////////////////////////////////////////////////////
// A DEVELOPPER RAPIDEMENT POUR TESTER AVEC CROSSOVER //
/*
void generateNewSolutions2(eoPop < MOEOT > & _pop, const moeoArchive < MOEOT > & _arch)
{
// here, we must have a QuadOp !
//eoQuadOp < MOEOT > quadOp;
rsCrossQuad quadOp;
// shuffle vector for the random selection of individuals
vector<unsigned> shuffle;
shuffle.resize(_arch.size());
// init shuffle
for (unsigned i=0; i<shuffle.size(); i++)
{
shuffle[i] = i;
}
// randomize shuffle
UF_random_generator <unsigned int> gen;
std::random_shuffle(shuffle.begin(), shuffle.end(), gen);
// start the creation of new solutions
unsigned i=0;
while ((i<_pop.size()-1) && (i<_arch.size()-1))
{
_pop[i] = _arch[shuffle[i]];
_pop[i+1] = _arch[shuffle[i+1]];
// then, apply the operator nIterationsNoise times
for (unsigned j=0; j<nNoiseIterations; j++)
{
quadOp(_pop[i], _pop[i+1]);
}
eval(_pop[i]);
eval(_pop[i+1]);
i=i+2;
}
// do we have to add some random solutions ?
while (i<_pop.size())
{
randomMonOp(_pop[i]);
eval(_pop[i]);
i++;
}
}
*/
/*
void generateNewSolutions2(eoPop < MOEOT > & _pop, const moeoArchive < MOEOT > & _arch)
{
// here, we must have a QuadOp !
//eoQuadOp < MOEOT > quadOp;
rsCrossQuad quadOp;
// shuffle vector for the random selection of individuals
vector<unsigned> shuffle;
shuffle.resize(_arch.size());
// init shuffle
for (unsigned i=0; i<shuffle.size(); i++)
{
shuffle[i] = i;
}
// randomize shuffle
UF_random_generator <unsigned int> gen;
std::random_shuffle(shuffle.begin(), shuffle.end(), gen);
// start the creation of new solutions
unsigned i=0;
while ((i<_pop.size()-1) && (i<_arch.size()-1))
{
_pop[i] = _arch[shuffle[i]];
_pop[i+1] = _arch[shuffle[i+1]];
// then, apply the operator nIterationsNoise times
for (unsigned j=0; j<nNoiseIterations; j++)
{
quadOp(_pop[i], _pop[i+1]);
}
eval(_pop[i]);
eval(_pop[i+1]);
i=i+2;
}
// do we have to add some random solutions ?
while (i<_pop.size())
{
randomMonOp(_pop[i]);
eval(_pop[i]);
i++;
}
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -21,7 +21,7 @@
* Starting from a Type (i.e.: an individual, a pop, an archive...), it produces a set of new non-dominated solutions.
*/
template < class MOEOT, class Type >
class moeoLS: public eoBF < Type, moeoArchive < MOEOT > &, void >
{};
class moeoLS: public eoBF < Type, moeoArchive < MOEOT > &, void >
{};
#endif /*MOEOLS_H_*/

View file

@ -5,8 +5,8 @@
#include <eoFunctor.h>
template < class Move >
template < class Move >
class moeoMoveIncrEval : public eoBF < const Move &, const typename Move::EOType &, typename Move::EOType::ObjectiveVector >
{};
{};
#endif

View file

@ -28,99 +28,99 @@
/**
* The NSGA-II algorithm as described in:
* Deb, K., S. Agrawal, A. Pratap, and T. Meyarivan : "A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II".
* Deb, K., S. Agrawal, A. Pratap, and T. Meyarivan : "A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II".
* In IEEE Transactions on Evolutionary Computation, Vol. 6, No 2, pp 182-197 (April 2002).
* This class builds the NSGA-II algorithm only by using the components of the ParadisEO-MOEO framework.
*/
template < class MOEOT >
template < class MOEOT >
class moeoNSGAII: public moeoEA < MOEOT >
{
public:
/**
* This constructor builds the algorithm as descibed in the paper.
* @param _max_gen number of generations before stopping
* @param _eval evaluation function
* @param _op variation operator
*/
moeoNSGAII (unsigned _max_gen, eoEvalFunc < MOEOT > & _eval, eoGenOp < MOEOT > &_op) :
continuator (*(new eoGenContinue < MOEOT > (_max_gen))), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, _op), breed (genBreed)
/**
* This constructor builds the algorithm as descibed in the paper.
* @param _max_gen number of generations before stopping
* @param _eval evaluation function
* @param _op variation operator
*/
moeoNSGAII (unsigned _max_gen, eoEvalFunc < MOEOT > & _eval, eoGenOp < MOEOT > &_op) :
continuator (*(new eoGenContinue < MOEOT > (_max_gen))), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, _op), breed (genBreed)
{}
/**
* Ctor taking _max_gen, crossover and mutation.
* @param _max_gen number of generations before stopping
* @param _eval evaluation function
* @param _crossover crossover
* @param _pCross crossover probability
* @param _mutation mutation
* @param _pMut mutation probability
* @param _eval evaluation function
* @param _crossover crossover
* @param _pCross crossover probability
* @param _mutation mutation
* @param _pMut mutation probability
*/
moeoNSGAII (unsigned _max_gen, eoEvalFunc < MOEOT > &_eval, eoQuadOp < MOEOT > & _crossover, double _pCross, eoMonOp < MOEOT > & _mutation, double _pMut) :
continuator (*(new eoGenContinue < MOEOT > (_max_gen))), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, *new eoSGAGenOp < MOEOT > (_crossover, _pCross, _mutation, _pMut)), breed (genBreed)
moeoNSGAII (unsigned _max_gen, eoEvalFunc < MOEOT > &_eval, eoQuadOp < MOEOT > & _crossover, double _pCross, eoMonOp < MOEOT > & _mutation, double _pMut) :
continuator (*(new eoGenContinue < MOEOT > (_max_gen))), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, *new eoSGAGenOp < MOEOT > (_crossover, _pCross, _mutation, _pMut)), breed (genBreed)
{}
/**
* Ctor taking a continuator instead of _gen_max.
* @param _continuator stopping criteria
* @param _eval evaluation function
* @param _op variation operator
*/
moeoNSGAII (eoContinue < MOEOT > & _continuator, eoEvalFunc < MOEOT > & _eval, eoGenOp < MOEOT > & _op) :
continuator (_continuator), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, _op), breed (genBreed)
moeoNSGAII (eoContinue < MOEOT > & _continuator, eoEvalFunc < MOEOT > & _eval, eoGenOp < MOEOT > & _op) :
continuator (_continuator), eval (_eval), loopEval (_eval), popEval (loopEval), select (2), // binary tournament selection
replace (fitnessAssignment, diversityAssignment), genBreed (select, _op), breed (genBreed)
{}
/**
* Apply a few generation of evolution to the population _pop.
* @param _pop the population
*/
virtual void operator () (eoPop < MOEOT > &_pop)
{
eoPop < MOEOT > offspring, empty_pop;
popEval (empty_pop, _pop); // a first eval of _pop
// evaluate fitness and diversity
fitnessAssignment(_pop);
diversityAssignment(_pop);
do
{
// generate offspring, worths are recalculated if necessary
breed (_pop, offspring);
// eval of offspring
popEval (_pop, offspring);
// after replace, the new pop is in _pop. Worths are recalculated if necessary
replace (_pop, offspring);
} while (continuator (_pop));
eoPop < MOEOT > offspring, empty_pop;
popEval (empty_pop, _pop); // a first eval of _pop
// evaluate fitness and diversity
fitnessAssignment(_pop);
diversityAssignment(_pop);
do
{
// generate offspring, worths are recalculated if necessary
breed (_pop, offspring);
// eval of offspring
popEval (_pop, offspring);
// after replace, the new pop is in _pop. Worths are recalculated if necessary
replace (_pop, offspring);
} while (continuator (_pop));
}
protected:
/** stopping criteria */
eoContinue < MOEOT > & continuator;
/** evaluation function */
eoEvalFunc < MOEOT > & eval;
/** to evaluate the whole population */
eoPopLoopEval < MOEOT > loopEval;
/** to evaluate the whole population */
eoPopEvalFunc < MOEOT > & popEval;
/** general breeder */
eoGeneralBreeder < MOEOT > genBreed;
/** breeder */
eoBreed < MOEOT > & breed;
/** binary tournament selection */
moeoDetTournamentSelect < MOEOT > select;
/** elitist replacement */
moeoElitistReplacement < MOEOT > replace;
/** fitness assignment used in NSGA-II */
moeoFastNonDominatedSortingFitnessAssignment < MOEOT > fitnessAssignment;
/** Diversity assignment used in NSGA-II */
moeoCrowdingDistanceDiversityAssignment < MOEOT > diversityAssignment;
/** stopping criteria */
eoContinue < MOEOT > & continuator;
/** evaluation function */
eoEvalFunc < MOEOT > & eval;
/** to evaluate the whole population */
eoPopLoopEval < MOEOT > loopEval;
/** to evaluate the whole population */
eoPopEvalFunc < MOEOT > & popEval;
/** general breeder */
eoGeneralBreeder < MOEOT > genBreed;
/** breeder */
eoBreed < MOEOT > & breed;
/** binary tournament selection */
moeoDetTournamentSelect < MOEOT > select;
/** elitist replacement */
moeoElitistReplacement < MOEOT > replace;
/** fitness assignment used in NSGA-II */
moeoFastNonDominatedSortingFitnessAssignment < MOEOT > fitnessAssignment;
/** Diversity assignment used in NSGA-II */
moeoCrowdingDistanceDiversityAssignment < MOEOT > diversityAssignment;
};

View file

@ -19,8 +19,8 @@
#include <moeoObjectiveVectorComparator.h>
/**
* Abstract class allowing to represent a solution in the objective space (phenotypic representation).
* The template argument ObjectiveVectorTraits defaults to moeoObjectiveVectorTraits,
* Abstract class allowing to represent a solution in the objective space (phenotypic representation).
* The template argument ObjectiveVectorTraits defaults to moeoObjectiveVectorTraits,
* but it can be replaced at will by any other class that implements the static functions defined therein.
* Some static funtions to access to the traits characteristics are re-defined in order not to write a lot of typedef's.
*/
@ -29,170 +29,170 @@ class moeoObjectiveVector
{
public:
/** The traits of objective vectors */
typedef ObjectiveVectorTraits Traits;
/**
* Parameters setting (for the objective vector of any solution)
* @param _nObjectives the number of objectives
* @param _bObjectives the min/max vector (true = min / false = max)
*/
static void setup(unsigned _nObjectives, std::vector < bool > & _bObjectives)
{
ObjectiveVectorTraits::setup(_nObjectives, _bObjectives);
}
/**
* Returns the number of objectives
*/
static unsigned nObjectives()
{
return ObjectiveVectorTraits::nObjectives();
}
/**
* Returns true if the _ith objective have to be minimized
* @param _i the index
*/
static bool minimizing(unsigned _i) {
return ObjectiveVectorTraits::minimizing(_i);
}
/**
* Returns true if the _ith objective have to be maximized
* @param _i the index
*/
static bool maximizing(unsigned _i) {
return ObjectiveVectorTraits::maximizing(_i);
}
/** The traits of objective vectors */
typedef ObjectiveVectorTraits Traits;
/**
* Parameters setting (for the objective vector of any solution)
* @param _nObjectives the number of objectives
* @param _bObjectives the min/max vector (true = min / false = max)
*/
static void setup(unsigned _nObjectives, std::vector < bool > & _bObjectives)
{
ObjectiveVectorTraits::setup(_nObjectives, _bObjectives);
}
/**
* Returns the number of objectives
*/
static unsigned nObjectives()
{
return ObjectiveVectorTraits::nObjectives();
}
/**
* Returns true if the _ith objective have to be minimized
* @param _i the index
*/
static bool minimizing(unsigned _i) {
return ObjectiveVectorTraits::minimizing(_i);
}
/**
* Returns true if the _ith objective have to be maximized
* @param _i the index
*/
static bool maximizing(unsigned _i) {
return ObjectiveVectorTraits::maximizing(_i);
}
};
/**
* This class allows to represent a solution in the objective space (phenotypic representation) by a std::vector of doubles,
* i.e. that an objective value is represented using a double, and this for any objective.
* i.e. that an objective value is represented using a double, and this for any objective.
*/
template < class ObjectiveVectorTraits >
class moeoObjectiveVectorDouble : public moeoObjectiveVector < ObjectiveVectorTraits >, public std::vector < double >
{
public:
using std::vector< double >::size;
using std::vector< double >::operator[];
/**
* Ctor
*/
moeoObjectiveVectorDouble() : std::vector < double > (ObjectiveVectorTraits::nObjectives(), 0.0) {}
/**
* Ctor from a vector of doubles
* @param _v the std::vector < double >
*/
moeoObjectiveVectorDouble(std::vector <double> & _v) : std::vector < double > (_v) {}
/**
* Returns true if the current objective vector dominates _other according to the Pareto dominance relation
* (but it's better to use a moeoObjectiveVectorComparator object to compare solutions)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool dominates(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
moeoParetoObjectiveVectorComparator < moeoObjectiveVectorDouble<ObjectiveVectorTraits> > comparator;
return comparator(*this, _other);
}
/**
* Returns true if the current objective vector is equal to _other (according to a tolerance value)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator==(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
for (unsigned i=0; i < size(); i++)
{
if ( fabs(operator[](i) - _other[i]) > ObjectiveVectorTraits::tolerance() )
{
return false;
}
}
return true;
}
/**
* Returns true if the current objective vector is different than _other (according to a tolerance value)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator!=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return ! operator==(_other);
}
/**
* Returns true if the current objective vector is smaller than _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator<(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
for (unsigned i=0; i < size(); i++)
{
if ( fabs(operator[](i) - _other[i]) > ObjectiveVectorTraits::tolerance() )
{
if (operator[](i) < _other[i])
{
return true;
}
else
{
return false;
}
}
}
return false;
}
/**
* Returns true if the current objective vector is greater than _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator>(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return _other < *this;
}
/**
* Returns true if the current objective vector is smaller than or equal to _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator<=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return operator==(_other) || operator<(_other);
}
/**
* Returns true if the current objective vector is greater than or equal to _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator>=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return operator==(_other) || operator>(_other);
}
public:
using std::vector< double >::size;
using std::vector< double >::operator[];
/**
* Ctor
*/
moeoObjectiveVectorDouble() : std::vector < double > (ObjectiveVectorTraits::nObjectives(), 0.0) {}
/**
* Ctor from a vector of doubles
* @param _v the std::vector < double >
*/
moeoObjectiveVectorDouble(std::vector <double> & _v) : std::vector < double > (_v) {}
/**
* Returns true if the current objective vector dominates _other according to the Pareto dominance relation
* (but it's better to use a moeoObjectiveVectorComparator object to compare solutions)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool dominates(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
moeoParetoObjectiveVectorComparator < moeoObjectiveVectorDouble<ObjectiveVectorTraits> > comparator;
return comparator(*this, _other);
}
/**
* Returns true if the current objective vector is equal to _other (according to a tolerance value)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator==(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
for (unsigned i=0; i < size(); i++)
{
if ( fabs(operator[](i) - _other[i]) > ObjectiveVectorTraits::tolerance() )
{
return false;
}
}
return true;
}
/**
* Returns true if the current objective vector is different than _other (according to a tolerance value)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator!=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return ! operator==(_other);
}
/**
* Returns true if the current objective vector is smaller than _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator<(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
for (unsigned i=0; i < size(); i++)
{
if ( fabs(operator[](i) - _other[i]) > ObjectiveVectorTraits::tolerance() )
{
if (operator[](i) < _other[i])
{
return true;
}
else
{
return false;
}
}
}
return false;
}
/**
* Returns true if the current objective vector is greater than _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator>(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return _other < *this;
}
/**
* Returns true if the current objective vector is smaller than or equal to _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator<=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return operator==(_other) || operator<(_other);
}
/**
* Returns true if the current objective vector is greater than or equal to _other on the first objective, then on the second, and so on
* (can be usefull for sorting/printing)
* @param _other the other moeoObjectiveVectorDouble object to compare with
*/
bool operator>=(const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _other) const
{
return operator==(_other) || operator>(_other);
}
};
@ -205,11 +205,11 @@ public:
template < class ObjectiveVectorTraits >
std::ostream & operator<<(std::ostream & _os, const moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _objectiveVector)
{
for (unsigned i=0; i<_objectiveVector.size(); i++)
{
_os << _objectiveVector[i] << '\t';
}
return _os;
for (unsigned i=0; i<_objectiveVector.size(); i++)
{
_os << _objectiveVector[i] << '\t';
}
return _os;
}
/**
@ -220,12 +220,12 @@ std::ostream & operator<<(std::ostream & _os, const moeoObjectiveVectorDouble <
template < class ObjectiveVectorTraits >
std::istream & operator>>(std::istream & _is, moeoObjectiveVectorDouble < ObjectiveVectorTraits > & _objectiveVector)
{
_objectiveVector = moeoObjectiveVectorDouble < ObjectiveVectorTraits > ();
for (unsigned i=0; i<_objectiveVector.size(); i++)
{
_is >> _objectiveVector[i];
}
return _is;
_objectiveVector = moeoObjectiveVectorDouble < ObjectiveVectorTraits > ();
for (unsigned i=0; i<_objectiveVector.size(); i++)
{
_is >> _objectiveVector[i];
}
return _is;
}
#endif /*MOEOOBJECTIVEVECTOR_H_*/

View file

@ -18,11 +18,11 @@
/**
* Abstract class allowing to compare 2 objective vectors.
* The template argument ObjectiveVector have to be a moeoObjectiveVector.
* The template argument ObjectiveVector have to be a moeoObjectiveVector.
*/
template < class ObjectiveVector >
class moeoObjectiveVectorComparator : public eoBF < const ObjectiveVector &, const ObjectiveVector &, bool >
{};
{};
/**
@ -32,48 +32,48 @@ template < class ObjectiveVector >
class moeoParetoObjectiveVectorComparator : public moeoObjectiveVectorComparator < ObjectiveVector >
{
public:
/**
* Returns true if _objectiveVector1 dominates _objectiveVector2
* @param _objectiveVector1 the first objective vector
* @param _objectiveVector2 the second objective vector
*/
bool operator()(const ObjectiveVector & _objectiveVector1, const ObjectiveVector & _objectiveVector2)
{
bool dom = false;
for (unsigned i=0; i<ObjectiveVector::nObjectives(); i++)
{
// first, we have to check if the 2 objective values are not equal for the ith objective
if ( fabs(_objectiveVector1[i] - _objectiveVector2[i]) > ObjectiveVector::Traits::tolerance() )
{
// if the ith objective have to be minimized...
if (ObjectiveVector::minimizing(i))
{
if (_objectiveVector1[i] < _objectiveVector2[i])
{
dom = true; //_objectiveVector1[i] is better than _objectiveVector2[i]
}
else
{
return false; //_objectiveVector1 cannot dominate _objectiveVector2
}
}
// if the ith objective have to be maximized...
else if (ObjectiveVector::maximizing(i))
{
if (_objectiveVector1[i] > _objectiveVector2[i])
{
dom = true; //_objectiveVector1[i] is better than _objectiveVector2[i]
}
else
{
return false; //_objectiveVector1 cannot dominate _objectiveVector2
}
}
}
}
return dom;
}
/**
* Returns true if _objectiveVector1 dominates _objectiveVector2
* @param _objectiveVector1 the first objective vector
* @param _objectiveVector2 the second objective vector
*/
bool operator()(const ObjectiveVector & _objectiveVector1, const ObjectiveVector & _objectiveVector2)
{
bool dom = false;
for (unsigned i=0; i<ObjectiveVector::nObjectives(); i++)
{
// first, we have to check if the 2 objective values are not equal for the ith objective
if ( fabs(_objectiveVector1[i] - _objectiveVector2[i]) > ObjectiveVector::Traits::tolerance() )
{
// if the ith objective have to be minimized...
if (ObjectiveVector::minimizing(i))
{
if (_objectiveVector1[i] < _objectiveVector2[i])
{
dom = true; //_objectiveVector1[i] is better than _objectiveVector2[i]
}
else
{
return false; //_objectiveVector1 cannot dominate _objectiveVector2
}
}
// if the ith objective have to be maximized...
else if (ObjectiveVector::maximizing(i))
{
if (_objectiveVector1[i] > _objectiveVector2[i])
{
dom = true; //_objectiveVector1[i] is better than _objectiveVector2[i]
}
else
{
return false; //_objectiveVector1 cannot dominate _objectiveVector2
}
}
}
}
return dom;
}
};
@ -89,76 +89,76 @@ class moeoGDominanceObjectiveVectorComparator : public moeoObjectiveVectorCompar
{
public:
/**
* Ctor.
* @param _ref the reference point
*/
moeoGDominanceObjectiveVectorComparator(ObjectiveVector _ref) : ref(_ref)
{}
/**
* Ctor.
* @param _ref the reference point
*/
moeoGDominanceObjectiveVectorComparator(ObjectiveVector _ref) : ref(_ref)
{}
/**
* Returns true if _objectiveVector1 g-dominates _objectiveVector2.
* @param _objectiveVector1 the first objective vector
* @param _objectiveVector2 the second objective vector
*/
bool operator()(const ObjectiveVector & _objectiveVector1, const ObjectiveVector & _objectiveVector2)
{
unsigned flag1 = flag(_objectiveVector1);
unsigned flag2 = flag(_objectiveVector2);
if (flag1==0)
{
// cannot dominate
return false;
}
else if ( (flag1==1) && (flag2==0) )
{
// dominates
return true;
}
else // (flag1==1) && (flag2==1)
{
// both are on the good region, so let's use the classical Pareto dominance
return paretoComparator(_objectiveVector1, _objectiveVector2);
}
}
/**
* Returns true if _objectiveVector1 g-dominates _objectiveVector2.
* @param _objectiveVector1 the first objective vector
* @param _objectiveVector2 the second objective vector
*/
bool operator()(const ObjectiveVector & _objectiveVector1, const ObjectiveVector & _objectiveVector2)
{
unsigned flag1 = flag(_objectiveVector1);
unsigned flag2 = flag(_objectiveVector2);
if (flag1==0)
{
// cannot dominate
return false;
}
else if ( (flag1==1) && (flag2==0) )
{
// dominates
return true;
}
else // (flag1==1) && (flag2==1)
{
// both are on the good region, so let's use the classical Pareto dominance
return paretoComparator(_objectiveVector1, _objectiveVector2);
}
}
private:
/** the reference point */
ObjectiveVector ref;
/** Pareto comparator */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/** the reference point */
ObjectiveVector ref;
/** Pareto comparator */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator;
/**
* Returns the flag of _objectiveVector according to the reference point
* @param _objectiveVector the first objective vector
*/
unsigned flag(const ObjectiveVector & _objectiveVector)
{
unsigned result=1;
for (unsigned i=0; i<ref.nObjectives(); i++)
{
if (_objectiveVector[i] > ref[i])
{
result=0;
}
}
if (result==0)
{
result=1;
for (unsigned i=0; i<ref.nObjectives(); i++)
{
if (_objectiveVector[i] < ref[i])
{
result=0;
}
}
}
return result;
}
/**
* Returns the flag of _objectiveVector according to the reference point
* @param _objectiveVector the first objective vector
*/
unsigned flag(const ObjectiveVector & _objectiveVector)
{
unsigned result=1;
for (unsigned i=0; i<ref.nObjectives(); i++)
{
if (_objectiveVector[i] > ref[i])
{
result=0;
}
}
if (result==0)
{
result=1;
for (unsigned i=0; i<ref.nObjectives(); i++)
{
if (_objectiveVector[i] < ref[i])
{
result=0;
}
}
}
return result;
}
};

View file

@ -24,79 +24,79 @@ class moeoObjectiveVectorTraits
{
public:
/** The tolerance value (used to compare solutions) */
const static double tol = 1e-6;
/**
* Parameters setting
* @param _nObjectives the number of objectives
* @param _bObjectives the min/max vector (true = min / false = max)
*/
static void setup(unsigned _nObjectives, std::vector < bool > & _bObjectives)
{
// in case the number of objectives was already set to a different value
if ( nObj && (nObj != _nObjectives) ) {
std::cout << "WARNING\n";
std::cout << "WARNING : the number of objectives are changing\n";
std::cout << "WARNING : Make sure all existing objects are destroyed\n";
std::cout << "WARNING\n";
}
// number of objectives
nObj = _nObjectives;
// min/max vector
bObj = _bObjectives;
// in case the number of objectives and the min/max vector size don't match
if (nObj != bObj.size())
throw std::runtime_error("Number of objectives and min/max size don't match in moeoObjectiveVectorTraits::setup");
}
/**
* Returns the number of objectives
*/
static unsigned nObjectives()
{
// in case the number of objectives would not be assigned yet
if (! nObj)
throw std::runtime_error("Number of objectives not assigned in moeoObjectiveVectorTraits");
return nObj;
}
/**
* Returns true if the _ith objective have to be minimized
* @param _i the index
*/
static bool minimizing(unsigned _i)
{
// in case there would be a wrong index
if (_i >= bObj.size())
throw std::runtime_error("Wrong index in moeoObjectiveVectorTraits");
return bObj[_i];
}
/**
* Returns true if the _ith objective have to be maximized
* @param _i the index
*/
static bool maximizing(unsigned _i) {
return (! minimizing(_i));
}
/**
* Returns the tolerance value (to compare solutions)
*/
static double tolerance()
{
return tol;
}
/** The tolerance value (used to compare solutions) */
const static double tol = 1e-6;
/**
* Parameters setting
* @param _nObjectives the number of objectives
* @param _bObjectives the min/max vector (true = min / false = max)
*/
static void setup(unsigned _nObjectives, std::vector < bool > & _bObjectives)
{
// in case the number of objectives was already set to a different value
if ( nObj && (nObj != _nObjectives) ) {
std::cout << "WARNING\n";
std::cout << "WARNING : the number of objectives are changing\n";
std::cout << "WARNING : Make sure all existing objects are destroyed\n";
std::cout << "WARNING\n";
}
// number of objectives
nObj = _nObjectives;
// min/max vector
bObj = _bObjectives;
// in case the number of objectives and the min/max vector size don't match
if (nObj != bObj.size())
throw std::runtime_error("Number of objectives and min/max size don't match in moeoObjectiveVectorTraits::setup");
}
/**
* Returns the number of objectives
*/
static unsigned nObjectives()
{
// in case the number of objectives would not be assigned yet
if (! nObj)
throw std::runtime_error("Number of objectives not assigned in moeoObjectiveVectorTraits");
return nObj;
}
/**
* Returns true if the _ith objective have to be minimized
* @param _i the index
*/
static bool minimizing(unsigned _i)
{
// in case there would be a wrong index
if (_i >= bObj.size())
throw std::runtime_error("Wrong index in moeoObjectiveVectorTraits");
return bObj[_i];
}
/**
* Returns true if the _ith objective have to be maximized
* @param _i the index
*/
static bool maximizing(unsigned _i) {
return (! minimizing(_i));
}
/**
* Returns the tolerance value (to compare solutions)
*/
static double tolerance()
{
return tol;
}
private:
/** The number of objectives */
static unsigned nObj;
/** The min/max vector */
static std::vector < bool > bObj;
/** The number of objectives */
static unsigned nObj;
/** The min/max vector */
static std::vector < bool > bObj;
};
#endif /*MOEOOBJECTIVEVECTORTRAITS_H_*/

View file

@ -26,83 +26,83 @@ class moeoReferencePointIndicatorBasedFitnessAssignment : public moeoFitnessAssi
{
public:
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor
* @param _refPoint the reference point
* @param _metric the quality indicator
*/
moeoReferencePointIndicatorBasedFitnessAssignment (const ObjectiveVector _refPoint, moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * _metric) :
refPoint(_refPoint), metric(_metric)
{}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// 1 - setting of the bounds
setup(_pop);
// 2 - setting fitnesses
setFitnesses(_pop);
}
/** The type of objective vector */
typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/**
* Ctor
* @param _refPoint the reference point
* @param _metric the quality indicator
*/
moeoReferencePointIndicatorBasedFitnessAssignment (const ObjectiveVector _refPoint, moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * _metric) :
refPoint(_refPoint), metric(_metric)
{}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
// nothing to do ;-)
}
/**
* Sets the fitness values for every solution contained in the population _pop
* @param _pop the population
*/
void operator()(eoPop < MOEOT > & _pop)
{
// 1 - setting of the bounds
setup(_pop);
// 2 - setting fitnesses
setFitnesses(_pop);
}
/**
* Updates the fitness values of the whole population _pop by taking the deletion of the objective vector _objVec into account.
* @param _pop the population
* @param _objecVec the objective vector
*/
void updateByDeleting(eoPop < MOEOT > & _pop, MOEOT & _moeo)
{
// nothing to do ;-)
}
protected:
/** the reference point */
ObjectiveVector refPoint;
/** the quality indicator */
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * metric;
/** the reference point */
ObjectiveVector refPoint;
/** the quality indicator */
moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > * metric;
/**
* Sets the bounds for every objective using the min and the max value for every objective vector of _pop (and the reference point)
* @param _pop the population
*/
void setup(const eoPop < MOEOT > & _pop)
{
double min, max;
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
min = refPoint[i];
max = refPoint[i];
for (unsigned j=0; j<_pop.size(); j++)
{
min = std::min(min, _pop[j].objectiveVector()[i]);
max = std::max(max, _pop[j].objectiveVector()[i]);
}
// setting of the bounds for the objective i
(*metric).setup(min, max, i);
}
}
/**
* Sets the bounds for every objective using the min and the max value for every objective vector of _pop (and the reference point)
* @param _pop the population
*/
void setup(const eoPop < MOEOT > & _pop)
{
double min, max;
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{
min = refPoint[i];
max = refPoint[i];
for (unsigned j=0; j<_pop.size(); j++)
{
min = std::min(min, _pop[j].objectiveVector()[i]);
max = std::max(max, _pop[j].objectiveVector()[i]);
}
// setting of the bounds for the objective i
(*metric).setup(min, max, i);
}
}
/**
* Sets the fitness of every individual contained in the population _pop
* @param _pop the population
*/
void setFitnesses(eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(- (*metric)(_pop[i].objectiveVector(), refPoint) );
}
}
/**
* Sets the fitness of every individual contained in the population _pop
* @param _pop the population
*/
void setFitnesses(eoPop < MOEOT > & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
{
_pop[i].fitness(- (*metric)(_pop[i].objectiveVector(), refPoint) );
}
}
};

View file

@ -20,6 +20,6 @@
*/
template < class MOEOT >
class moeoReplacement : public eoReplacement < MOEOT >
{};
{};
#endif /*MOEOREPLACEMENT_H_*/

View file

@ -27,63 +27,63 @@ class moeoSelectFromPopAndArch : public moeoSelectOne < MOEOT >
{
public:
/**
* Ctor
* @param _popSelectOne the population's selection operator
* @param _archSelectOne the archive's selection operator
* @param _arch the archive
* @param _ratioFromPop the ratio of selected individuals from the population
*/
moeoSelectFromPopAndArch (moeoSelectOne < MOEOT > & _popSelectOne, moeoSelectOne < MOEOT > _archSelectOne, moeoArchive < MOEOT > & _arch, double _ratioFromPop=0.5)
: popSelectOne(_popSelectOne), archSelectOne(_archSelectOne), arch(_arch), ratioFromPop(_ratioFromPop)
{}
/**
* Defaulr ctor - the archive's selection operator is a random selector
* @param _popSelectOne the population's selection operator
* @param _arch the archive
* @param _ratioFromPop the ratio of selected individuals from the population
*/
moeoSelectFromPopAndArch (moeoSelectOne < MOEOT > & _popSelectOne, moeoArchive < MOEOT > & _arch, double _ratioFromPop=0.5)
: popSelectOne(_popSelectOne), archSelectOne(randomSelectOne), arch(_arch), ratioFromPop(_ratioFromPop)
{}
/**
* The selection process
*/
virtual const MOEOT & operator () (const eoPop < MOEOT > & pop)
{
if (arch.size() > 0)
if (rng.flip(ratioFromPop))
return popSelectOne(pop);
else
return archSelectOne(arch);
else
return popSelectOne(pop);
}
/**
* Setups some population stats
*/
virtual void setup (const eoPop < MOEOT > & _pop)
{
popSelectOne.setup(_pop);
}
/**
* Ctor
* @param _popSelectOne the population's selection operator
* @param _archSelectOne the archive's selection operator
* @param _arch the archive
* @param _ratioFromPop the ratio of selected individuals from the population
*/
moeoSelectFromPopAndArch (moeoSelectOne < MOEOT > & _popSelectOne, moeoSelectOne < MOEOT > _archSelectOne, moeoArchive < MOEOT > & _arch, double _ratioFromPop=0.5)
: popSelectOne(_popSelectOne), archSelectOne(_archSelectOne), arch(_arch), ratioFromPop(_ratioFromPop)
{}
/**
* Defaulr ctor - the archive's selection operator is a random selector
* @param _popSelectOne the population's selection operator
* @param _arch the archive
* @param _ratioFromPop the ratio of selected individuals from the population
*/
moeoSelectFromPopAndArch (moeoSelectOne < MOEOT > & _popSelectOne, moeoArchive < MOEOT > & _arch, double _ratioFromPop=0.5)
: popSelectOne(_popSelectOne), archSelectOne(randomSelectOne), arch(_arch), ratioFromPop(_ratioFromPop)
{}
/**
* The selection process
*/
virtual const MOEOT & operator () (const eoPop < MOEOT > & pop)
{
if (arch.size() > 0)
if (rng.flip(ratioFromPop))
return popSelectOne(pop);
else
return archSelectOne(arch);
else
return popSelectOne(pop);
}
/**
* Setups some population stats
*/
virtual void setup (const eoPop < MOEOT > & _pop)
{
popSelectOne.setup(_pop);
}
private:
/** The population's selection operator */
moeoSelectOne < MOEOT > & popSelectOne;
/** The archive's selection operator */
moeoSelectOne < MOEOT > & archSelectOne;
/** The archive */
moeoArchive < MOEOT > & arch;
/** The ratio of selected individuals from the population*/
double ratioFromPop;
/** A random selection operator (used as default for archSelectOne) */
moeoRandomSelect < MOEOT > randomSelectOne;
/** The population's selection operator */
moeoSelectOne < MOEOT > & popSelectOne;
/** The archive's selection operator */
moeoSelectOne < MOEOT > & archSelectOne;
/** The archive */
moeoArchive < MOEOT > & arch;
/** The ratio of selected individuals from the population*/
double ratioFromPop;
/** A random selection operator (used as default for archSelectOne) */
moeoRandomSelect < MOEOT > randomSelectOne;
};
#endif /*MOEOSELECTONEFROMPOPANDARCH_H_*/

View file

@ -20,16 +20,16 @@ template <class It,class MOEOT>
It mo_deterministic_tournament(It _begin, It _end, unsigned _t_size,moeoComparator<MOEOT>& _comparator ,eoRng& _gen = rng)
{
It best = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i)
{
It competitor = _begin + _gen.random(_end - _begin);
// compare the two individuals by using the comparator
if(_comparator(*best,*competitor))
// best "better" than competitor
best=competitor;
// compare the two individuals by using the comparator
if (_comparator(*best,*competitor))
// best "better" than competitor
best=competitor;
}
return best;
@ -53,22 +53,22 @@ MOEOT& mo_deterministic_tournament(eoPop<MOEOT>& _pop, unsigned _t_size,moeoComp
template <class It,class MOEOT>
It mo_stochastic_tournament(It _begin, It _end, double _t_rate,moeoComparator<MOEOT>& _comparator ,eoRng& _gen = rng)
{
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
bool return_better = _gen.flip(_t_rate);
if (_comparator(*i1 , *i2))
{
if (return_better) return i2;
// else
bool return_better = _gen.flip(_t_rate);
return i1;
}
if (_comparator(*i1 , *i2))
{
if (return_better) return i2;
// else
return i1;
}
else
{
if (return_better) return i1;
// else
if (return_better) return i1;
// else
}
// else
@ -96,13 +96,13 @@ It mo_roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0
return _begin + _gen.random(_end - _begin); // uniform choice
return _begin + _gen.random(_end - _begin); // uniform choice
It i = _begin;
while (roulette > 0.0)
{
roulette -= static_cast<double>(*(i++));
roulette -= static_cast<double>(*(i++));
}
return --i;
@ -114,13 +114,13 @@ const MOEOT& mo_roulette_wheel(const eoPop<MOEOT>& _pop, double total, eoRng& _g
float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0
return _pop[_gen.random(_pop.size())]; // uniform choice
return _pop[_gen.random(_pop.size())]; // uniform choice
typename eoPop<MOEOT>::const_iterator i = _pop.begin();
while (roulette > 0.0)
{
roulette -= static_cast<double>((i++)->fitness());
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;
@ -132,14 +132,14 @@ MOEOT& mo_roulette_wheel(eoPop<MOEOT>& _pop, double total, eoRng& _gen = rng)
float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0
return _pop[_gen.random(_pop.size())]; // uniform choice
return _pop[_gen.random(_pop.size())]; // uniform choice
typename eoPop<MOEOT>::iterator i = _pop.begin();
while (roulette > 0.0)
{
// fitness ?
roulette -= static_cast<double>((i++)->fitness());
// fitness ?
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;

View file

@ -33,7 +33,7 @@ public:
using std::vector < GeneType > :: resize;
using std::vector < GeneType > :: size;
/** the atomic type */
/** the atomic type */
typedef GeneType AtomType;
/** the container type */
typedef std::vector < GeneType > ContainerType;
@ -44,60 +44,60 @@ public:
* @param _size Length of vector (default is 0)
* @param _value Initial value of all elements (default is default value of type GeneType)
*/
moeoVector(unsigned _size = 0, GeneType _value = GeneType()) :
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >(), std::vector<GeneType>(_size, _value)
moeoVector(unsigned _size = 0, GeneType _value = GeneType()) :
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >(), std::vector<GeneType>(_size, _value)
{}
/**
* We can't have a Ctor from a std::vector as it would create ambiguity with the copy Ctor.
* @param _v a vector of GeneType
*/
void value(const std::vector < GeneType > & _v)
{
if (_v.size() != size()) // safety check
{
if (size()) // NOT an initial empty std::vector
{
std::cout << "Warning: Changing size in moeoVector assignation"<<std::endl;
resize(_v.size());
}
}
std::copy(_v.begin(), _v.end(), begin());
invalidate();
if (_v.size() != size()) // safety check
{
if (size()) // NOT an initial empty std::vector
{
std::cout << "Warning: Changing size in moeoVector assignation"<<std::endl;
resize(_v.size());
}
}
std::copy(_v.begin(), _v.end(), begin());
invalidate();
}
/**
* To avoid conflicts between MOEO::operator< and std::vector<GeneType>::operator<
* @param _moeo the object to compare with
*/
bool operator<(const moeoVector< MOEOObjectiveVector, MOEOFitness, MOEODiversity, GeneType> & _moeo) const
{
return MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::operator<(_moeo);
return MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::operator<(_moeo);
}
/**
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
{
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::printOn(_os);
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::printOn(_os);
_os << ' ';
_os << size() << ' ';
std::copy(begin(), end(), std::ostream_iterator<AtomType>(_os, " "));
}
/**
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
{
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::readFrom(_is);
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::readFrom(_is);
unsigned sz;
_is >> sz;
resize(sz);
@ -109,7 +109,7 @@ public:
operator[](i) = atom;
}
}
};
@ -145,13 +145,13 @@ class moeoRealVector : public moeoVector < MOEOObjectiveVector, MOEOFitness, MOE
{
public:
/**
* Ctor
* @param _size Length of vector (default is 0)
* @param _value Initial value of all elements (default is default value of type GeneType)
*/
moeoRealVector(unsigned _size = 0, double _value = 0.0) : moeoVector< MOEOObjectiveVector, MOEOFitness, MOEODiversity, double >(_size, _value)
{}
/**
* Ctor
* @param _size Length of vector (default is 0)
* @param _value Initial value of all elements (default is default value of type GeneType)
*/
moeoRealVector(unsigned _size = 0, double _value = 0.0) : moeoVector< MOEOObjectiveVector, MOEOFitness, MOEODiversity, double >(_size, _value)
{}
};
@ -164,52 +164,52 @@ class moeoBitVector : public moeoVector < MOEOObjectiveVector, MOEOFitness, MOEO
{
public:
using moeoVector < MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool > :: begin;
using moeoVector < MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool > :: begin;
using moeoVector < MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool > :: end;
using moeoVector < MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool > :: resize;
using moeoVector < MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool > :: size;
/**
* Ctor
* @param _size Length of vector (default is 0)
* @param _value Initial value of all elements (default is default value of type GeneType)
*/
moeoBitVector(unsigned _size = 0, bool _value = false) : moeoVector< MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool >(_size, _value)
{}
/**
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
/**
* Ctor
* @param _size Length of vector (default is 0)
* @param _value Initial value of all elements (default is default value of type GeneType)
*/
moeoBitVector(unsigned _size = 0, bool _value = false) : moeoVector< MOEOObjectiveVector, MOEOFitness, MOEODiversity, bool >(_size, _value)
{}
/**
* Writing object
* @param _os output stream
*/
virtual void printOn(std::ostream & _os) const
{
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::printOn(_os);
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::printOn(_os);
_os << ' ';
_os << size() << ' ';
std::copy(begin(), end(), std::ostream_iterator<bool>(_os));
}
/**
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
* Reading object
* @param _is input stream
*/
virtual void readFrom(std::istream & _is)
{
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::readFrom(_is);
MOEO < MOEOObjectiveVector, MOEOFitness, MOEODiversity >::readFrom(_is);
unsigned s;
_is >> s;
std::string bits;
_is >> bits;
if (_is)
{
resize(bits.size());
std::transform(bits.begin(), bits.end(), begin(), std::bind2nd(std::equal_to<char>(), '1'));
resize(bits.size());
std::transform(bits.begin(), bits.end(), begin(), std::bind2nd(std::equal_to<char>(), '1'));
}
}
};

View file

@ -24,89 +24,89 @@
typedef moeoObjectiveVectorDouble<moeoObjectiveVectorTraits> FlowShopObjectiveVector;
/**
/**
* Structure of the genotype for the flow-shop scheduling problem
*/
class FlowShop: public MOEO<FlowShopObjectiveVector, double, double> {
public:
/**
* default constructor
*/
FlowShop() {}
/**
* default constructor
*/
FlowShop() {}
/**
* destructor
*/
virtual ~FlowShop() {}
/**
* class name
*/
virtual string className() const {
return "FlowShop";
}
/**
* destructor
*/
virtual ~FlowShop() {}
/**
* set scheduling vector
* @param vector<unsigned> & _scheduling the new scheduling to set
*/
void setScheduling(vector<unsigned> & _scheduling) {
scheduling = _scheduling;
}
/**
* get scheduling vector
*/
const vector<unsigned> & getScheduling() const {
return scheduling;
}
/**
* printing...
*/
void printOn(ostream& _os) const {
// fitness
MOEO<FlowShopObjectiveVector, double, double>::printOn(_os);
// size
_os << scheduling.size() << "\t" ;
// scheduling
for (unsigned i=0; i<scheduling.size(); i++)
_os << scheduling[i] << ' ' ;
}
/**
* reading...
*/
void readFrom(istream& _is) {
// fitness
MOEO<FlowShopObjectiveVector, double, double>::readFrom(_is);
// size
unsigned size;
_is >> size;
// scheduling
scheduling.resize(size);
bool tmp;
for (unsigned i=0; i<size; i++) {
_is >> tmp;
scheduling[i] = tmp;
/**
* class name
*/
virtual string className() const {
return "FlowShop";
}
}
bool operator==(const FlowShop& _other) const { return scheduling == _other.getScheduling(); }
bool operator!=(const FlowShop& _other) const { return scheduling != _other.getScheduling(); }
bool operator< (const FlowShop& _other) const { return scheduling < _other.getScheduling(); }
bool operator> (const FlowShop& _other) const { return scheduling > _other.getScheduling(); }
bool operator<=(const FlowShop& _other) const { return scheduling <= _other.getScheduling(); }
bool operator>=(const FlowShop& _other) const { return scheduling >= _other.getScheduling(); }
/**
* set scheduling vector
* @param vector<unsigned> & _scheduling the new scheduling to set
*/
void setScheduling(vector<unsigned> & _scheduling) {
scheduling = _scheduling;
}
/**
* get scheduling vector
*/
const vector<unsigned> & getScheduling() const {
return scheduling;
}
/**
* printing...
*/
void printOn(ostream& _os) const {
// fitness
MOEO<FlowShopObjectiveVector, double, double>::printOn(_os);
// size
_os << scheduling.size() << "\t" ;
// scheduling
for (unsigned i=0; i<scheduling.size(); i++)
_os << scheduling[i] << ' ' ;
}
/**
* reading...
*/
void readFrom(istream& _is) {
// fitness
MOEO<FlowShopObjectiveVector, double, double>::readFrom(_is);
// size
unsigned size;
_is >> size;
// scheduling
scheduling.resize(size);
bool tmp;
for (unsigned i=0; i<size; i++) {
_is >> tmp;
scheduling[i] = tmp;
}
}
bool operator==(const FlowShop& _other) const { return scheduling == _other.getScheduling(); }
bool operator!=(const FlowShop& _other) const { return scheduling != _other.getScheduling(); }
bool operator< (const FlowShop& _other) const { return scheduling < _other.getScheduling(); }
bool operator> (const FlowShop& _other) const { return scheduling > _other.getScheduling(); }
bool operator<=(const FlowShop& _other) const { return scheduling <= _other.getScheduling(); }
bool operator>=(const FlowShop& _other) const { return scheduling >= _other.getScheduling(); }
private:
/** scheduling (order of operations) */
std::vector<unsigned> scheduling;
/** scheduling (order of operations) */
std::vector<unsigned> scheduling;
};

View file

@ -19,7 +19,7 @@
const static std::string BENCHMARKS_WEB_SITE = "www.lifl.fr/~basseur/BenchsUncertain/";
/**
/**
* Class to handle parameters of a flow-shop instance from a benchmark file
* benchmark files are available at www.lifl.fr/~basseur/BenchsUncertain/
*/
@ -27,114 +27,114 @@ class FlowShopBenchmarkParser {
public:
/**
* constructor
* @param const string _benchmarkFileName the name of the benchmark file
*/
FlowShopBenchmarkParser(const string _benchmarkFileName) {
init(_benchmarkFileName);
}
/**
* the number of machines
*/
const unsigned getM() {
return M;
}
/**
* the number of jobs
*/
const unsigned getN() {
return N;
}
/**
* the processing times
*/
const std::vector< std::vector<unsigned> > getP() {
return p;
}
/**
* the due-dates
*/
const std::vector<unsigned> getD() {
return d;
}
/**
* printing...
*/
void printOn(ostream& _os) const {
_os << "M=" << M << " N=" << N << endl;
_os << "*** processing times" << endl;
for (unsigned i=0; i<M; i++) {
for (unsigned j=0; j<N; j++) {
_os << p[i][j] << " ";
}
_os << endl;
/**
* constructor
* @param const string _benchmarkFileName the name of the benchmark file
*/
FlowShopBenchmarkParser(const string _benchmarkFileName) {
init(_benchmarkFileName);
}
_os << "*** due-dates" << endl;
for (unsigned j=0; j<N; j++) {
_os << d[j] << " ";
/**
* the number of machines
*/
const unsigned getM() {
return M;
}
/**
* the number of jobs
*/
const unsigned getN() {
return N;
}
/**
* the processing times
*/
const std::vector< std::vector<unsigned> > getP() {
return p;
}
/**
* the due-dates
*/
const std::vector<unsigned> getD() {
return d;
}
/**
* printing...
*/
void printOn(ostream& _os) const {
_os << "M=" << M << " N=" << N << endl;
_os << "*** processing times" << endl;
for (unsigned i=0; i<M; i++) {
for (unsigned j=0; j<N; j++) {
_os << p[i][j] << " ";
}
_os << endl;
}
_os << "*** due-dates" << endl;
for (unsigned j=0; j<N; j++) {
_os << d[j] << " ";
}
_os << endl << endl;
}
_os << endl << endl;
}
private:
/** number of machines */
unsigned M;
/** number of jobs */
unsigned N;
/** p[i][j] = processing time of job j on machine i */
std::vector< std::vector<unsigned> > p;
/** d[j] = due-date of the job j */
std::vector<unsigned> d;
/** number of machines */
unsigned M;
/** number of jobs */
unsigned N;
/** p[i][j] = processing time of job j on machine i */
std::vector< std::vector<unsigned> > p;
/** d[j] = due-date of the job j */
std::vector<unsigned> d;
/**
* Initialisation of the parameters with the data contained in the benchmark file
* @param const string _benchmarkFileName the name of the benchmark file
*/
void init(const string _benchmarkFileName) {
string buffer;
string::size_type start, end;
ifstream inputFile(_benchmarkFileName.data(), ios::in);
// opening of the benchmark file
if (! inputFile)
cerr << "*** ERROR : Unable to open the benchmark file '" << _benchmarkFileName << "'" << endl;
// number of jobs (N)
getline(inputFile, buffer, '\n');
N = atoi(buffer.data());
// number of machines M
getline(inputFile, buffer, '\n');
M = atoi(buffer.data());
// initial and current seeds (not used)
getline(inputFile, buffer, '\n');
// processing times and due-dates
p = std::vector< std::vector<unsigned> > (M,N);
d = std::vector<unsigned> (N);
// for each job...
for (unsigned j=0 ; j<N ; j++) {
// index of the job (<=> j)
getline(inputFile, buffer, '\n');
// due-date of the job j
getline(inputFile, buffer, '\n');
d[j] = atoi(buffer.data());
// processing times of the job j on each machine
getline(inputFile, buffer, '\n');
start = buffer.find_first_not_of(" ");
for (unsigned i=0 ; i<M ; i++) {
end = buffer.find_first_of(" ", start);
p[i][j] = atoi(buffer.substr(start, end-start).data());
start = buffer.find_first_not_of(" ", end);
}
/**
* Initialisation of the parameters with the data contained in the benchmark file
* @param const string _benchmarkFileName the name of the benchmark file
*/
void init(const string _benchmarkFileName) {
string buffer;
string::size_type start, end;
ifstream inputFile(_benchmarkFileName.data(), ios::in);
// opening of the benchmark file
if (! inputFile)
cerr << "*** ERROR : Unable to open the benchmark file '" << _benchmarkFileName << "'" << endl;
// number of jobs (N)
getline(inputFile, buffer, '\n');
N = atoi(buffer.data());
// number of machines M
getline(inputFile, buffer, '\n');
M = atoi(buffer.data());
// initial and current seeds (not used)
getline(inputFile, buffer, '\n');
// processing times and due-dates
p = std::vector< std::vector<unsigned> > (M,N);
d = std::vector<unsigned> (N);
// for each job...
for (unsigned j=0 ; j<N ; j++) {
// index of the job (<=> j)
getline(inputFile, buffer, '\n');
// due-date of the job j
getline(inputFile, buffer, '\n');
d[j] = atoi(buffer.data());
// processing times of the job j on each machine
getline(inputFile, buffer, '\n');
start = buffer.find_first_not_of(" ");
for (unsigned i=0 ; i<M ; i++) {
end = buffer.find_first_of(" ", start);
p[i][j] = atoi(buffer.substr(start, end-start).data());
start = buffer.find_first_not_of(" ", end);
}
}
// closing of the input file
inputFile.close();
}
// closing of the input file
inputFile.close();
}
};
#endif /*FLOWSHOPBENCHMARKPARSER_H_*/

View file

@ -10,7 +10,7 @@
*/
//-----------------------------------------------------------------------------
// Miscilaneous include and declaration
// Miscilaneous include and declaration
using namespace std;
@ -41,78 +41,78 @@ void make_help(eoParser & _parser);
int main(int argc, char* argv[]) {
try {
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // to keep all things allocated
try {
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // to keep all things allocated
/*** the representation-dependent things ***/
/*** the representation-dependent things ***/
// The fitness evaluation
eoEvalFuncCounter<FlowShop>& eval = do_make_eval(parser, state);
// the genotype (through a genotype initializer)
eoInit<FlowShop>& init = do_make_genotype(parser, state);
// the variation operators
eoGenOp<FlowShop>& op = do_make_op(parser, state);
// The fitness evaluation
eoEvalFuncCounter<FlowShop>& eval = do_make_eval(parser, state);
// the genotype (through a genotype initializer)
eoInit<FlowShop>& init = do_make_genotype(parser, state);
// the variation operators
eoGenOp<FlowShop>& op = do_make_op(parser, state);
/*** the representation-independent things ***/
/*** the representation-independent things ***/
// initialization of the population
eoPop<FlowShop>& pop = do_make_pop(parser, state, init);
// definition of the archive
moeoArchive<FlowShop> arch;
// stopping criteria
eoContinue<FlowShop>& term = do_make_continue_moeo(parser, state, eval);
// output
eoCheckPoint<FlowShop>& checkpoint = do_make_checkpoint_moeo(parser, state, eval, term, pop, arch);
// algorithm
eoAlgo<FlowShop>& algo = do_make_ea_moeo(parser, state, eval, checkpoint, op, arch);
// initialization of the population
eoPop<FlowShop>& pop = do_make_pop(parser, state, init);
// definition of the archive
moeoArchive<FlowShop> arch;
// stopping criteria
eoContinue<FlowShop>& term = do_make_continue_moeo(parser, state, eval);
// output
eoCheckPoint<FlowShop>& checkpoint = do_make_checkpoint_moeo(parser, state, eval, term, pop, arch);
// algorithm
eoAlgo<FlowShop>& algo = do_make_ea_moeo(parser, state, eval, checkpoint, op, arch);
/*** Go ! ***/
// help ?
make_help(parser);
/*** Go ! ***/
// first evalution
apply<FlowShop>(eval, pop);
pop.sort();
arch.update(pop);
// help ?
make_help(parser);
// printing of the initial population
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
// first evalution
apply<FlowShop>(eval, pop);
// run the algo
do_run(algo, pop);
// printing of the final population
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
pop.sort();
arch.update(pop);
// printing of the final archive
cout << "Final Archive\n";
arch.sortedPrintOn(cout);
cout << endl;
// printing of the initial population
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
// run the algo
do_run(algo, pop);
// printing of the final population
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
// printing of the final archive
cout << "Final Archive\n";
arch.sortedPrintOn(cout);
cout << endl;
} catch(exception& e) {
cout << e.what() << endl;
}
return EXIT_SUCCESS;
} catch (exception& e) {
cout << e.what() << endl;
}
return EXIT_SUCCESS;
}

View file

@ -24,105 +24,105 @@ class FlowShopEval : public moeoEvalFunc<FlowShop> {
public:
/**
* constructor
* @param _M the number of machines
* @param _N the number of jobs to schedule
* @param _p the processing times
* @param _d the due dates
*/
FlowShopEval(const unsigned _M, const unsigned _N, const vector< vector<unsigned> > & _p, const vector<unsigned> & _d) :
M(_M), N (_N), p(_p), d(_d){
/**
* constructor
* @param _M the number of machines
* @param _N the number of jobs to schedule
* @param _p the processing times
* @param _d the due dates
*/
FlowShopEval(const unsigned _M, const unsigned _N, const vector< vector<unsigned> > & _p, const vector<unsigned> & _d) :
M(_M), N (_N), p(_p), d(_d){
unsigned nObjs = 2;
std::vector<bool> bObjs(nObjs, true);
moeoObjectiveVectorTraits::setup(nObjs, bObjs);
}
unsigned nObjs = 2;
std::vector<bool> bObjs(nObjs, true);
moeoObjectiveVectorTraits::setup(nObjs, bObjs);
}
/**
* computation of the multi-objective evaluation of an eoFlowShop object
* @param FlowShop & _eo the FlowShop object to evaluate
*/
void operator()(FlowShop & _eo) {
FlowShopObjectiveVector objVector;
objVector[0] = tardiness(_eo);
objVector[1] = makespan(_eo);
_eo.objectiveVector(objVector);
}
/**
* computation of the multi-objective evaluation of an eoFlowShop object
* @param FlowShop & _eo the FlowShop object to evaluate
*/
void operator()(FlowShop & _eo) {
FlowShopObjectiveVector objVector;
objVector[0] = tardiness(_eo);
objVector[1] = makespan(_eo);
_eo.objectiveVector(objVector);
}
private:
/** number of machines */
unsigned M;
/** number of jobs */
unsigned N;
/** p[i][j] = processing time of job j on machine i */
std::vector< std::vector<unsigned> > p;
/** d[j] = due-date of the job j */
std::vector<unsigned> d;
private:
/**
* computation of the makespan
* @param FlowShop _eo the FlowShop object to evaluate
*/
double makespan(FlowShop _eo) {
// the scheduling to evaluate
vector<unsigned> scheduling = _eo.getScheduling();
// completion times computation for each job on each machine
// C[i][j] = completion of the jth job of the scheduling on the ith machine
std::vector< std::vector<unsigned> > C = completionTime(_eo);
// fitness == C[M-1][scheduling[N-1]];
return C[M-1][scheduling[N-1]];
}
/** number of machines */
unsigned M;
/** number of jobs */
unsigned N;
/** p[i][j] = processing time of job j on machine i */
std::vector< std::vector<unsigned> > p;
/** d[j] = due-date of the job j */
std::vector<unsigned> d;
/**
* computation of the tardiness
* @param _eo the FlowShop object to evaluate
*/
double tardiness(FlowShop _eo) {
// the scheduling to evaluate
vector<unsigned> scheduling = _eo.getScheduling();
// completion times computation for each job on each machine
// C[i][j] = completion of the jth job of the scheduling on the ith machine
std::vector< std::vector<unsigned> > C = completionTime(_eo);
// tardiness computation
unsigned long sum = 0;
for (unsigned j=0 ; j<N ; j++)
sum += (unsigned) std::max (0, (int) (C[M-1][scheduling[j]] - d[scheduling[j]]));
// fitness == sum
return sum;
}
/**
* computation of the makespan
* @param FlowShop _eo the FlowShop object to evaluate
*/
double makespan(FlowShop _eo) {
// the scheduling to evaluate
vector<unsigned> scheduling = _eo.getScheduling();
// completion times computation for each job on each machine
// C[i][j] = completion of the jth job of the scheduling on the ith machine
std::vector< std::vector<unsigned> > C = completionTime(_eo);
// fitness == C[M-1][scheduling[N-1]];
return C[M-1][scheduling[N-1]];
}
/**
* computation of the completion times of a scheduling (for each job on each machine)
* C[i][j] = completion of the jth job of the scheduling on the ith machine
* @param const FlowShop _eo the genotype to evaluate
*/
std::vector< std::vector<unsigned> > completionTime(FlowShop _eo) {
vector<unsigned> scheduling = _eo.getScheduling();
std::vector< std::vector<unsigned> > C(M,N);
C[0][scheduling[0]] = p[0][scheduling[0]];
for (unsigned j=1; j<N; j++)
C[0][scheduling[j]] = C[0][scheduling[j-1]] + p[0][scheduling[j]];
for (unsigned i=1; i<M; i++)
C[i][scheduling[0]] = C[i-1][scheduling[0]] + p[i][scheduling[0]];
for (unsigned i=1; i<M; i++)
for (unsigned j=1; j<N; j++)
C[i][scheduling[j]] = std::max(C[i][scheduling[j-1]], C[i-1][scheduling[j]]) + p[i][scheduling[j]];
return C;
}
/**
* computation of the tardiness
* @param _eo the FlowShop object to evaluate
*/
double tardiness(FlowShop _eo) {
// the scheduling to evaluate
vector<unsigned> scheduling = _eo.getScheduling();
// completion times computation for each job on each machine
// C[i][j] = completion of the jth job of the scheduling on the ith machine
std::vector< std::vector<unsigned> > C = completionTime(_eo);
// tardiness computation
unsigned long sum = 0;
for (unsigned j=0 ; j<N ; j++)
sum += (unsigned) std::max (0, (int) (C[M-1][scheduling[j]] - d[scheduling[j]]));
// fitness == sum
return sum;
}
/**
* computation of the completion times of a scheduling (for each job on each machine)
* C[i][j] = completion of the jth job of the scheduling on the ith machine
* @param const FlowShop _eo the genotype to evaluate
*/
std::vector< std::vector<unsigned> > completionTime(FlowShop _eo) {
vector<unsigned> scheduling = _eo.getScheduling();
std::vector< std::vector<unsigned> > C(M,N);
C[0][scheduling[0]] = p[0][scheduling[0]];
for (unsigned j=1; j<N; j++)
C[0][scheduling[j]] = C[0][scheduling[j-1]] + p[0][scheduling[j]];
for (unsigned i=1; i<M; i++)
C[i][scheduling[0]] = C[i-1][scheduling[0]] + p[i][scheduling[0]];
for (unsigned i=1; i<M; i++)
for (unsigned j=1; j<N; j++)
C[i][scheduling[j]] = std::max(C[i][scheduling[j-1]], C[i-1][scheduling[j]]) + p[i][scheduling[j]];
return C;
}
};

View file

@ -24,41 +24,41 @@ class FlowShopInit: public eoInit<FlowShop> {
public:
/**
* constructor
* @param const unsigned _N the number of jobs to schedule
*/
FlowShopInit(const unsigned _N) {
N = _N;
}
/**
* randomize a genotype
* @param FlowShop & _genotype a genotype that has been default-constructed
*/
void operator()(FlowShop & _genotype) {
// scheduling vector
vector<unsigned> scheduling(N);
// initialisation of possible values
vector<unsigned> possibles(N);
for(unsigned i=0 ; i<N ; i++)
possibles[i] = i;
// random initialization
unsigned rInd; // random index
for (unsigned i=0; i<N; i++) {
rInd = (unsigned) rng.uniform(N-i);
scheduling[i] = possibles[rInd];
possibles[rInd] = possibles[N-i-1];
/**
* constructor
* @param const unsigned _N the number of jobs to schedule
*/
FlowShopInit(const unsigned _N) {
N = _N;
}
/**
* randomize a genotype
* @param FlowShop & _genotype a genotype that has been default-constructed
*/
void operator()(FlowShop & _genotype) {
// scheduling vector
vector<unsigned> scheduling(N);
// initialisation of possible values
vector<unsigned> possibles(N);
for (unsigned i=0 ; i<N ; i++)
possibles[i] = i;
// random initialization
unsigned rInd; // random index
for (unsigned i=0; i<N; i++) {
rInd = (unsigned) rng.uniform(N-i);
scheduling[i] = possibles[rInd];
possibles[rInd] = possibles[N-i-1];
}
_genotype.setScheduling(scheduling);
_genotype.invalidate(); // IMPORTANT in case the _genotype is old
}
_genotype.setScheduling(scheduling);
_genotype.invalidate(); // IMPORTANT in case the _genotype is old
}
private:
/** the number of jobs (size of a scheduling vector) */
unsigned N;
/** the number of jobs (size of a scheduling vector) */
unsigned N;
};
#endif /*FLOWSHOPINIT_H_*/

View file

@ -21,99 +21,99 @@
* Quadratic crossover operator for flow-shop (modify the both genotypes)
*/
class FlowShopOpCrossoverQuad: public eoQuadOp<FlowShop> {
public:
/**
* default constructor
*/
FlowShopOpCrossoverQuad() {}
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpCrossoverQuad";
}
/**
* eoQuad crossover - _genotype1 and _genotype2 are the (future) offspring, i.e. _copies_ of the parents
* @param FlowShop & _genotype1 the first parent
* @param FlowShop & _genotype2 the second parent
*/
bool operator()(FlowShop & _genotype1, FlowShop & _genotype2) {
bool oneAtLeastIsModified;
// parents
vector<unsigned> parent1 = _genotype1.getScheduling();
vector<unsigned> parent2 = _genotype2.getScheduling();
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(min(parent1.size(), parent2.size()));
point2 = rng.random(min(parent1.size(), parent2.size()));
} while (fabs((double) point1-point2) <= 2);
// computation of the offspring
vector<unsigned> offspring1 = generateOffspring(parent1, parent2, point1, point2);
vector<unsigned> offspring2 = generateOffspring(parent2, parent1, point1, point2);
// does at least one genotype has been modified ?
if ((parent1 != offspring1) || (parent2 != offspring2)) {
// update
_genotype1.setScheduling(offspring1);
_genotype2.setScheduling(offspring2);
// at least one genotype has been modified
oneAtLeastIsModified = true;
}
else {
// no genotype has been modified
oneAtLeastIsModified = false;
public:
/**
* default constructor
*/
FlowShopOpCrossoverQuad() {}
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpCrossoverQuad";
}
// return 'true' if at least one genotype has been modified
return oneAtLeastIsModified;
}
/**
* eoQuad crossover - _genotype1 and _genotype2 are the (future) offspring, i.e. _copies_ of the parents
* @param FlowShop & _genotype1 the first parent
* @param FlowShop & _genotype2 the second parent
*/
bool operator()(FlowShop & _genotype1, FlowShop & _genotype2) {
bool oneAtLeastIsModified;
// parents
vector<unsigned> parent1 = _genotype1.getScheduling();
vector<unsigned> parent2 = _genotype2.getScheduling();
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(min(parent1.size(), parent2.size()));
point2 = rng.random(min(parent1.size(), parent2.size()));
} while (fabs((double) point1-point2) <= 2);
// computation of the offspring
vector<unsigned> offspring1 = generateOffspring(parent1, parent2, point1, point2);
vector<unsigned> offspring2 = generateOffspring(parent2, parent1, point1, point2);
// does at least one genotype has been modified ?
if ((parent1 != offspring1) || (parent2 != offspring2)) {
// update
_genotype1.setScheduling(offspring1);
_genotype2.setScheduling(offspring2);
// at least one genotype has been modified
oneAtLeastIsModified = true;
}
else {
// no genotype has been modified
oneAtLeastIsModified = false;
}
// return 'true' if at least one genotype has been modified
return oneAtLeastIsModified;
}
private:
/**
* generation of an offspring by a 2 points crossover
* @param vector<unsigned> _parent1 the first parent
* @param vector<unsigned> _parent2 the second parent
* @param unsigned_point1 the first point
* @param unsigned_point2 the second point
*/
vector<unsigned> generateOffspring(vector<unsigned> _parent1, vector<unsigned> _parent2, unsigned _point1, unsigned _point2) {
vector<unsigned> result = _parent1;
vector<bool> taken_values(result.size(), false);
if (_point1 > _point2) swap(_point1, _point2);
/* first parent */
for (unsigned i=0 ; i<=_point1 ; i++) {
// result[i] == _parent1[i]
taken_values[_parent1[i]] = true;
/**
* generation of an offspring by a 2 points crossover
* @param vector<unsigned> _parent1 the first parent
* @param vector<unsigned> _parent2 the second parent
* @param unsigned_point1 the first point
* @param unsigned_point2 the second point
*/
vector<unsigned> generateOffspring(vector<unsigned> _parent1, vector<unsigned> _parent2, unsigned _point1, unsigned _point2) {
vector<unsigned> result = _parent1;
vector<bool> taken_values(result.size(), false);
if (_point1 > _point2) swap(_point1, _point2);
/* first parent */
for (unsigned i=0 ; i<=_point1 ; i++) {
// result[i] == _parent1[i]
taken_values[_parent1[i]] = true;
}
for (unsigned i=_point2 ; i<result.size() ; i++) {
// result[i] == _parent1[i]
taken_values[_parent1[i]] = true;
}
/* second parent */
unsigned i = _point1+1;
unsigned j = 0;
while (i<_point2 && j<_parent2.size()) {
if (! taken_values[_parent2[j]]) {
result[i] = _parent2[j];
i++;
}
j++;
}
return result;
}
for (unsigned i=_point2 ; i<result.size() ; i++) {
// result[i] == _parent1[i]
taken_values[_parent1[i]] = true;
}
/* second parent */
unsigned i = _point1+1;
unsigned j = 0;
while (i<_point2 && j<_parent2.size()) {
if(! taken_values[_parent2[j]]) {
result[i] = _parent2[j];
i++;
}
j++;
}
return result;
}
};

View file

@ -24,54 +24,54 @@ class FlowShopOpMutationExchange: public eoMonOp<FlowShop> {
public:
/**
* default constructor
*/
FlowShopOpMutationExchange() {}
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpMutationExchange";
}
/**
* default constructor
*/
FlowShopOpMutationExchange() {}
/**
* modifies the parent with an exchange mutation
* @param FlowShop & _genotype the parent genotype (will be modified)
*/
bool operator()(FlowShop & _genotype) {
bool isModified;
// schedulings
vector<unsigned> initScheduling = _genotype.getScheduling();
vector<unsigned> resultScheduling = _genotype.getScheduling();
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(resultScheduling.size());
point2 = rng.random(resultScheduling.size());
} while (point1 == point2);
// swap
swap (resultScheduling[point1], resultScheduling[point2]);
// update (if necessary)
if (resultScheduling != initScheduling) {
// update
_genotype.setScheduling(resultScheduling);
// the genotype has been modified
isModified = true;
}
else {
// the genotype has not been modified
isModified = false;
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpMutationExchange";
}
// return 'true' if the genotype has been modified
return isModified;
}
/**
* modifies the parent with an exchange mutation
* @param FlowShop & _genotype the parent genotype (will be modified)
*/
bool operator()(FlowShop & _genotype) {
bool isModified;
// schedulings
vector<unsigned> initScheduling = _genotype.getScheduling();
vector<unsigned> resultScheduling = _genotype.getScheduling();
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(resultScheduling.size());
point2 = rng.random(resultScheduling.size());
} while (point1 == point2);
// swap
swap (resultScheduling[point1], resultScheduling[point2]);
// update (if necessary)
if (resultScheduling != initScheduling) {
// update
_genotype.setScheduling(resultScheduling);
// the genotype has been modified
isModified = true;
}
else {
// the genotype has not been modified
isModified = false;
}
// return 'true' if the genotype has been modified
return isModified;
}
};

View file

@ -23,63 +23,63 @@
class FlowShopOpMutationShift: public eoMonOp<FlowShop> {
public:
/**
* default constructor
*/
FlowShopOpMutationShift() {}
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpMutationShift";
}
/**
* modifies the parent with a shift mutation
* @param FlowShop & _genotype the parent genotype (will be modified)
*/
bool operator()(FlowShop & _genotype) {
bool isModified;
int direction;
unsigned tmp;
// schedulings
vector<unsigned> initScheduling = _genotype.getScheduling();
vector<unsigned> resultScheduling = initScheduling;
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(resultScheduling.size());
point2 = rng.random(resultScheduling.size());
} while (point1 == point2);
// direction
if (point1 < point2) direction = 1;
else direction = -1;
// mutation
tmp = resultScheduling[point1];
for(unsigned i=point1 ; i!=point2 ; i+=direction)
resultScheduling[i] = resultScheduling[i+direction];
resultScheduling[point2] = tmp;
// update (if necessary)
if (resultScheduling != initScheduling) {
// update
_genotype.setScheduling(resultScheduling);
// the genotype has been modified
isModified = true;
}
else {
// the genotype has not been modified
isModified = false;
/**
* default constructor
*/
FlowShopOpMutationShift() {}
/**
* the class name (used to display statistics)
*/
string className() const {
return "FlowShopOpMutationShift";
}
// return 'true' if the genotype has been modified
return isModified;
}
/**
* modifies the parent with a shift mutation
* @param FlowShop & _genotype the parent genotype (will be modified)
*/
bool operator()(FlowShop & _genotype) {
bool isModified;
int direction;
unsigned tmp;
// schedulings
vector<unsigned> initScheduling = _genotype.getScheduling();
vector<unsigned> resultScheduling = initScheduling;
// computation of the 2 random points
unsigned point1, point2;
do {
point1 = rng.random(resultScheduling.size());
point2 = rng.random(resultScheduling.size());
} while (point1 == point2);
// direction
if (point1 < point2) direction = 1;
else direction = -1;
// mutation
tmp = resultScheduling[point1];
for (unsigned i=point1 ; i!=point2 ; i+=direction)
resultScheduling[i] = resultScheduling[i+direction];
resultScheduling[point2] = tmp;
// update (if necessary)
if (resultScheduling != initScheduling) {
// update
_genotype.setScheduling(resultScheduling);
// the genotype has been modified
isModified = true;
}
else {
// the genotype has not been modified
isModified = false;
}
// return 'true' if the genotype has been modified
return isModified;
}
};

View file

@ -23,33 +23,33 @@
/*
* This function creates an eoEvalFuncCounter<eoFlowShop> that can later be used to evaluate an individual.
* @param eoParser& _parser to get user parameters
* @param eoState& _state to store the memory
* @param eoState& _state to store the memory
*/
eoEvalFuncCounter<FlowShop> & do_make_eval(eoParser& _parser, eoState& _state) {
// benchmark file name
string benchmarkFileName = _parser.getORcreateParam(string(), "BenchmarkFile", "Benchmark file name (benchmarks are available at " + BENCHMARKS_WEB_SITE + ")", 'B',"Representation", true).value();
if (benchmarkFileName == "") {
std::string stmp = "*** Missing name of the benchmark file\n";
stmp += " Type '-B=the_benchmark_file_name' or '--BenchmarkFile=the_benchmark_file_name'\n";
stmp += " Benchmarks files are available at " + BENCHMARKS_WEB_SITE;
throw std::runtime_error(stmp.c_str());
}
// reading of the parameters contained in the benchmark file
FlowShopBenchmarkParser fParser(benchmarkFileName);
unsigned M = fParser.getM();
unsigned N = fParser.getN();
std::vector< std::vector<unsigned> > p = fParser.getP();
std::vector<unsigned> d = fParser.getD();
// build of the initializer (a pointer, stored in the eoState)
FlowShopEval* plainEval = new FlowShopEval(M, N, p, d);
// turn that object into an evaluation counter
eoEvalFuncCounter<FlowShop>* eval = new eoEvalFuncCounter<FlowShop> (* plainEval);
// store in state
_state.storeFunctor(eval);
// and return a reference
return *eval;
// benchmark file name
string benchmarkFileName = _parser.getORcreateParam(string(), "BenchmarkFile", "Benchmark file name (benchmarks are available at " + BENCHMARKS_WEB_SITE + ")", 'B',"Representation", true).value();
if (benchmarkFileName == "") {
std::string stmp = "*** Missing name of the benchmark file\n";
stmp += " Type '-B=the_benchmark_file_name' or '--BenchmarkFile=the_benchmark_file_name'\n";
stmp += " Benchmarks files are available at " + BENCHMARKS_WEB_SITE;
throw std::runtime_error(stmp.c_str());
}
// reading of the parameters contained in the benchmark file
FlowShopBenchmarkParser fParser(benchmarkFileName);
unsigned M = fParser.getM();
unsigned N = fParser.getN();
std::vector< std::vector<unsigned> > p = fParser.getP();
std::vector<unsigned> d = fParser.getD();
// build of the initializer (a pointer, stored in the eoState)
FlowShopEval* plainEval = new FlowShopEval(M, N, p, d);
// turn that object into an evaluation counter
eoEvalFuncCounter<FlowShop>* eval = new eoEvalFuncCounter<FlowShop> (* plainEval);
// store in state
_state.storeFunctor(eval);
// and return a reference
return *eval;
}
#endif /*MAKE_EVAL_FLOWSHOP_H_*/

View file

@ -25,25 +25,25 @@
* @param eoState& _state to store the memory
*/
eoInit<FlowShop> & do_make_genotype(eoParser& _parser, eoState& _state) {
// benchmark file name
string benchmarkFileName = _parser.getORcreateParam(string(), "BenchmarkFile", "Benchmark file name (benchmarks are available at " + BENCHMARKS_WEB_SITE + ")", 'B',"Representation", true).value();
if (benchmarkFileName == "") {
std::string stmp = "*** Missing name of the benchmark file\n";
stmp += " Type '-B=the_benchmark_file_name' or '--BenchmarkFile=the_benchmark_file_name'\n";
stmp += " Benchmarks files are available at " + BENCHMARKS_WEB_SITE;
throw std::runtime_error(stmp.c_str());
}
// reading of number of jobs to schedule contained in the benchmark file
FlowShopBenchmarkParser fParser(benchmarkFileName);
unsigned N = fParser.getN();
// build of the initializer (a pointer, stored in the eoState)
eoInit<FlowShop>* init = new FlowShopInit(N);
// store in state
_state.storeFunctor(init);
// and return a reference
return *init;
// benchmark file name
string benchmarkFileName = _parser.getORcreateParam(string(), "BenchmarkFile", "Benchmark file name (benchmarks are available at " + BENCHMARKS_WEB_SITE + ")", 'B',"Representation", true).value();
if (benchmarkFileName == "") {
std::string stmp = "*** Missing name of the benchmark file\n";
stmp += " Type '-B=the_benchmark_file_name' or '--BenchmarkFile=the_benchmark_file_name'\n";
stmp += " Benchmarks files are available at " + BENCHMARKS_WEB_SITE;
throw std::runtime_error(stmp.c_str());
}
// reading of number of jobs to schedule contained in the benchmark file
FlowShopBenchmarkParser fParser(benchmarkFileName);
unsigned N = fParser.getN();
// build of the initializer (a pointer, stored in the eoState)
eoInit<FlowShop>* init = new FlowShopInit(N);
// store in state
_state.storeFunctor(init);
// and return a reference
return *init;
}
#endif /*MAKE_GENOTYPE_FLOWSHOP_H_*/

View file

@ -30,77 +30,77 @@
* @param eoState& _state to store the memory
*/
eoGenOp<FlowShop> & do_make_op(eoParameterLoader& _parser, eoState& _state) {
/////////////////////////////
// Variation operators
////////////////////////////
// the crossover
////////////////
// a first crossover
eoQuadOp<FlowShop> *cross = new FlowShopOpCrossoverQuad;
// store in the state
_state.storeFunctor(cross);
// relative rate in the combination
double cross1Rate = _parser.createParam(1.0, "crossRate", "Relative rate for the only crossover", 0, "Variation Operators").value();
// creation of the combined operator with this one
eoPropCombinedQuadOp<FlowShop> *propXover = new eoPropCombinedQuadOp<FlowShop>(*cross, cross1Rate);
// store in the state
_state.storeFunctor(propXover);
/////////////////////////////
// Variation operators
////////////////////////////
// the mutation
///////////////
// a first mutation : the shift mutation
eoMonOp<FlowShop> *mut = new FlowShopOpMutationShift;
_state.storeFunctor(mut);
// its relative rate in the combination
double mut1Rate = _parser.createParam(0.5, "shiftMutRate", "Relative rate for shift mutation", 0, "Variation Operators").value();
// creation of the combined operator with this one
eoPropCombinedMonOp<FlowShop> *propMutation = new eoPropCombinedMonOp<FlowShop>(*mut, mut1Rate);
_state.storeFunctor(propMutation);
// a second mutation : the exchange mutation
mut = new FlowShopOpMutationExchange;
_state.storeFunctor(mut);
// its relative rate in the combination
double mut2Rate = _parser.createParam(0.5, "exchangeMutRate", "Relative rate for exchange mutation", 0, "Variation Operators").value();
// addition of this one to the combined operator
propMutation -> add(*mut, mut2Rate);
// the crossover
////////////////
// end of crossover and mutation definitions
////////////////////////////////////////////
// First read the individual level parameters
eoValueParam<double>& pCrossParam = _parser.createParam(0.25, "pCross", "Probability of Crossover", 'c', "Variation Operators" );
// minimum check
if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) )
throw runtime_error("Invalid pCross");
// a first crossover
eoQuadOp<FlowShop> *cross = new FlowShopOpCrossoverQuad;
// store in the state
_state.storeFunctor(cross);
eoValueParam<double>& pMutParam = _parser.createParam(0.35, "pMut", "Probability of Mutation", 'm', "Variation Operators" );
// minimum check
if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) )
throw runtime_error("Invalid pMut");
// the crossover - with probability pCross
eoProportionalOp<FlowShop> * propOp = new eoProportionalOp<FlowShop> ;
_state.storeFunctor(propOp);
eoQuadOp<FlowShop> *ptQuad = new eoQuadCloneOp<FlowShop>;
_state.storeFunctor(ptQuad);
propOp -> add(*propXover, pCrossParam.value()); // crossover, with proba pcross
propOp -> add(*ptQuad, 1-pCrossParam.value()); // nothing, with proba 1-pcross
// now the sequential
eoSequentialOp<FlowShop> *op = new eoSequentialOp<FlowShop>;
_state.storeFunctor(op);
op -> add(*propOp, 1.0); // always do combined crossover
op -> add(*propMutation, pMutParam.value()); // then mutation, with proba pmut
// relative rate in the combination
double cross1Rate = _parser.createParam(1.0, "crossRate", "Relative rate for the only crossover", 0, "Variation Operators").value();
// creation of the combined operator with this one
eoPropCombinedQuadOp<FlowShop> *propXover = new eoPropCombinedQuadOp<FlowShop>(*cross, cross1Rate);
// store in the state
_state.storeFunctor(propXover);
// return a reference
return *op;
// the mutation
///////////////
// a first mutation : the shift mutation
eoMonOp<FlowShop> *mut = new FlowShopOpMutationShift;
_state.storeFunctor(mut);
// its relative rate in the combination
double mut1Rate = _parser.createParam(0.5, "shiftMutRate", "Relative rate for shift mutation", 0, "Variation Operators").value();
// creation of the combined operator with this one
eoPropCombinedMonOp<FlowShop> *propMutation = new eoPropCombinedMonOp<FlowShop>(*mut, mut1Rate);
_state.storeFunctor(propMutation);
// a second mutation : the exchange mutation
mut = new FlowShopOpMutationExchange;
_state.storeFunctor(mut);
// its relative rate in the combination
double mut2Rate = _parser.createParam(0.5, "exchangeMutRate", "Relative rate for exchange mutation", 0, "Variation Operators").value();
// addition of this one to the combined operator
propMutation -> add(*mut, mut2Rate);
// end of crossover and mutation definitions
////////////////////////////////////////////
// First read the individual level parameters
eoValueParam<double>& pCrossParam = _parser.createParam(0.25, "pCross", "Probability of Crossover", 'c', "Variation Operators" );
// minimum check
if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) )
throw runtime_error("Invalid pCross");
eoValueParam<double>& pMutParam = _parser.createParam(0.35, "pMut", "Probability of Mutation", 'm', "Variation Operators" );
// minimum check
if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) )
throw runtime_error("Invalid pMut");
// the crossover - with probability pCross
eoProportionalOp<FlowShop> * propOp = new eoProportionalOp<FlowShop> ;
_state.storeFunctor(propOp);
eoQuadOp<FlowShop> *ptQuad = new eoQuadCloneOp<FlowShop>;
_state.storeFunctor(ptQuad);
propOp -> add(*propXover, pCrossParam.value()); // crossover, with proba pcross
propOp -> add(*ptQuad, 1-pCrossParam.value()); // nothing, with proba 1-pcross
// now the sequential
eoSequentialOp<FlowShop> *op = new eoSequentialOp<FlowShop>;
_state.storeFunctor(op);
op -> add(*propOp, 1.0); // always do combined crossover
op -> add(*propMutation, pMutParam.value()); // then mutation, with proba pmut
// return a reference
return *op;
}
#endif /*MAKE_OP_FLOWSHOP_H_*/

View file

@ -21,14 +21,15 @@ using namespace std;
// the moeoObjectiveVectorTraits : minimizing 2 objectives
class Sch1ObjectiveVectorTraits : public moeoObjectiveVectorTraits
{
public:static bool minimizing (int i)
{
return true;
}
static unsigned nObjectives ()
{
return 2;
}
public:
static bool minimizing (int i)
{
return true;
}
static unsigned nObjectives ()
{
return 2;
}
};
@ -40,7 +41,7 @@ typedef moeoObjectiveVectorDouble < Sch1ObjectiveVectorTraits > Sch1ObjectiveVec
class Sch1 : public moeoRealVector < Sch1ObjectiveVector, double, double >
{
public:
Sch1() : moeoRealVector < Sch1ObjectiveVector, double, double > (1) {}
Sch1() : moeoRealVector < Sch1ObjectiveVector, double, double > (1) {}
};
@ -48,56 +49,56 @@ public:
class Sch1Eval : public moeoEvalFunc < Sch1 >
{
public:
void operator () (Sch1 & _sch1)
{
if (_sch1.invalidObjectiveVector())
{
Sch1ObjectiveVector objVec;
double x = _sch1[0];
objVec[0] = x * x;
objVec[1] = (x - 2.0) * (x - 2.0);
_sch1.objectiveVector(objVec);
}
}
void operator () (Sch1 & _sch1)
{
if (_sch1.invalidObjectiveVector())
{
Sch1ObjectiveVector objVec;
double x = _sch1[0];
objVec[0] = x * x;
objVec[1] = (x - 2.0) * (x - 2.0);
_sch1.objectiveVector(objVec);
}
}
};
// main
int main (int argc, char *argv[])
{
// parameters
unsigned POP_SIZE = 20;
unsigned MAX_GEN = 100;
double M_EPSILON = 0.01;
double P_CROSS = 0.25;
double P_MUT = 0.35;
// objective functions evaluation
Sch1Eval eval;
// crossover and mutation
eoQuadCloneOp < Sch1 > xover;
eoUniformMutation < Sch1 > mutation (M_EPSILON);
// generate initial population
eoRealVectorBounds bounds (1, 0.0, 2.0); // [0, 2]
eoRealInitBounded < Sch1 > init (bounds);
eoPop < Sch1 > pop (POP_SIZE, init);
// build NSGA-II
moeoNSGAII < Sch1 > nsgaII (MAX_GEN, eval, xover, P_CROSS, mutation, P_MUT);
// run the algo
nsgaII (pop);
// extract first front of the final population using an moeoArchive (this is the output of nsgaII)
moeoArchive < Sch1 > arch;
arch.update (pop);
// printing of the final archive
cout << "Final Archive" << endl;
arch.sortedPrintOn (cout);
cout << endl;
return EXIT_SUCCESS;
// parameters
unsigned POP_SIZE = 20;
unsigned MAX_GEN = 100;
double M_EPSILON = 0.01;
double P_CROSS = 0.25;
double P_MUT = 0.35;
// objective functions evaluation
Sch1Eval eval;
// crossover and mutation
eoQuadCloneOp < Sch1 > xover;
eoUniformMutation < Sch1 > mutation (M_EPSILON);
// generate initial population
eoRealVectorBounds bounds (1, 0.0, 2.0); // [0, 2]
eoRealInitBounded < Sch1 > init (bounds);
eoPop < Sch1 > pop (POP_SIZE, init);
// build NSGA-II
moeoNSGAII < Sch1 > nsgaII (MAX_GEN, eval, xover, P_CROSS, mutation, P_MUT);
// run the algo
nsgaII (pop);
// extract first front of the final population using an moeoArchive (this is the output of nsgaII)
moeoArchive < Sch1 > arch;
arch.update (pop);
// printing of the final archive
cout << "Final Archive" << endl;
arch.sortedPrintOn (cout);
cout << endl;
return EXIT_SUCCESS;
}