⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mutationswapop.cpp

📁 非常好的进化算法EC 实现平台 可以实现多种算法 GA GP
💻 CPP
字号:
/* *  Open BEAGLE *  Copyright (C) 2001-2005 by Christian Gagne and Marc Parizeau * *  This library is free software; you can redistribute it and/or *  modify it under the terms of the GNU Lesser General Public *  License as published by the Free Software Foundation; either *  version 2.1 of the License, or (at your option) any later version. * *  This library is distributed in the hope that it will be useful, *  but WITHOUT ANY WARRANTY; without even the implied warranty of *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *  Lesser General Public License for more details. * *  You should have received a copy of the GNU Lesser General Public *  License along with this library; if not, write to the Free Software *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA * *  Contact: *  Laboratoire de Vision et Systemes Numeriques *  Departement de genie electrique et de genie informatique *  Universite Laval, Quebec, Canada, G1K 7P4 *  http://vision.gel.ulaval.ca * *//*! *  \file   beagle/GP/src/MutationSwapOp.cpp *  \brief  Source code of class GP::MutationSwapOp. *  \author Christian Gagne *  \author Marc Parizeau *  $Revision: 1.16 $ *  $Date: 2005/10/04 16:25:10 $ */#include "beagle/GP.hpp"#include <algorithm>#include <string>using namespace Beagle;/*! *  \brief Construct a GP swap mutation operator. *  \param inMutationPbName Mutation probability parameter name used in register. *  \param inDistribPbName Swap mutation distribution probability parameter name. *  \param inName Name of the operator. */GP::MutationSwapOp::MutationSwapOp(Beagle::string inMutationPbName,                                   Beagle::string inDistribPbName,                                   Beagle::string inName) :  Beagle::MutationOp(inMutationPbName, inName),  mDistribPbName(inDistribPbName){ }/*! *  \brief Initialize the GP swap mutation operator. *  \param ioSystem System of the evolution. */void GP::MutationSwapOp::initialize(Beagle::System& ioSystem){  Beagle_StackTraceBeginM();  Beagle::MutationOp::initialize(ioSystem);  if(ioSystem.getRegister().isRegistered(mMutationPbName)) {    ioSystem.getRegister().deleteEntry(mMutationPbName);  }  if(ioSystem.getRegister().isRegistered(mMutationPbName)) {    mMutationProba =      castHandleT<Float>(ioSystem.getRegister().getEntry(mMutationPbName));  } else {    mMutationProba = new Float(float(0.05));    string lLongDescrip = "Swap mutation probability for an individual. ";    lLongDescrip += "Swap mutation consists in exchanging the primitive associated to a ";    lLongDescrip += "node by one having the same number of arguments.";    Register::Description lProbaDescription(      "Individual swap mutation prob.",      "Float",      "0.05",      lLongDescrip    );    ioSystem.getRegister().addEntry(mMutationPbName, mMutationProba, lProbaDescription);  }  if(ioSystem.getRegister().isRegistered(mDistribPbName)) {    mDistributionProba = castHandleT<Float>(      ioSystem.getRegister().getEntry(mDistribPbName));  } else {    mDistributionProba = new Float(float(0.5));    string lLongDescrip =      "Probability that a swap mutation point is a branch (node with sub-trees). ";    lLongDescrip += "Value of 1.0 means that all swap mutation points are branches, ";    lLongDescrip += "and value of 0.0 means that all swap mutation points are leaves. ";    lLongDescrip += "Swap mutation consists in exchanging the primitive associated to a ";    lLongDescrip += "node by one having the same number of arguments.";    Register::Description lDistributionDescription(      "Swap mutation distrib. prob.",      "Float",      "0.5",      lLongDescrip    );    ioSystem.getRegister().addEntry(mDistribPbName, mDistributionProba, lDistributionDescription);  }  Beagle_StackTraceEndM("void GP::MutationSwapOp::initialize(Beagle::System& ioSystem)");}/*! *  \brief Swap mutate a GP individual. *  \param ioIndividual GP individual to swap mutate. *  \param ioContext Context of the evolution. *  \return True if the individual is effectively mutated, false if not. */bool GP::MutationSwapOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext){  Beagle_StackTraceBeginM();  GP::Individual& lIndividual  = castObjectT<GP::Individual&>(ioIndividual);  GP::Context& lContext        = castObjectT<GP::Context&>(ioContext);  double lDistrProba           = mDistributionProba->getWrappedValue();  // Store original values.  GP::Tree::Handle lOldTreeHandle = lContext.getGenotypeHandle();  unsigned int lOldTreeIndex = lContext.getGenotypeIndex();  // Select the tree to mutate  unsigned int lNbNodes = 0;  for(unsigned int i=0; i<lIndividual.size(); i++) lNbNodes += lIndividual[i]->size();  if(lNbNodes == 0) return false;  unsigned int lChosenNode = lContext.getSystem().getRandomizer().rollInteger(0, lNbNodes-1);  unsigned int lChosenTree = 0;  for(; (lChosenTree+1)<lIndividual.size(); lChosenTree++) {    if(lChosenNode < lIndividual[lChosenTree]->size()) break;    else lChosenNode -= lIndividual[lChosenTree]->size();  }  GP::Tree& lTree = *lIndividual[lChosenTree];  if(lTree.size() == 0) return false;  // Store the new values       lContext.setGenotypeHandle(lIndividual[lChosenTree]);  lContext.setGenotypeIndex(lChosenTree);  Beagle_LogDebugM(    ioContext.getSystem().getLogger(),    "mutation", "Beagle::GP::MutationSwapOp",    string("Individual before GP swap mutation: ")+ioIndividual.serialize()  );  // Choose the node to mutate.  if(lTree.size() > 1) {    bool lTypeNode = (lContext.getSystem().getRandomizer().rollUniform(0., 1.) < lDistrProba);    while((lTree[lChosenNode].mPrimitive->getNumberArguments() != 0) != lTypeNode) {      lChosenNode = lContext.getSystem().getRandomizer().rollInteger(0, lTree.size()-1);    }  }  Primitive::Handle lOriginalPrimitive = lTree[lChosenNode].mPrimitive;  Beagle_LogVerboseM(    ioContext.getSystem().getLogger(),    "mutation", "Beagle::GP::MutationSwapOp",    string("Swap mutating the ")+uint2ordinal(lChosenNode+1)+    string(" node (primitive: \"")+lOriginalPrimitive->getName()+    string("\" nb args: ")+uint2str(lOriginalPrimitive->getNumberArguments())+    string(") of the ")+uint2ordinal(lChosenTree+1)+string(" tree")  );   GP::PrimitiveSet& lPrimitiveSet = lTree.getPrimitiveSet(lContext);  unsigned int lNbArgsPrimit = lTree[lChosenNode].mPrimitive->getNumberArguments();  // Select primitive to replace choosen one.  Primitive::Handle lChosenPrimitive = lPrimitiveSet.select(lNbArgsPrimit, lContext);  if (lChosenPrimitive==NULL) {    Beagle_LogVerboseM(      ioContext.getSystem().getLogger(),      "mutation", "Beagle::GP::MutationSwapOp",      string("Swap mutation failed because no primitive could be found that had ")+      uint2str(lNbArgsPrimit)+string(" arguments")    );     return false;  }  else {    Beagle_LogDebugM(      ioContext.getSystem().getLogger(),      "mutation", "Beagle::GP::MutationSwapOp",      string("Swap mutation chose primitive \"")+lChosenPrimitive->getName()+string("\"")    );   }  // Replace choose primitive.  lTree[lChosenNode].mPrimitive = lChosenPrimitive->giveReference(lNbArgsPrimit, lContext);  // Restore the original values.  lContext.setGenotypeHandle(lOldTreeHandle);  lContext.setGenotypeIndex(lOldTreeIndex);  Beagle_LogDebugM(    ioContext.getSystem().getLogger(),    "mutation", "Beagle::GP::MutationSwapOp",    string("Individual after GP swap mutation: ")+    ioIndividual.serialize()  );   return true;  Beagle_StackTraceEndM("bool GP::MutationSwapOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)");}/*! *  \brief Read a mutation operator from XML subtree. *  \param inIter XML iterator to use to read crossover operator. *  \param inOpMap Operator map to use to read crossover operator. */void GP::MutationSwapOp::readWithMap(PACC::XML::ConstIterator inIter, OperatorMap& inOpMap){  Beagle_StackTraceBeginM();  if((inIter->getType()!=PACC::XML::eData) || (inIter->getValue()!=getName().c_str())) {    std::ostringstream lOSS;    lOSS << "tag <" << getName() << "> expected!" << std::flush;    throw Beagle_IOExceptionNodeM(*inIter, lOSS.str().c_str());  }  string mMutationPbReadName = inIter->getAttribute("mutationpb").c_str();  if(mMutationPbReadName.empty() == false) mMutationPbName = mMutationPbReadName;  string mDistribPbReadName = inIter->getAttribute("distrpb").c_str();  if(mDistribPbReadName.empty() == false) mDistribPbName = mDistribPbReadName;  Beagle_StackTraceEndM("void GP::MutationSwapOp::readWithMap(PACC::XML::ConstIterator inIter, OperatorMap& inOpMap)");}/*! *  \brief Write mutation operator into XML streamer. *  \param ioStreamer XML streamer to write mutation operator into. *  \param inIndent Whether XML output should be indented. */void GP::MutationSwapOp::writeContent(PACC::XML::Streamer& ioStreamer, bool inIndent) const{  Beagle_StackTraceBeginM();  Beagle::MutationOp::writeContent(ioStreamer, inIndent);  ioStreamer.insertAttribute("distrpb", mDistribPbName);  Beagle_StackTraceEndM("void GP::MutationSwapOp::writeContent(PACC::XML::Streamer& ioStreamer, bool inIndent) const");}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -