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

@ -32,256 +32,256 @@ class MOEO : public EO < MOEOObjectiveVector >
{ {
public: public:
/** the objective vector type of a solution */ /** the objective vector type of a solution */
typedef MOEOObjectiveVector ObjectiveVector; typedef MOEOObjectiveVector ObjectiveVector;
/** the fitness type of a solution */ /** the fitness type of a solution */
typedef MOEOFitness Fitness; typedef MOEOFitness Fitness;
/** the diversity type of a solution */ /** the diversity type of a solution */
typedef MOEODiversity Diversity; typedef MOEODiversity Diversity;
/** /**
* Ctor * Ctor
*/ */
MOEO() MOEO()
{ {
// default values for every parameters // default values for every parameters
objectiveVectorValue = ObjectiveVector(); objectiveVectorValue = ObjectiveVector();
fitnessValue = Fitness(); fitnessValue = Fitness();
diversityValue = Diversity(); diversityValue = Diversity();
// invalidate all // invalidate all
invalidate(); invalidate();
} }
/** /**
* Virtual dtor * Virtual dtor
*/ */
virtual ~MOEO() {}; virtual ~MOEO() {};
/** /**
* Returns the objective vector of the current solution * Returns the objective vector of the current solution
*/ */
ObjectiveVector objectiveVector() const ObjectiveVector objectiveVector() const
{ {
if ( invalidObjectiveVector() ) if ( invalidObjectiveVector() )
{ {
throw std::runtime_error("invalid objective vector"); throw std::runtime_error("invalid objective vector");
} }
return objectiveVectorValue; return objectiveVectorValue;
} }
/** /**
* Sets the objective vector of the current solution * Sets the objective vector of the current solution
* @param _objectiveVectorValue the new objective vector * @param _objectiveVectorValue the new objective vector
*/ */
void objectiveVector(const ObjectiveVector & _objectiveVectorValue) void objectiveVector(const ObjectiveVector & _objectiveVectorValue)
{ {
objectiveVectorValue = _objectiveVectorValue; objectiveVectorValue = _objectiveVectorValue;
invalidObjectiveVectorValue = false; invalidObjectiveVectorValue = false;
} }
/** /**
* Sets the objective vector as invalid * Sets the objective vector as invalid
*/ */
void invalidateObjectiveVector() void invalidateObjectiveVector()
{ {
invalidObjectiveVectorValue = true; invalidObjectiveVectorValue = true;
} }
/** /**
* Returns true if the objective vector is invalid, false otherwise * Returns true if the objective vector is invalid, false otherwise
*/ */
bool invalidObjectiveVector() const bool invalidObjectiveVector() const
{ {
return invalidObjectiveVectorValue; return invalidObjectiveVectorValue;
} }
/** /**
* Returns the fitness value of the current solution * Returns the fitness value of the current solution
*/ */
Fitness fitness() const Fitness fitness() const
{ {
if ( invalidFitness() ) if ( invalidFitness() )
{ {
throw std::runtime_error("invalid fitness (MOEO)"); throw std::runtime_error("invalid fitness (MOEO)");
} }
return fitnessValue; return fitnessValue;
} }
/** /**
* Sets the fitness value of the current solution * Sets the fitness value of the current solution
* @param _fitnessValue the new fitness value * @param _fitnessValue the new fitness value
*/ */
void fitness(const Fitness & _fitnessValue) void fitness(const Fitness & _fitnessValue)
{ {
fitnessValue = _fitnessValue; fitnessValue = _fitnessValue;
invalidFitnessValue = false; invalidFitnessValue = false;
} }
/** /**
* Sets the fitness value as invalid * Sets the fitness value as invalid
*/ */
void invalidateFitness() void invalidateFitness()
{ {
invalidFitnessValue = true; invalidFitnessValue = true;
} }
/** /**
* Returns true if the fitness value is invalid, false otherwise * Returns true if the fitness value is invalid, false otherwise
*/ */
bool invalidFitness() const bool invalidFitness() const
{ {
return invalidFitnessValue; return invalidFitnessValue;
} }
/** /**
* Returns the diversity value of the current solution * Returns the diversity value of the current solution
*/ */
Diversity diversity() const Diversity diversity() const
{ {
if ( invalidDiversity() ) if ( invalidDiversity() )
{ {
throw std::runtime_error("invalid diversity"); throw std::runtime_error("invalid diversity");
} }
return diversityValue; return diversityValue;
} }
/** /**
* Sets the diversity value of the current solution * Sets the diversity value of the current solution
* @param _diversityValue the new diversity value * @param _diversityValue the new diversity value
*/ */
void diversity(const Diversity & _diversityValue) void diversity(const Diversity & _diversityValue)
{ {
diversityValue = _diversityValue; diversityValue = _diversityValue;
invalidDiversityValue = false; invalidDiversityValue = false;
} }
/** /**
* Sets the diversity value as invalid * Sets the diversity value as invalid
*/ */
void invalidateDiversity() void invalidateDiversity()
{ {
invalidDiversityValue = true; invalidDiversityValue = true;
} }
/** /**
* Returns true if the diversity value is invalid, false otherwise * Returns true if the diversity value is invalid, false otherwise
*/ */
bool invalidDiversity() const bool invalidDiversity() const
{ {
return invalidDiversityValue; return invalidDiversityValue;
} }
/** /**
* Sets the objective vector, the fitness value and the diversity value as invalid * Sets the objective vector, the fitness value and the diversity value as invalid
*/ */
void invalidate() void invalidate()
{ {
invalidateObjectiveVector(); invalidateObjectiveVector();
invalidateFitness(); invalidateFitness();
invalidateDiversity(); invalidateDiversity();
} }
/** /**
* Returns true if the fitness value is invalid, false otherwise * Returns true if the fitness value is invalid, false otherwise
*/ */
bool invalid() const bool invalid() const
{ {
return invalidObjectiveVector(); return invalidObjectiveVector();
} }
/** /**
* Returns true if the objective vector of the current solution is smaller than the objective vector of _other on the first objective, * 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). * 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. * 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 * @param _other the other MOEO object to compare with
*/ */
bool operator<(const MOEO & _other) const bool operator<(const MOEO & _other) const
{ {
return objectiveVector() < _other.objectiveVector(); return objectiveVector() < _other.objectiveVector();
} }
/** /**
* Return the class id (the class name as a std::string) * Return the class id (the class name as a std::string)
*/ */
virtual std::string className() const virtual std::string className() const
{ {
return "MOEO"; return "MOEO";
} }
/** /**
* Writing object * Writing object
* @param _os output stream * @param _os output stream
*/ */
virtual void printOn(std::ostream & _os) const virtual void printOn(std::ostream & _os) const
{ {
if ( invalidObjectiveVector() ) if ( invalidObjectiveVector() )
{ {
_os << "INVALID\t"; _os << "INVALID\t";
} }
else else
{ {
_os << objectiveVectorValue << '\t'; _os << objectiveVectorValue << '\t';
} }
} }
/** /**
* Reading object * Reading object
* @param _is input stream * @param _is input stream
*/ */
virtual void readFrom(std::istream & _is) virtual void readFrom(std::istream & _is)
{ {
std::string objectiveVector_str; std::string objectiveVector_str;
int pos = _is.tellg(); int pos = _is.tellg();
_is >> objectiveVector_str; _is >> objectiveVector_str;
if (objectiveVector_str == "INVALID") if (objectiveVector_str == "INVALID")
{ {
invalidateObjectiveVector(); invalidateObjectiveVector();
} }
else else
{ {
invalidObjectiveVectorValue = false; invalidObjectiveVectorValue = false;
_is.seekg(pos); // rewind _is.seekg(pos); // rewind
_is >> objectiveVectorValue; _is >> objectiveVectorValue;
} }
} }
private: private:
/** the objective vector of this solution */ /** the objective vector of this solution */
ObjectiveVector objectiveVectorValue; ObjectiveVector objectiveVectorValue;
/** true if the objective vector is invalid */ /** true if the objective vector is invalid */
bool invalidObjectiveVectorValue; bool invalidObjectiveVectorValue;
/** the fitness value of this solution */ /** the fitness value of this solution */
Fitness fitnessValue; Fitness fitnessValue;
/** true if the fitness value is invalid */ /** true if the fitness value is invalid */
bool invalidFitnessValue; bool invalidFitnessValue;
/** the diversity value of this solution */ /** the diversity value of this solution */
Diversity diversityValue; Diversity diversityValue;
/** true if the diversity value is invalid */ /** true if the diversity value is invalid */
bool invalidDiversityValue; 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)); eoCheckPoint < MOEOT > & checkpoint = _state.storeFunctor(new eoCheckPoint < MOEOT > (_continue));
/* the objective vector type */ /* the objective vector type */
typedef typename MOEOT::ObjectiveVector ObjectiveVector; typedef typename MOEOT::ObjectiveVector ObjectiveVector;
// get number of obectives // get number of obectives
unsigned nObj = ObjectiveVector::nObjectives(); unsigned nObj = ObjectiveVector::nObjectives();
@ -70,8 +70,8 @@ eoCheckPoint < MOEOT > & do_make_checkpoint_moeo (eoParser & _parser, eoState &
eoSortedPopStat<MOEOT> * popStat; eoSortedPopStat<MOEOT> * popStat;
if ( printPop ) // we do want pop dump if ( printPop ) // we do want pop dump
{ {
popStat = & _state.storeFunctor(new eoSortedPopStat<MOEOT>); popStat = & _state.storeFunctor(new eoSortedPopStat<MOEOT>);
checkpoint.add(*popStat); checkpoint.add(*popStat);
} }
////////////////////////////////// //////////////////////////////////
@ -82,34 +82,34 @@ 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" ); eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
if (_parser.isItThere(saveFrequencyParam)) if (_parser.isItThere(saveFrequencyParam))
{ {
// first make sure dirName is OK // first make sure dirName is OK
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX ); unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirName + "\generations"; std::string stmp = dirName + "\generations";
#else #else
std::string stmp = dirName + "/generations"; std::string stmp = dirName + "/generations";
#endif #endif
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp); eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
_state.storeFunctor(stateSaver1); _state.storeFunctor(stateSaver1);
checkpoint.add(*stateSaver1); checkpoint.add(*stateSaver1);
} }
// save state every T seconds // save state every T seconds
eoValueParam<unsigned>& saveTimeIntervalParam = _parser.getORcreateParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" ); 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) if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
{ {
// first make sure dirName is OK // first make sure dirName is OK
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirName + "\time"; std::string stmp = dirName + "\time";
#else #else
std::string stmp = dirName + "/time"; std::string stmp = dirName + "/time";
#endif #endif
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
_state.storeFunctor(stateSaver2); _state.storeFunctor(stateSaver2);
checkpoint.add(*stateSaver2); checkpoint.add(*stateSaver2);
} }
/////////////////// ///////////////////
@ -119,56 +119,56 @@ 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(); bool updateArch = _parser.getORcreateParam(true, "updateArch", "Update the archive at each gen.", '\0', "Evolution Engine").value();
if (updateArch) if (updateArch)
{ {
moeoArchiveUpdater < MOEOT > * updater = new moeoArchiveUpdater < MOEOT > (_archive, _pop); moeoArchiveUpdater < MOEOT > * updater = new moeoArchiveUpdater < MOEOT > (_archive, _pop);
_state.storeFunctor(updater); _state.storeFunctor(updater);
checkpoint.add(*updater); checkpoint.add(*updater);
} }
// store the objective vectors contained in the archive every generation // 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(); bool storeArch = _parser.getORcreateParam(false, "storeArch", "Store the archive's objective vectors at each gen.", '\0', "Output").value();
if (storeArch) if (storeArch)
{ {
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirName + "\arch"; std::string stmp = dirName + "\arch";
#else #else
std::string stmp = dirName + "/arch"; std::string stmp = dirName + "/arch";
#endif #endif
moeoArchiveObjectiveVectorSavingUpdater < MOEOT > * save_updater = new moeoArchiveObjectiveVectorSavingUpdater < MOEOT > (_archive, stmp); moeoArchiveObjectiveVectorSavingUpdater < MOEOT > * save_updater = new moeoArchiveObjectiveVectorSavingUpdater < MOEOT > (_archive, stmp);
_state.storeFunctor(save_updater); _state.storeFunctor(save_updater);
checkpoint.add(*save_updater); checkpoint.add(*save_updater);
} }
// store the contribution of the non-dominated solutions // 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(); bool cont = _parser.getORcreateParam(false, "contribution", "Store the contribution of the archive at each gen.", '\0', "Output").value();
if (cont) if (cont)
{ {
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirName + "\contribution"; std::string stmp = dirName + "\contribution";
#else #else
std::string stmp = dirName + "/contribution"; std::string stmp = dirName + "/contribution";
#endif #endif
moeoContributionMetric < ObjectiveVector > * contribution = new moeoContributionMetric < ObjectiveVector >; moeoContributionMetric < ObjectiveVector > * contribution = new moeoContributionMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * contribution_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*contribution, _archive, stmp); moeoBinaryMetricSavingUpdater < MOEOT > * contribution_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*contribution, _archive, stmp);
_state.storeFunctor(contribution_updater); _state.storeFunctor(contribution_updater);
checkpoint.add(*contribution_updater); checkpoint.add(*contribution_updater);
} }
// store the entropy of the non-dominated solutions // 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(); bool ent = _parser.getORcreateParam(false, "entropy", "Store the entropy of the archive at each gen.", '\0', "Output").value();
if (ent) if (ent)
{ {
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirName + "\entropy"; std::string stmp = dirName + "\entropy";
#else #else
std::string stmp = dirName + "/entropy"; std::string stmp = dirName + "/entropy";
#endif #endif
moeoEntropyMetric < ObjectiveVector > * entropy = new moeoEntropyMetric < ObjectiveVector >; moeoEntropyMetric < ObjectiveVector > * entropy = new moeoEntropyMetric < ObjectiveVector >;
moeoBinaryMetricSavingUpdater < MOEOT > * entropy_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*entropy, _archive, stmp); moeoBinaryMetricSavingUpdater < MOEOT > * entropy_updater = new moeoBinaryMetricSavingUpdater < MOEOT > (*entropy, _archive, stmp);
_state.storeFunctor(entropy_updater); _state.storeFunctor(entropy_updater);
checkpoint.add(*entropy_updater); checkpoint.add(*entropy_updater);
} }
// and that's it for the (control and) output // and that's it for the (control and) output

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -27,50 +27,50 @@ class moeoNormalizedSolutionVsSolutionBinaryMetric : public moeoSolutionVsSoluti
{ {
public: public:
/** very small value to avoid the extreme case where the min bound == the max bound */ /** very small value to avoid the extreme case where the min bound == the max bound */
const static double tiny = 1e-6; const static double tiny = 1e-6;
/** /**
* Default ctr for any moeoNormalizedSolutionVsSolutionBinaryMetric object * Default ctr for any moeoNormalizedSolutionVsSolutionBinaryMetric object
*/ */
moeoNormalizedSolutionVsSolutionBinaryMetric() moeoNormalizedSolutionVsSolutionBinaryMetric()
{ {
bounds.resize(ObjectiveVector::Traits::nObjectives()); bounds.resize(ObjectiveVector::Traits::nObjectives());
} }
/** /**
* Sets the lower bound (_min) and the upper bound (_max) for the objective _obj * Sets the lower bound (_min) and the upper bound (_max) for the objective _obj
* _min lower bound * _min lower bound
* _max upper bound * _max upper bound
* _obj the objective index * _obj the objective index
*/ */
void setup(double _min, double _max, unsigned _obj) void setup(double _min, double _max, unsigned _obj)
{ {
if (_min == _max) if (_min == _max)
{ {
_min -= tiny; _min -= tiny;
_max += tiny; _max += tiny;
} }
bounds[_obj] = eoRealInterval(_min, _max); bounds[_obj] = eoRealInterval(_min, _max);
} }
/** /**
* Sets the lower bound and the upper bound for the objective _obj using a eoRealInterval object * Sets the lower bound and the upper bound for the objective _obj using a eoRealInterval object
* _realInterval the eoRealInterval object * _realInterval the eoRealInterval object
* _obj the objective index * _obj the objective index
*/ */
virtual void setup(eoRealInterval _realInterval, unsigned _obj) virtual void setup(eoRealInterval _realInterval, unsigned _obj)
{ {
bounds[_obj] = _realInterval; bounds[_obj] = _realInterval;
} }
protected: protected:
/** the bounds for every objective (bounds[i] = bounds for the objective i) */ /** the bounds for every objective (bounds[i] = bounds for the objective i) */
std::vector < eoRealInterval > bounds; std::vector < eoRealInterval > bounds;
}; };
@ -85,59 +85,59 @@ class moeoAdditiveEpsilonBinaryMetric : public moeoNormalizedSolutionVsSolutionB
{ {
public: public:
/** /**
* Returns the minimal distance by which the objective vector _o1 must be translated in all objectives * 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 * 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 * @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector * @param _o1 the first objective vector
* @param _o2 the second objective vector * @param _o2 the second objective vector
*/ */
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2) double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{ {
// computation of the epsilon value for the first objective // computation of the epsilon value for the first objective
double result = epsilon(_o1, _o2, 0); double result = epsilon(_o1, _o2, 0);
// computation of the epsilon value for the other objectives // computation of the epsilon value for the other objectives
double tmp; double tmp;
for (unsigned i=1; i<ObjectiveVector::Traits::nObjectives(); i++) for (unsigned i=1; i<ObjectiveVector::Traits::nObjectives(); i++)
{ {
tmp = epsilon(_o1, _o2, i); tmp = epsilon(_o1, _o2, i);
result = std::max(result, tmp); result = std::max(result, tmp);
} }
// returns the maximum epsilon value // returns the maximum epsilon value
return result; return result;
} }
private: private:
/** the bounds for every objective */ /** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds; using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/** /**
* Returns the epsilon value by which the objective vector _o1 must be translated in the objective _obj * 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 * so that it dominates the objective vector _o2
* @param _o1 the first objective vector * @param _o1 the first objective vector
* @param _o2 the second objective vector * @param _o2 the second objective vector
* @param _obj the index of the objective * @param _obj the index of the objective
*/ */
double epsilon(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj) double epsilon(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj)
{ {
double result; double result;
// if the objective _obj have to be minimized // if the objective _obj have to be minimized
if (ObjectiveVector::Traits::minimizing(_obj)) if (ObjectiveVector::Traits::minimizing(_obj))
{ {
// _o1[_obj] - _o2[_obj] // _o1[_obj] - _o2[_obj]
result = ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ); 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 // if the objective _obj have to be maximized
else else
{ {
// _o2[_obj] - _o1[_obj] // _o2[_obj] - _o1[_obj]
result = ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ); result = ( (_o2[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() ) - ( (_o1[_obj] - bounds[_obj].minimum()) / bounds[_obj].range() );
} }
return result; return result;
} }
}; };
@ -155,110 +155,110 @@ class moeoHypervolumeBinaryMetric : public moeoNormalizedSolutionVsSolutionBinar
{ {
public: public:
/** /**
* Ctor * Ctor
* @param _rho value used to compute the reference point from the worst values for each objective (default : 1.1) * @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) moeoHypervolumeBinaryMetric(double _rho = 1.1) : rho(_rho)
{ {
// not-a-maximization problem check // not-a-maximization problem check
for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++) for (unsigned i=0; i<ObjectiveVector::Traits::nObjectives(); i++)
{ {
if (ObjectiveVector::Traits::maximizing(i)) if (ObjectiveVector::Traits::maximizing(i))
{ {
throw std::runtime_error("Hypervolume binary metric not yet implemented for a maximization problem in moeoHypervolumeBinaryMetric"); throw std::runtime_error("Hypervolume binary metric not yet implemented for a maximization problem in moeoHypervolumeBinaryMetric");
} }
} }
// consistency check // consistency check
if (rho < 1) 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 << "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; cout << "Adjusted to 1" << endl;
rho = 1; 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. * 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 * @warning don't forget to set the bounds for every objective before the call of this function
* @param _o1 the first objective vector * @param _o1 the first objective vector
* @param _o2 the second objective vector * @param _o2 the second objective vector
*/ */
double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2) double operator()(const ObjectiveVector & _o1, const ObjectiveVector & _o2)
{ {
double result; double result;
// if _o1 dominates _o2 // if _o1 dominates _o2
if ( paretoComparator(_o1,_o2) ) if ( paretoComparator(_o1,_o2) )
{ {
result = - hypervolume(_o1, _o2, ObjectiveVector::Traits::nObjectives()-1); result = - hypervolume(_o1, _o2, ObjectiveVector::Traits::nObjectives()-1);
} }
else else
{ {
result = hypervolume(_o2, _o1, ObjectiveVector::Traits::nObjectives()-1); result = hypervolume(_o2, _o1, ObjectiveVector::Traits::nObjectives()-1);
} }
return result; return result;
} }
private: private:
/** value used to compute the reference point from the worst values for each objective */ /** value used to compute the reference point from the worst values for each objective */
double rho; double rho;
/** the bounds for every objective */ /** the bounds for every objective */
using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds; using moeoNormalizedSolutionVsSolutionBinaryMetric < ObjectiveVector, double > :: bounds;
/** Functor to compare two objective vectors according to Pareto dominance relation */ /** Functor to compare two objective vectors according to Pareto dominance relation */
moeoParetoObjectiveVectorComparator < ObjectiveVector > paretoComparator; 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. * 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 _o1 the first objective vector
* @param _o2 the second objective vector * @param _o2 the second objective vector
* @param _obj the objective index * @param _obj the objective index
* @param _flag used for iteration, if _flag=true _o2 is not talen into account (default : false) * @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 hypervolume(const ObjectiveVector & _o1, const ObjectiveVector & _o2, const unsigned _obj, const bool _flag = false)
{ {
double result; double result;
double range = rho * bounds[_obj].range(); double range = rho * bounds[_obj].range();
double max = bounds[_obj].minimum() + range; double max = bounds[_obj].minimum() + range;
// value of _1 for the objective _obj // value of _1 for the objective _obj
double v1 = _o1[_obj]; double v1 = _o1[_obj];
// value of _2 for the objective _obj (if _flag=true, v2=max) // value of _2 for the objective _obj (if _flag=true, v2=max)
double v2; double v2;
if (_flag) if (_flag)
{ {
v2 = max; v2 = max;
} }
else else
{ {
v2 = _o2[_obj]; v2 = _o2[_obj];
} }
// computation of the volume // computation of the volume
if (_obj == 0) if (_obj == 0)
{ {
if (v1 < v2) if (v1 < v2)
{ {
result = (v2 - v1) / range; result = (v2 - v1) / range;
} }
else else
{ {
result = 0; result = 0;
} }
} }
else else
{ {
if (v1 < v2) if (v1 < v2)
{ {
result = ( hypervolume(_o1, _o2, _obj-1, true) * (v2 - v1) / range ) + ( hypervolume(_o1, _o2, _obj-1) * (max - v2) / range ); result = ( hypervolume(_o1, _o2, _obj-1, true) * (v2 - v1) / range ) + ( hypervolume(_o1, _o2, _obj-1) * (max - v2) / range );
} }
else else
{ {
result = hypervolume(_o1, _o2, _obj-1) * (max - v2) / range; result = hypervolume(_o1, _o2, _obj-1) * (max - v2) / range;
} }
} }
return result; return result;
} }
}; };

View file

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

View file

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

View file

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

View file

@ -25,42 +25,42 @@ class moeoCombinedLS : public moeoLS < MOEOT, Type >
{ {
public: public:
/** /**
* Ctor * Ctor
* @param _eval the full evaluator of a solution * @param _eval the full evaluator of a solution
* @param _first_mols the first multi-objective local search to add * @param _first_mols the first multi-objective local search to add
*/ */
moeoCombinedLS(moeoLS < MOEOT, Type > & _first_mols) moeoCombinedLS(moeoLS < MOEOT, Type > & _first_mols)
{ {
combinedLS.push_back (& _first_mols); combinedLS.push_back (& _first_mols);
} }
/** /**
* Adds a new local search to combine * Adds a new local search to combine
* @param _mols the multi-objective local search to add * @param _mols the multi-objective local search to add
*/ */
void add(moeoLS < MOEOT, Type > & _mols) void add(moeoLS < MOEOT, Type > & _mols)
{ {
combinedLS.push_back(& _mols); combinedLS.push_back(& _mols);
} }
/** /**
* Gives a new solution in order to explore the neigborhood. * Gives a new solution in order to explore the neigborhood.
* The new non-dominated solutions are added to the archive * The new non-dominated solutions are added to the archive
* @param _moeo the solution * @param _moeo the solution
* @param _arch the archive of non-dominated solutions * @param _arch the archive of non-dominated solutions
*/ */
void operator () (Type _type, moeoArchive < MOEOT > & _arch) void operator () (Type _type, moeoArchive < MOEOT > & _arch)
{ {
for (unsigned i=0; i<combinedLS.size(); i++) for (unsigned i=0; i<combinedLS.size(); i++)
combinedLS[i] -> operator()(_type, _arch); combinedLS[i] -> operator()(_type, _arch);
} }
private: private:
/** the vector that contains the combined LS */ /** the vector that contains the combined LS */
std::vector< moeoLS < MOEOT, Type > * > combinedLS; std::vector< moeoLS < MOEOT, Type > * > combinedLS;
}; };

View file

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

View file

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

View file

@ -27,89 +27,89 @@ class moeoCrowdingDistanceDiversityAssignment : public moeoDiversityAssignment <
{ {
public: public:
/** the objective vector type of the solutions */ /** the objective vector type of the solutions */
typedef typename MOEOT::ObjectiveVector ObjectiveVector; typedef typename MOEOT::ObjectiveVector ObjectiveVector;
/** /**
* Returns a big value (regarded as infinite) * Returns a big value (regarded as infinite)
*/ */
double inf() const double inf() const
{ {
return std::numeric_limits<double>::max(); return std::numeric_limits<double>::max();
} }
/** /**
* Computes diversity values for every solution contained in the population _pop * Computes diversity values for every solution contained in the population _pop
* @param _pop the population * @param _pop the population
*/ */
void operator()(eoPop < MOEOT > & _pop) void operator()(eoPop < MOEOT > & _pop)
{ {
// number of objectives for the problem under consideration // number of objectives for the problem under consideration
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives(); unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
if (_pop.size() <= 2) if (_pop.size() <= 2)
{ {
for (unsigned i=0; i<_pop.size(); i++) for (unsigned i=0; i<_pop.size(); i++)
{ {
_pop[i].diversity(inf()); _pop[i].diversity(inf());
} }
} }
else else
{ {
setDistances(_pop); setDistances(_pop);
} }
} }
/** /**
* @warning NOT IMPLEMENTED, DO NOTHING ! * @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. * 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 _pop the population
* @param _objVec the objective vector * @param _objVec the objective vector
* @warning NOT IMPLEMENTED, DO NOTHING ! * @warning NOT IMPLEMENTED, DO NOTHING !
*/ */
void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec) void updateByDeleting(eoPop < MOEOT > & _pop, ObjectiveVector & _objVec)
{ {
cout << "WARNING : updateByDeleting not implemented in moeoCrowdingDiversityAssignment" << endl; cout << "WARNING : updateByDeleting not implemented in moeoCrowdingDiversityAssignment" << endl;
} }
private: private:
/** /**
* Sets the distance values * Sets the distance values
* @param _pop the population * @param _pop the population
*/ */
void setDistances (eoPop < MOEOT > & _pop) void setDistances (eoPop < MOEOT > & _pop)
{ {
double min, max, distance; double min, max, distance;
unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives(); unsigned nObjectives = MOEOT::ObjectiveVector::nObjectives();
// set diversity to 0 // set diversity to 0
for (unsigned i=0; i<_pop.size(); i++) for (unsigned i=0; i<_pop.size(); i++)
{ {
_pop[i].diversity(0); _pop[i].diversity(0);
} }
// for each objective // for each objective
for (unsigned obj=0; obj<nObjectives; obj++) for (unsigned obj=0; obj<nObjectives; obj++)
{ {
// comparator // comparator
moeoOneObjectiveComparator < MOEOT > comp(obj); moeoOneObjectiveComparator < MOEOT > comp(obj);
// sort // sort
std::sort(_pop.begin(), _pop.end(), comp); std::sort(_pop.begin(), _pop.end(), comp);
// min & max // min & max
min = _pop[0].objectiveVector()[obj]; min = _pop[0].objectiveVector()[obj];
max = _pop[_pop.size()-1].objectiveVector()[obj]; max = _pop[_pop.size()-1].objectiveVector()[obj];
// set the diversity value to infiny for min and max // set the diversity value to infiny for min and max
_pop[0].diversity(inf()); _pop[0].diversity(inf());
_pop[_pop.size()-1].diversity(inf()); _pop[_pop.size()-1].diversity(inf());
for (unsigned i=1; i<_pop.size()-1; i++) for (unsigned i=1; i<_pop.size()-1; i++)
{ {
distance = (_pop[i+1].objectiveVector()[obj] - _pop[i-1].objectiveVector()[obj]) / (max-min); distance = (_pop[i+1].objectiveVector()[obj] - _pop[i-1].objectiveVector()[obj]) / (max-min);
_pop[i].diversity(_pop[i].diversity() + distance); _pop[i].diversity(_pop[i].diversity() + distance);
} }
} }
} }
}; };

View file

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

View file

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

View file

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

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