Skip to content

Instantly share code, notes, and snippets.

@jonpsy
Last active March 26, 2021 13:23
Show Gist options
  • Save jonpsy/72b428026283bf645c2d343319174c92 to your computer and use it in GitHub Desktop.
Save jonpsy/72b428026283bf645c2d343319174c92 to your computer and use it in GitHub Desktop.
A pseudo code for main loop
#include <bits/stdc++.h>
#include <armadillo>
template<typename MatType,
typename... ArbitraryFunctionType,
typename... CallbackTypes>
typename MatType::elem_type SPEA2::Optimize(
std::tuple<ArbitraryFunctionType...>& objectives,
MatType& iterate,
CallbackTypes&&... callbacks)
{
// .. Sanity checks & typedef
typedef std::reference_wrapper<const MatType> ConstRefMatType;
size_t combinedSize = populationSize + archiveSize;
std::vector<MatType> population(populationSize); //P_{0}
std::vector<MatType> archive(archiveSize);// A_{0} = empty
// C_{0}=P_{0} U A_{0}
std::vector<ConstRefMatType> combinedPopulation(combinedSize);
std::vector<arma::Col<ElemType>> solutionSet(combinedSize);
population = arma::randu(cols, rows) - 0.5 + iterate;
StorePopulation(combinedPopulation, population);
EvaluateObjectives(combinedPopulation, objectives,
solutionSet);
while (gen = 0; gen <= maxGen && terminate != true; ++gen)
{
terminate |= Callback::StepTaken(...);
//! [1] Fitness Assignment.
// FineGrainedFitness => A two step fitness calculation method.
arma::Col<ElemType> objectiveFitness =
FineGrainedFitness(solutionSet);
// Lower fitness is better.
arma::uvec sortedIndices = arma::stable_sort_index(objectiveFitness);
// num solutions for which objectiveFitness is < 1.
size_t numNonDominated = std::count(objectiveFitness,
[&](Elemtype a){ a < 1; })
//! [2] Environment Selection.
// Copy non dominated solutions from combined population to archive.
if (numNonDominated > archiveSize) // Diversity preserve.
archive.clear();
std::copy(archive,
combinedPopulation[sortedIndices(arma::span(0, numNonDominated))]);
// Truncate so that numNonDominated == archive
Truncate(archive);
else //Fill in order of descending fitness.
archive = combinedPopulation[sortedIndices(
arma::span(0, archiveSize))];
EvaluateObjectives(combinedPopulation, objectives,
solutionSet);
// No further modification, just return archive A_{t+1}
if (generation == maxGeneration)
break;
// Genetic operation to get P_{t+1}
ModifyPopulation(population, archive, objectiveFitness);
StorePopulation(combinedPopulation, population);
StoreArchive(combinedPopulation, archive);
}
bestFront = archive;
CallBack::EndOptimization(...);
// Store the minimum sum of objectives.
performance = arma::accu(min_accumulation(solutionSet));
return performance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment