当前位置: 首页>>代码示例>>C++>>正文


C++ beagle::Context类代码示例

本文整理汇总了C++中beagle::Context的典型用法代码示例。如果您正苦于以下问题:C++ Context类的具体用法?C++ Context怎么用?C++ Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: operate

/*!
 *  \brief Compile a shared library for evaluating the fitness of each individual in deme specified.
 *  \param ioDeme Reference to the deme for which to compile a shared library.
 *  \param ioContext Evolutionary context of the operation.
 *
 */
void SharedLibCompileOp::operate(Beagle::Deme& ioDeme, Beagle::Context& ioContext)
{  
    Beagle_StackTraceBeginM();

	std::string lPathLib;

    /* The abstract class Operator is defined in the namespace Beagle.
    * Thus, the Context passed in is from Beagle as well.
    * However, Beagle::GP::Individual::deparse requires a Beagle::GP::Context.
    * Cast the Beagle::Context passed in to a Beagle::GP::Context.
    */
    Beagle::GP::Context lContext= Beagle::castObjectT<Beagle::GP::Context&>(ioContext);

	// Create a SharedLibCompiler.
    int lNrColumns= castHandleT<Int>(ioContext.getSystem().getRegister()["icu.dataset.columns"])->getWrappedValue();
    std::string lTmpDirectory= castHandleT<String>(ioContext.getSystem().getRegister()["icu.compiler.tmp-directory"])->getWrappedValue();
    SharedLibCompiler lSharedLibCompiler(lNrColumns, lTmpDirectory);
    
    // Add individuals, compile.
    for(Beagle::Deme::const_iterator lIndividual=ioDeme.begin(); lIndividual!=ioDeme.end(); ++lIndividual)
    {
        Beagle::GP::Individual::Handle lGPIndividual= castHandleT<Beagle::GP::Individual>(*lIndividual);
		lSharedLibCompiler.addIndividual(*lGPIndividual, lContext.getGeneration(), lContext.getDemeIndex(), lIndividual- ioDeme.begin());
	}
	std::ostringstream lLibName;
	lLibName << "g" << lContext.getGeneration() << "_d" << lContext.getDemeIndex();
	lPathLib= lSharedLibCompiler.compile(lLibName.str());

    // Update register with the path of the newly compiled library.
    lContext.getSystem().getRegister().modifyEntry("icu.compiler.lib-path", new String(lPathLib));

    Beagle_StackTraceEndM("void SharedLibCompileOp::operate(Deme& ioDeme, Context& ioContext)");
}
开发者ID:emigdioz,项目名称:open-beagle-fast-gp,代码行数:39,代码来源:SharedLibCompileOp.cpp

示例2: expand

/*!
 *  \brief Expand modules in trees of actual population.
 *  \param ioDeme Deme to apply operation.
 *  \param ioContext Evolutionary context.
 */
void GP::ModuleExpandOp::operate(Beagle::Deme& ioDeme, Beagle::Context& ioContext)
{
    Beagle_StackTraceBeginM();
    Beagle_LogTraceM(
        ioContext.getSystem().getLogger(),
        "EMA", "GP::ModuleExpandOp",
        std::string("Expanding modules of the ")+
        uint2ordinal(ioContext.getDemeIndex()+1)+" deme"
    );
    if(mExpandProba->getWrappedValue()==0.0) return;

    Beagle_LogVerboseM(
        ioContext.getSystem().getLogger(),
        "EMA", "GP::ModuleExpandOp",
        std::string("Expanding modules with probability ")+
        dbl2str(mExpandProba->getWrappedValue())
    );

    GP::Context& lGPContext = castObjectT<GP::Context&>(ioContext);
    GP::Individual::Handle lOldIndividualHandle = lGPContext.getIndividualHandle();
    unsigned int lOldIndividualIndex = lGPContext.getIndividualIndex();
    GP::Tree::Handle lOldGenotypeHandle = lGPContext.getGenotypeHandle();
    unsigned int lOldGenotypeIndex = lGPContext.getGenotypeIndex();
    const std::string lModuleName = mModulePrimitName->getWrappedValue();
    for(unsigned int i=0; i<ioDeme.size(); i++) {
        for(unsigned int j=0; j<ioDeme[i]->size(); ++j) {
            GP::Tree& lTree = castObjectT<GP::Tree&>(*(*ioDeme[i])[j]);
            for(unsigned int k=0; k<lTree.size(); ++k) {
                if(lTree[k].mPrimitive->getName() == lModuleName) {
                    if(ioContext.getSystem().getRandomizer().rollUniform() <= mExpandProba->getWrappedValue()) {
                        lGPContext.setIndividualHandle(castHandleT<GP::Individual>(ioDeme[i]));
                        lGPContext.setIndividualIndex(i);
                        lGPContext.setGenotypeHandle(castHandleT<GP::Tree>((*ioDeme[i])[j]));
                        lGPContext.setGenotypeIndex(j);
                        Beagle_LogVerboseM(
                            ioContext.getSystem().getLogger(),
                            "expand", "ExpandOp",
                            std::string("Expanding the ") +uint2ordinal(i+1)+" individual"
                        );
                        expand(k, lTree, lGPContext);
                    }
                }
            }
        }
    }
    lGPContext.setGenotypeHandle(lOldGenotypeHandle);
    lGPContext.setGenotypeIndex(lOldGenotypeIndex);
    lGPContext.setIndividualHandle(lOldIndividualHandle);
    lGPContext.setIndividualIndex(lOldIndividualIndex);

    Beagle_LogObjectDebugM(
        ioContext.getSystem().getLogger(),
        "EMA", "GP::ModuleExpandOp",
        *(ioContext.getSystem().getComponent("ModuleVector"))
    );
    Beagle_StackTraceEndM();
}
开发者ID:falcong,项目名称:beagle-1,代码行数:62,代码来源:ModuleExpandOp.cpp

示例3: hits

/*!
 *  \brief Check if the evolution must terminate.
 *  \param inDeme Actual deme of the evolution.
 *  \param ioContext Actual evolution context.
 *  \return True if the ending criterion is reached, false if not.
 */
bool GP::TermMaxHitsOp::terminate(const Beagle::Deme& inDeme, Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	if(mMaxHits->getWrappedValue() == 0) return false;
	for(unsigned int i=0; i<inDeme.size(); i++) {
		const GP::FitnessKoza::Handle lFitness =
		    castHandleT<const GP::FitnessKoza>(inDeme[i]->getFitness());
		if(mMaxHits->getWrappedValue() <= lFitness->getHits()) {
			Beagle_LogInfoM(
			    ioContext.getSystem().getLogger(),
			    "termination", "Beagle::GP::TermMaxHitsOp",
			    std::string("Maximum number of hits (") +
			    uint2str(mMaxHits->getWrappedValue()) +
			    std::string(") termination criterion reached")
			);
			Beagle_LogInfoM(
			    ioContext.getSystem().getLogger(),
			    "termination", "Beagle::GP::TermMaxHitsOp",
			    std::string("The ")+uint2ordinal(i+1) +
			    std::string(" individual of the deme has ") +
			    uint2str(lFitness->getHits())+std::string(" hits")
			);
			ioContext.setTerminationSuccessful();
			return true;
		}
	}
	Beagle_LogTraceM(
	    ioContext.getSystem().getLogger(),
	    "termination", "Beagle::GP::TermMaxHitsOp",
	    std::string("Maximum number of hits (") +
	    uint2str(mMaxHits->getWrappedValue()) +
	    std::string(") termination criterion not reached")
	);
	return false;
	Beagle_StackTraceEndM("bool GP::TermMaxHitsOp::terminate(const Beagle::Deme& inDeme, Beagle::Context& ioContext)");
}
开发者ID:splodginald,项目名称:MPI-PACC-OpenBeagle,代码行数:42,代码来源:TermMaxHitsOp.cpp

示例4:

/*!
 *  \brief Mutate a linear GP individual.
 *  \param ioIndividual Linear GP individual to mutate.
 *  \param ioContext Context of the evolution.
 *  \return True if the individual is effectively mutated, false if not.
 */
bool LinGP::MutationOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)
{
	Beagle_ValidateParameterM(mInstructMutateProba->getWrappedValue()>=0.0,
	                          mInstructMutatePbName, "<0");
	bool lMutated = false;
	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    std::string("Linear GP mutation probability is: ")+
	    dbl2str(mInstructMutateProba->getWrappedValue())
	);

	LinGP::Context& lLinGPContext = castObjectT<LinGP::Context&>(ioContext);
	LinGP::InstructionSuperSet::Handle lInsSS =
	    castHandleT<LinGP::InstructionSuperSet>(lLinGPContext.getSystem().getComponent("LinGP-InstructionSuperSet"));

	for(unsigned int i=0; i<ioIndividual.size(); i++) {
		LinGP::Program::Handle lProgram = castHandleT<LinGP::Program>(ioIndividual[i]);
		Beagle_LogVerboseM(
		    ioContext.getSystem().getLogger(),
		    std::string("Mutating the ")+uint2ordinal(i+1)+" program"
		);
		Beagle_LogDebugM(
		    ioContext.getSystem().getLogger(),
		    *lProgram
		);
		for(unsigned int j=0; j<lProgram->size(); j++) {
			double lRolledPb = ioContext.getSystem().getRandomizer().rollUniform();
			if(lRolledPb <= mInstructMutateProba->getWrappedValue()) {
				(*lProgram)[j] =
				    lInsSS->getInstructionSets()[i]->selectRandomInstruction(lLinGPContext.getSystem())->giveReference(lLinGPContext);
				lMutated = true;
			}
		}
		if(lMutated) {
			Beagle_LogVerboseM(
			    ioContext.getSystem().getLogger(),
			    std::string("The program has been mutated")
			);
			Beagle_LogDebugM(
			    ioContext.getSystem().getLogger(),
			    *lProgram
			);
		} else {
			Beagle_LogVerboseM(
			    ioContext.getSystem().getLogger(),
			    std::string("The program has not been mutated")
			);
		}
	}
	return lMutated;
}
开发者ID:GhostGambler,项目名称:beagle,代码行数:57,代码来源:MutationOp.cpp

示例5: lDesiredTypes

/*!
 *  \brief Standard mutate a constrained GP individual.
 *  \param ioIndividual GP individual to standard mutate.
 *  \param ioContext Context of the evolution.
 *  \return True if the individual is effectively mutated, false if not.
 */
bool GP::MutationStandardSelectiveConstrainedOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	GP::Individual& lIndividual        = castObjectT<GP::Individual&>(ioIndividual);
	GP::Context& lContext              = castObjectT<GP::Context&>(ioContext);
	unsigned int lMaxTreeDepth         = mMaxTreeDepth->getWrappedValue();
	unsigned int lMaxRegenerationDepth = mMaxRegenerationDepth->getWrappedValue();
	
	//Select node to mutate
	unsigned int lChoosenTree = 0;
	unsigned int lChoosenNode = 0;
	
	bool lDoParameterSearch = (lContext.getSystem().getRandomizer().rollUniform(0.0, 1.0) <= mMutParameterPb->getWrappedValue());
	
	//Select primitive based on type
	for(unsigned int lTry = 0; lTry < 2; ++lTry) { //Do only twice
		std::vector<const std::type_info*> lDesiredTypes(1, ArgEph);
		RouletteT< std::pair<unsigned int,unsigned int> > lRoulette;
		SelectiveConstrainedSelectionOp::buildRoulette(lRoulette, lDesiredTypes, lIndividual, lContext,!lDoParameterSearch,lDoParameterSearch);
		
		if(lRoulette.size() == 0) {
			if(lDoParameterSearch) {
				Beagle_LogVerboseM(
								   ioContext.getSystem().getLogger(),
								   "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
								   string("No EphemeralDouble node found.")
								   );
			}
			else {
				Beagle_LogVerboseM(
								   ioContext.getSystem().getLogger(),
								   "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
								   string("No non EphemeralDouble node found.")
								   );
			}
			lDoParameterSearch = !lDoParameterSearch;
			if(lTry >= 1) {
				Beagle_LogVerboseM(
								   ioContext.getSystem().getLogger(),
								   "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
								   "Unable to GP standard mutate the individual"
								   );
				return false;
			}
		}
		else { 
			std::pair<unsigned int,unsigned int> lSelectedNode = lRoulette.select(ioContext.getSystem().getRandomizer());
			lChoosenTree = lSelectedNode.first;
			lChoosenNode = lSelectedNode.second;
			break;
		}
	}
	
	if(lDoParameterSearch) {
		Beagle_LogVerboseM(
						   ioContext.getSystem().getLogger(),
						   "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
						   string("Mutation applied only on EphemeralDouble node.")
						   );
	}
	else {
		Beagle_LogVerboseM(
						   ioContext.getSystem().getLogger(),
						   "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
						   string("Mutation applied on node that are not EphemeralDouble.")
						   );
	}
	
	
	unsigned int lOldGenotypeIndex = lContext.getGenotypeIndex();
	GP::Tree::Handle lOldGenotypeHandle = lContext.getGenotypeHandle();
	
	Beagle_LogDebugM(
					 ioContext.getSystem().getLogger(),
					 "mutation", "Beagle::GP::MutationStandardSelectiveConstrainedOp",
					 std::string("Individual before GP standard mutation: ")+
					 ioIndividual.serialize()
					 );
	
	GP::Tree::Handle lActualTree = lIndividual[lChoosenTree];
	GP::Tree::Handle lNewTree    = castHandleT<GP::Tree>(lIndividual.getTypeAlloc()->allocate());
	lNewTree->setPrimitiveSetIndex(lActualTree->getPrimitiveSetIndex());
	lNewTree->setNumberArguments(lActualTree->getNumberArguments());
	unsigned int lChoosenNodeSubTreeSize = (*lActualTree)[lChoosenNode].mSubTreeSize;
	lNewTree->insert(lNewTree->end(), lActualTree->begin(), lActualTree->begin()+lChoosenNode);
	lContext.setGenotypeIndex(lChoosenTree);
	lContext.setGenotypeHandle(lActualTree);
	lContext.emptyCallStack();
	lActualTree->setContextToNode(lChoosenNode, lContext);
	lContext.popCallStack();
	const unsigned int lMaxSubTreeDepth =
    minOf<unsigned int>(lMaxTreeDepth - lContext.getCallStackSize(), lMaxRegenerationDepth);
	lIndividual[lChoosenTree] = lNewTree;
	lContext.setGenotypeHandle(lNewTree);
//.........这里部分代码省略.........
开发者ID:ComputationalIntelligenceAndMechatronics,项目名称:HBGGP,代码行数:101,代码来源:MutationStandardSelectiveConstrainedOp.cpp

示例6: maxOf

/*!
 *  \brief Calculate statistics of a given deme.
 *  \param outStats Evaluated statistics.
 *  \param ioDeme Deme to evalute the statistics.
 *  \param ioContext Context of the evolution.
 */
void GP::StatsCalcFitnessKozaOp::calculateStatsDeme(Beagle::Stats& outStats,
        Beagle::Deme& ioDeme,
        Beagle::Context& ioContext) const
{
	Beagle_StackTraceBeginM();

	outStats.clear();
	outStats.clearItems();
	outStats.addItem("processed", ioContext.getProcessedDeme());
	outStats.addItem("total-processed", ioContext.getTotalProcessedDeme());

	if(ioDeme.size() == 0) {
		outStats.setGenerationValues(std::string("deme")+uint2str(ioContext.getDemeIndex()),
		                             ioContext.getGeneration(), 0, true);

		outStats.resize(7);
		outStats[0].mID = "normalized";
		outStats[0].mAvg = 0.0;
		outStats[0].mStd = 0.0;
		outStats[0].mMax = 0.0;
		outStats[0].mMin = 0.0;

		outStats[1].mID = "adjusted";
		outStats[1].mAvg = 0.0;
		outStats[1].mStd = 0.0;
		outStats[1].mMax = 0.0;
		outStats[1].mMin = 0.0;

		outStats[2].mID = "standardized";
		outStats[2].mAvg = 0.0;
		outStats[2].mStd = 0.0;
		outStats[2].mMax = 0.0;
		outStats[2].mMin = 0.0;

		outStats[3].mID = "raw";
		outStats[3].mAvg = 0.0;
		outStats[3].mStd = 0.0;
		outStats[3].mMax = 0.0;
		outStats[3].mMin = 0.0;

		outStats[4].mID = "hits";
		outStats[4].mAvg = 0.0;
		outStats[4].mStd = 0.0;
		outStats[4].mMax = 0.0;
		outStats[4].mMin = 0.0;

		outStats[5].mID = "treedepth";
		outStats[5].mAvg = 0.0;
		outStats[5].mStd = 0.0;
		outStats[5].mMax = 0.0;
		outStats[5].mMin = 0.0;

		outStats[6].mID = "treesize";
		outStats[6].mAvg = 0.0;
		outStats[6].mStd = 0.0;
		outStats[6].mMax = 0.0;
		outStats[6].mMin = 0.0;
		return;
	}

	const GP::Individual::Handle lFirstIndiv =
	    castHandleT<GP::Individual>(ioDeme[0]);
	const GP::FitnessKoza::Handle lFirstIndivFitness =
	    castHandleT<GP::FitnessKoza>(lFirstIndiv->getFitness());

	if(ioDeme.size() == 1) {
		outStats.setGenerationValues(std::string("deme")+uint2str(ioContext.getDemeIndex()),
		                             ioContext.getGeneration(), 1, true);

		outStats.resize(7);
		outStats[0].mID = "normalized";
		outStats[0].mAvg = lFirstIndivFitness->getNormalizedFitness();
		outStats[0].mStd = 0.0;
		outStats[0].mMax = lFirstIndivFitness->getNormalizedFitness();
		outStats[0].mMin = lFirstIndivFitness->getNormalizedFitness();

		outStats[1].mID = "adjusted";
		outStats[1].mAvg = lFirstIndivFitness->getAdjustedFitness();
		outStats[1].mStd = 0.0;
		outStats[1].mMax = lFirstIndivFitness->getAdjustedFitness();
		outStats[1].mMin = lFirstIndivFitness->getAdjustedFitness();

		outStats[2].mID = "standardized";
		outStats[2].mAvg = lFirstIndivFitness->getStandardizedFitness();
		outStats[2].mStd = 0.0;
		outStats[2].mMax = lFirstIndivFitness->getStandardizedFitness();
		outStats[2].mMin = lFirstIndivFitness->getStandardizedFitness();

		outStats[3].mID = "raw";
		outStats[3].mAvg = lFirstIndivFitness->getRawFitness();
		outStats[3].mStd = 0.0;
		outStats[3].mMax = lFirstIndivFitness->getRawFitness();
		outStats[3].mMin = lFirstIndivFitness->getRawFitness();

//.........这里部分代码省略.........
开发者ID:splodginald,项目名称:MPI-PACC-OpenBeagle,代码行数:101,代码来源:StatsCalcFitnessKozaOp.cpp

示例7: if

/*!
 *  \brief Swap subtree mutate a GP individual.
 *  \param ioIndividual GP individual to swap subtree mutate.
 *  \param ioContext Context of the evolution.
 */
bool GP::MutationSwapSubtreeOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	// Initial parameters checks.
	Beagle_AssertM(ioIndividual.size() > 0);
	Beagle_ValidateParameterM(mNumberAttempts->getWrappedValue()>0, "gp.try", ">0");

	// Cast method arguments.
	GP::Individual&     lGPIndiv      = castObjectT<GP::Individual&>(ioIndividual);
	GP::Context&        lContext1     = castObjectT<GP::Context&>(ioContext);
	Context::Alloc::Handle lContextAlloc =
	    castHandleT<Context::Alloc>(ioContext.getSystem().getFactory().getConceptAllocator("Context"));
	GP::Context::Handle lContextHdl2  = castHandleT<GP::Context>(lContextAlloc->clone(lContext1));

	const Factory& lFactory = ioContext.getSystem().getFactory();
	GP::Tree::Alloc::Handle lTreeAlloc =
		castHandleT<GP::Tree::Alloc>(lFactory.getConceptAllocator("Genotype"));

	// Get parameters in local values, with the total number of nodes of the mutated individual.
	bool             lMatingDone     = false;
	float            lDistrProba     = mDistributionProba->getWrappedValue();
	unsigned int     lMaxTreeDepth   = mMaxTreeDepth->getWrappedValue();
	GP::Tree::Handle lOldTreeHandle1 = lContext1.getGenotypeHandle();
	unsigned int     lOldTreeIndex1  = lContext1.getGenotypeIndex();
	unsigned int     lSizeIndiv      = 0;
	for(unsigned int i=0; i<lGPIndiv.size(); ++i) lSizeIndiv += lGPIndiv[i]->size();

	// Some outputs.
	Beagle_LogDebugM(
	    lContext1.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationSwapSubtreeOp",
	    "Individual tried for swap subtree mutation (before)"
	);
	Beagle_LogObjectDebugM(
	    lContext1.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationSwapSubtreeOp",
	    lGPIndiv
	);

	// Mutation loop. Try the given number of attempts to mutation the individual.
	for(unsigned int lAttempt=0; lAttempt < mNumberAttempts->getWrappedValue(); lAttempt++) {

		// Calculate the number of nodes in the individual
		unsigned int lNbNodes = 0;
		for(unsigned int i=0; i<lGPIndiv.size(); i++) lNbNodes += lGPIndiv[i]->size();
		if(lNbNodes == 0) return false;

		// Choose a node of the individual to mutate.
		unsigned int lNode1 = lContext1.getSystem().getRandomizer().rollInteger(0, lNbNodes-1);

		// Get the tree in which the choosen node is. Change the global node index to the tree's index.
		unsigned int lChoosenTree = 0;
		for(; lChoosenTree<lGPIndiv.size(); ++lChoosenTree) {
			if(lNode1 < lGPIndiv[lChoosenTree]->size()) break;
			Beagle_AssertM(lNode1 >= lGPIndiv[lChoosenTree]->size());
			lNode1 -= lGPIndiv[lChoosenTree]->size();
		}
		Beagle_AssertM(lChoosenTree < lGPIndiv.size());

		// Cannot do anything with an tree of size <= 1.
		if(lGPIndiv[lChoosenTree]->size() <= 1) continue;

		// Some outputs.
		Beagle_LogVerboseM(
		    lContext1.getSystem().getLogger(),
		    "mutation", "Beagle::GP::MutationSwapSubtreeOp",
		    std::string("Trying a swap subtree mutation of the ")+uint2ordinal(lChoosenTree+1)+
		    std::string(" tree")
		);

		// Make two clones of the choosen tree.
		GP::Tree::Handle lTreeClone1 = castHandleT<GP::Tree>(lTreeAlloc->clone(*lGPIndiv[lChoosenTree]));
		GP::Tree::Handle lTreeClone2 = castHandleT<GP::Tree>(lTreeAlloc->clone(*lGPIndiv[lChoosenTree]));

		// Now we decide whether the swap subtree mutation is internal or external.
		bool lMutationType = lContext1.getSystem().getRandomizer().rollUniform(0.0, 1.0) < lDistrProba;

		// Cannot do an internal mutation when there is only one branch in the tree.
		if(lTreeClone1->size() == (*lTreeClone1)[0].mPrimitive->getNumberArguments()+1)
			lMutationType = false;

		// This is special case, a linear tree. Cannot do an external mutation.
		if(lTreeClone1->size() == (*lTreeClone1)[1].mSubTreeSize+1) {
			if(lTreeClone1->size()==2) continue;   // Cannot do anything here with the tree.
			lMutationType = true;
		}

		// lMutationType is true -> internal mutation
		if(lMutationType)  {

			// If the selected node is a terminal, or a branch with a subtree made only of terminals,
			// choose another node in the same tree.
			while((*lTreeClone1)[lNode1].mSubTreeSize ==
//.........这里部分代码省略.........
开发者ID:AngelGate,项目名称:beagle,代码行数:101,代码来源:MutationSwapSubtreeOp.cpp

示例8: maxOf

/*!
 *  \brief Calculate MCC statistics of a given deme.
 *  \param outStats  Evaluated statistics.
 *  \param ioDeme    Deme to evalute.
 *  \param ioContext Context of the evolution.
 *
 *  The following statistics are calculated and made available in outStats:
 *    + mcc (as returned by FitnessMCC::getValue)
 *    + true-positives
 *    + false-positives
 *    + true-negatives
 *    + false-negatives
 *    + true-positives-relative
 *    + false-positives-relative
 *    + true-negatives-relative
 *    + false-negatives-relative
 *    + treedepth
 *    + treesize
 *
 */
void GP::StatsCalcFitnessMCCOp::calculateStatsDeme(Beagle::Stats& outStats,
        Beagle::Deme& ioDeme,
        Beagle::Context& ioContext) const
{
	Beagle_StackTraceBeginM();

	outStats.clear();
	outStats.clearItems();
	outStats.addItem("processed", ioContext.getProcessedDeme());
	outStats.addItem("total-processed", ioContext.getTotalProcessedDeme());

//std::cerr << ioDeme.size() << std::endl;

	if(ioDeme.size() == 0) {
	    /*
	     * The deme does not contain any individuals.
	     * Set all statistics to 0.0.
	     */
		outStats.setGenerationValues(std::string("deme")+uint2str(ioContext.getDemeIndex()),
		                             ioContext.getGeneration(), 0, true);

		outStats.resize(11);
		outStats[0].mID = "mcc";
		outStats[0].mAvg = 0.0;
		outStats[0].mStd = 0.0;
		outStats[0].mMax = 0.0;
		outStats[0].mMin = 0.0;

		outStats[1].mID = "true-positives";
		outStats[1].mAvg = 0.0;
		outStats[1].mStd = 0.0;
		outStats[1].mMax = 0.0;
		outStats[1].mMin = 0.0;

		outStats[2].mID = "false-positives";
		outStats[2].mAvg = 0.0;
		outStats[2].mStd = 0.0;
		outStats[2].mMax = 0.0;
		outStats[2].mMin = 0.0;

		outStats[3].mID = "true-negatives";
		outStats[3].mAvg = 0.0;
		outStats[3].mStd = 0.0;
		outStats[3].mMax = 0.0;
		outStats[3].mMin = 0.0;

		outStats[4].mID = "false-negatives";
		outStats[4].mAvg = 0.0;
		outStats[4].mStd = 0.0;
		outStats[4].mMax = 0.0;
		outStats[4].mMin = 0.0;

		outStats[5].mID = "true-positives-relative";
		outStats[5].mAvg = 0.0;
		outStats[5].mStd = 0.0;
		outStats[5].mMax = 0.0;
		outStats[5].mMin = 0.0;

		outStats[6].mID = "false-positives-relative";
		outStats[6].mAvg = 0.0;
		outStats[6].mStd = 0.0;
		outStats[6].mMax = 0.0;
		outStats[6].mMin = 0.0;

		outStats[7].mID = "true-negatives-relative";
		outStats[7].mAvg = 0.0;
		outStats[7].mStd = 0.0;
		outStats[7].mMax = 0.0;
		outStats[7].mMin = 0.0;

		outStats[8].mID = "false-negatives-relative";
		outStats[8].mAvg = 0.0;
		outStats[8].mStd = 0.0;
		outStats[8].mMax = 0.0;
		outStats[8].mMin = 0.0;

		outStats[9].mID = "treedepth";
		outStats[9].mAvg = 0.0;
		outStats[9].mStd = 0.0;
		outStats[9].mMax = 0.0;
//.........这里部分代码省略.........
开发者ID:emigdioz,项目名称:open-beagle-fast-gp,代码行数:101,代码来源:StatsCalcFitnessMCCOp.cpp

示例9: Beagle_RunTimeExceptionM

/*!
 *  \brief Initialize the trees of an individual.
 *  \param outIndividual Individual to initialize.
 *  \param ioContext Evolution context.
 *  \throw Beagle::RunTimeException If the min/max depths are incorrectly set.
 */
void GP::InitializationOp::initIndividual(Beagle::Individual& outIndividual,
        Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
#ifndef BEAGLE_NDEBUG
	if (mMinTreeDepth==NULL || mMaxTreeDepth==NULL)
		throw Beagle_RunTimeExceptionM(std::string("GP::InitializationOp has not been initialized.").
		                               append(" Consider the GP::InitializationOp::registerParams() method."));
	if(*mMinTreeDepth > *mMaxTreeDepth) {
		std::string lMessage = "GP::InitializationOp::initIndividual: Minimum tree depth is superior ";
		lMessage += "to the maximum tree depth. Could not initialize the individuals!";
		throw Beagle::ValidationException(lMessage);
	}
#endif // BEAGLE_NDEBUG
	Beagle_ValidateParameterM(mMinTreeDepth->getWrappedValue()>0,"gp.init.mindepth",">0");

	GP::Individual& lIndividual = castObjectT<GP::Individual&>(outIndividual);
	GP::Context& lContext = castObjectT<GP::Context&>(ioContext);

	GP::PrimitiveSuperSet::Handle lSuperSet =
	    castHandleT<GP::PrimitiveSuperSet>(ioContext.getSystem().getComponent("GP-PrimitiveSuperSet"));
	if(lSuperSet == NULL) {
		throw Beagle_RunTimeExceptionM("There should be a GP::PrimitiveSuperSet component in the system");
	}
	const unsigned int lPrimitiveSuperSetSize = lSuperSet->size();
	const Factory& lFactory = ioContext.getSystem().getFactory();
#ifndef BEAGLE_NDEBUG
	if(lPrimitiveSuperSetSize == 0)
		throw Beagle_RunTimeExceptionM(std::string("GP::InitializationOp::initIndividual(): There ").
		                               append(" are no PrimitiveSets in the PrimitiveSuperSet.  There needs to be at least one").
		                               append(" PrimitiveSet. See the examples that are included with Beagle to learn how").
		                               append(" to create a PrimitiveSet, add Primitives to it, and then construct a System based").
		                               append(" on the PrimitiveSet."));
#endif // BEAGLE_NDEBUG

	// Choose randomly the number of individuals in tree
	const unsigned int lMaxDepth   = mMaxTreeDepth->getWrappedValue();
	const unsigned int lMinDepth   = mMinTreeDepth->getWrappedValue();
	const unsigned int lMaxNbTrees = mMaxNumberTrees->getWrappedValue();
	const unsigned int lMinNbTrees = mMinNumberTrees->getWrappedValue();
	Beagle_AssertM(lMaxNbTrees >= lMinNbTrees);
	const unsigned int lNbTrees =
	    ioContext.getSystem().getRandomizer().rollInteger(lMinNbTrees,lMaxNbTrees);
	Genotype::Alloc::Handle lGenotypeAlloc =
		castHandleT<Genotype::Alloc>(lFactory.getConceptAllocator("Genotype"));
	lIndividual.clear();
	for(unsigned int i=0; i<lNbTrees; ++i) {
		lIndividual.push_back(castHandleT<Genotype>(lGenotypeAlloc->allocate()));
	}
	GP::Tree::Handle lOldTreeHandle = lContext.getGenotypeHandle();
	unsigned int lOldTreeIndex = lContext.getGenotypeIndex();
	for(unsigned int i=0; i<lIndividual.size(); ++i) {
		if(i<lPrimitiveSuperSetSize) lIndividual[i]->setPrimitiveSetIndex(i);
		else lIndividual[i]->setPrimitiveSetIndex(lPrimitiveSuperSetSize-1);
		const unsigned int lMaxArgs =
		    (i<mMaxTreeArgs->size()) ? (*mMaxTreeArgs)[i] : mMaxTreeArgs->back();
		const unsigned int lMinArgs =
		    (i<mMinTreeArgs->size()) ? (*mMinTreeArgs)[i] : mMinTreeArgs->back();
		Beagle_AssertM(lMaxArgs >= lMinArgs);
		const unsigned int lNbArgs =
		    ioContext.getSystem().getRandomizer().rollInteger(lMinArgs,lMaxArgs);
		lIndividual[i]->setNumberArguments(lNbArgs);
	}
	for(unsigned int i=0; i<lIndividual.size(); ++i) {
		lContext.setGenotypeHandle(lIndividual[i]);
		lContext.setGenotypeIndex(i);
		const unsigned int lTreeDepth =
		    lContext.getSystem().getRandomizer().rollInteger(lMinDepth,lMaxDepth);
		lContext.emptyCallStack();
		lIndividual[i]->clear();
		initTree(*lIndividual[i], lMinDepth, lTreeDepth, lContext);
	}

	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "initialization", "Beagle::GP::InitializationOp",
	    std::string("Initialized individual:")
	);
	Beagle_LogObjectDebugM(
	    ioContext.getSystem().getLogger(),
	    "initialization", "Beagle::GP::InitializationOp",
	    lIndividual
	);

	lContext.setGenotypeIndex(lOldTreeIndex);
	lContext.setGenotypeHandle(lOldTreeHandle);
	Beagle_StackTraceEndM();
}
开发者ID:AngelGate,项目名称:beagle,代码行数:94,代码来源:InitializationOp.cpp

示例10:

/*!
 *  \brief Standard mutate a constrained GP individual.
 *  \param ioIndividual GP individual to standard mutate.
 *  \param ioContext Context of the evolution.
 *  \return True if the individual is effectively mutated, false if not.
 */
bool STGP::MutationStandardConstrainedOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	GP::Individual& lIndividual        = castObjectT<GP::Individual&>(ioIndividual);
	GP::Context& lContext              = castObjectT<GP::Context&>(ioContext);
	unsigned int lMaxTreeDepth         = mMaxTreeDepth->getWrappedValue();
	unsigned int lMaxRegenerationDepth = mMaxRegenerationDepth->getWrappedValue();

	unsigned int lNbNodes = 0;
	for(unsigned int i=0; i<lIndividual.size(); i++) lNbNodes += lIndividual[i]->size();
	if(lNbNodes == 0) return false;
	unsigned int lChoosenNode = lContext.getSystem().getRandomizer().rollInteger(0, lNbNodes-1);
	unsigned int lChoosenTree = 0;
	for(; (lChoosenTree+1)<lIndividual.size(); lChoosenTree++) {
		if(lChoosenNode < lIndividual[lChoosenTree]->size()) break;
		else lChoosenNode -= lIndividual[lChoosenTree]->size();
	}

	const Factory& lFactory = ioContext.getSystem().getFactory();
	GP::Tree::Alloc::Handle lTreeAlloc =
		castHandleT<GP::Tree::Alloc>(lFactory.getConceptAllocator("Genotype"));

	unsigned int lOldGenotypeIndex = lContext.getGenotypeIndex();
	GP::Tree::Handle lOldGenotypeHandle = lContext.getGenotypeHandle();

	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "Individual before GP standard mutation"
	);
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    ioIndividual
	);

	GP::Tree::Handle lActualTree = lIndividual[lChoosenTree];
	GP::Tree::Handle lNewTree    = castHandleT<GP::Tree>(lTreeAlloc->allocate());
	lNewTree->setPrimitiveSetIndex(lActualTree->getPrimitiveSetIndex());
	lNewTree->setNumberArguments(lActualTree->getNumberArguments());
	unsigned int lChoosenNodeSubTreeSize = (*lActualTree)[lChoosenNode].mSubTreeSize;
	lNewTree->insert(lNewTree->end(), lActualTree->begin(), lActualTree->begin()+lChoosenNode);
	lContext.setGenotypeIndex(lChoosenTree);
	lContext.setGenotypeHandle(lActualTree);
	lContext.emptyCallStack();
	lActualTree->setContextToNode(lChoosenNode, lContext);
	lContext.popCallStack();
	const unsigned int lMaxSubTreeDepth =
	    minOf<unsigned int>(lMaxTreeDepth - lContext.getCallStackSize(), lMaxRegenerationDepth);
	lIndividual[lChoosenTree] = lNewTree;
	lContext.setGenotypeHandle(lNewTree);

	unsigned int lAttempt=0;
	for(; lAttempt < mNumberAttempts->getWrappedValue(); lAttempt++) {
		if(mInitOp->initTree(*lNewTree, 1, lMaxSubTreeDepth, lContext) != 0) break;
	}
	if(lAttempt == mNumberAttempts->getWrappedValue()) {
		lIndividual[lChoosenTree] = lActualTree;
		lContext.setGenotypeIndex(lOldGenotypeIndex);
		lContext.setGenotypeHandle(lOldGenotypeHandle);
		Beagle_LogVerboseM(
		    ioContext.getSystem().getLogger(),
		    "Unable to GP standard mutate the individual"
		);
		return false;
	}

	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    std::string("GP standard mutate the ")+uint2ordinal(lChoosenNode+1)+
	    std::string(" node of the ")+uint2ordinal(lChoosenTree+1)+
	    std::string(" tree with max depth ")+uint2str(lMaxSubTreeDepth)
	);

	lNewTree->insert(lNewTree->end(),
	                 lActualTree->begin()+lChoosenNode+lChoosenNodeSubTreeSize,
	                 lActualTree->end());
	unsigned int lDiffSize =
	    (*lActualTree)[lChoosenNode].mSubTreeSize - (*lNewTree)[lChoosenNode].mSubTreeSize;
	for(unsigned int l=0; l<lContext.getCallStackSize(); l++) {
		(*lNewTree)[lContext.getCallStackElement(l)].mSubTreeSize -= lDiffSize;
	}

	lContext.setGenotypeIndex(lOldGenotypeIndex);
	lContext.setGenotypeHandle(lOldGenotypeHandle);

	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "Individual after GP standard mutation"
	);
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    ioIndividual
	);

	return true;
//.........这里部分代码省略.........
开发者ID:GhostGambler,项目名称:beagle,代码行数:101,代码来源:MutationStandardConstrainedOp.cpp

示例11: lArrayA

/*!
 *  \brief Evaluate the fitness of the given individual.
 *  \param inIndividual Current individual to evaluate.
 *  \param ioContext Evolutionary context.
 *  \return Handle to the fitness value of the individual.
 */
Beagle::Fitness::Handle AnalogFilterParameterEvalOp::evaluate(Beagle::Individual& inIndividual, Beagle::Context& ioContext) {
    Beagle_AssertM(inIndividual.size() == 1);

    Beagle_LogVerboseM(
        ioContext.getSystem().getLogger(),
        "evaluation", "AnalogFilterParameterEvalOp",
        std::string("Evaluating individual: ")+
        inIndividual.serialize()
    );

    BGFitness *lFitness = new BGFitness(0);
    GrowingBondGraph::Handle lBondGraph;

    GA::FloatVector::Handle lParametersVector = castHandleT<GA::FloatVector>(inIndividual[0]);

    BGContext& lBGContext = castObjectT<BGContext&>(ioContext);

    SpeciesGA& lSpecies = castObjectT<SpeciesGA&>(ioContext.getDeme());
    RepresentantGP::Handle lIndividual = castHandleT<RepresentantGP>(lSpecies.getRepresentant());

    TreeSTag::Handle lTree = castHandleT<TreeSTag>((*lIndividual)[0]);
//	lTree->assignNewParameterVector(lParametersVector, lBGContext);
    lBondGraph = lTree->getBondGraph();
    lBondGraph->assignParameters(*lParametersVector);


    lIndividual->getFitness()->setInvalid();

    Beagle_LogDebugM(
        ioContext.getSystem().getLogger(),
        "evaluation", "AnalogFilterParameterEvalOp",
        std::string("Individual after parameter assignment: ")+
        lIndividual->serialize()
    );

    try {
        vector<double> lInitial;

        //Run the individual to create the bond graph.
//		RootReturn lResult;
//
//		lBGContext.setIndividualHandle(lIndividual);
//		lIndividual->run(lResult, lBGContext);
//		lBondGraph = lBGContext.getBondGraph();
//		lTree->setBondGraph(lBondGraph);
//
//		//Set output bond
//		Bond* lOutputBond = lBondGraph->getComponents()[lResult.getValue()-1]->getPorts()[0]->getBond();
//		lBondGraph->setOutputBonds(lOutputBond, 0);

        Beagle_LogDebugM(
            ioContext.getSystem().getLogger(),
            "evaluation", "AnalogFilterParameterEvalOp",
            std::string("Evaluating bondgrap: ")+
            lBondGraph->BondGraph::serialize()
        );
        //lBondGraph->simplify();

        //Get state equations
        lBondGraph->assignCausality();
        lBondGraph->computeStateEquation();
        PACC::Matrix lA,lB,lB2,lC,lD,lD2;
        lBondGraph->getStateMatrix(lA,lB,lB2);
        lBondGraph->getOutputMatrix(lC,lD,lD2);

        lFitness->addStateMatrix(lA);
        lFitness->addStateMatrix(lB);
        lFitness->addStateMatrix(lC);
        lFitness->addStateMatrix(lD);

        //Check to see if the system is LTI
        if(lBondGraph->hasDeferentialCausality()) {
            //lFitness->setValue(ioContext.getSystem().getRandomizer().getFloat());
            lFitness->setValue(0);
            //delete lBondGraph;
            return lFitness;
        } else {
#ifndef DEBUG_NOMATLAB
            //Evalute the response in Matlab.

            // Cast the state matrix as input data
            // The mwArray::SetData is copying in column major order and the PACC::Matrix is a row major order
            // Therefore, the matrix need to be transposed.
            PACC::Matrix lAt,lBt,lCt,lDt;
            if(!lA.empty())
                lAt = lA.transpose();
            if(!lB.empty())
                lBt = lB.transpose();
            if(!lC.empty())
                lCt = lC.transpose();
            if(!lD.empty())
                lDt = lD.transpose();

            double *lValueA = new double[lAt.size()];
//.........这里部分代码省略.........
开发者ID:ComputationalIntelligenceAndMechatronics,项目名称:HBGGP,代码行数:101,代码来源:AnalogFilterParameterEvalOp.cpp

示例12: mate

/*!
 *  \brief Mate two GP individuals for a constrained tree crossover.
 *  \param ioIndiv1   First individual to mate.
 *  \param ioContext1 Evolutionary context of the first individual.
 *  \param ioIndiv2   Second individual to mate.
 *  \param ioContext2 Evolutionary context of the second individual.
 *  \return True if the individuals are effectively mated, false if not.
 */
bool STGP::CrossoverConstrainedOp::mate(Beagle::Individual& ioIndiv1, Beagle::Context& ioContext1,
                                      Beagle::Individual& ioIndiv2, Beagle::Context& ioContext2)
{
	Beagle_StackTraceBeginM();
	// Initial parameters checks
	Beagle_AssertM(ioIndiv1.size() > 0);
	//Beagle_AssertM(ioIndiv1.size() == ioIndiv2.size());
	Beagle_ValidateParameterM(mNumberAttempts->getWrappedValue()>0,"gp.try",">0");

	// Cast method arguments.
	GP::Individual& lIndiv1   = castObjectT<GP::Individual&>(ioIndiv1);
	GP::Individual& lIndiv2   = castObjectT<GP::Individual&>(ioIndiv2);
	GP::Context&    lContext1 = castObjectT<GP::Context&>(ioContext1);
	GP::Context&    lContext2 = castObjectT<GP::Context&>(ioContext2);

	// Get parameters in local values, with the total number of nodes of an individual.
	bool             lMatingDone     = false;
	float            lDistrProba     = mDistributionProba->getWrappedValue();
	unsigned int     lMaxTreeDepth   = mMaxTreeDepth->getWrappedValue();
	GP::Tree::Handle lOldTreeHandle1 = lContext1.getGenotypeHandle();
	unsigned int     lOldTreeIndex1  = lContext1.getGenotypeIndex();
	GP::Tree::Handle lOldTreeHandle2 = lContext2.getGenotypeHandle();
	unsigned int     lOldTreeIndex2  = lContext2.getGenotypeIndex();
	unsigned int     lSizeIndiv1     = 0;
	for(unsigned int i=0; i<lIndiv1.size(); i++) lSizeIndiv1 += lIndiv1[i]->size();

	Beagle_LogDebugM(
	    ioContext1.getSystem().getLogger(),
	    "Individuals to mate (before constrained GP crossover)"
	);
	Beagle_LogDebugM(
	    ioContext1.getSystem().getLogger(),
	    lIndiv1
	);
	Beagle_LogDebugM(
	    ioContext1.getSystem().getLogger(),
	    lIndiv2
	);

	// Crossover loop. Try the given number of attempts to mate two individuals.
	for(unsigned int lAttempt=0; lAttempt < mNumberAttempts->getWrappedValue(); ++lAttempt) {

		// Choose a node in all the individual node.
		unsigned int lChoosenNode1 =
		    lContext1.getSystem().getRandomizer().rollInteger(0, lSizeIndiv1-1);

		// Get the tree in which the choosen node is. Change the global node index to the tree's index.
		unsigned int lChoosenTree1 = 0;
		for(; lChoosenTree1<lIndiv1.size(); lChoosenTree1++) {
			if(lChoosenNode1 < lIndiv1[lChoosenTree1]->size()) break;
			Beagle_AssertM(lChoosenNode1 >= lIndiv1[lChoosenTree1]->size());
			lChoosenNode1 -= lIndiv1[lChoosenTree1]->size();
		}
		Beagle_AssertM(lChoosenTree1 < lIndiv1.size());

		// Choose a type of node (branch or leaf) following the distribution probability and change the
		// node for another node of the same tree if the types mismatch.
		GP::Tree& lTree1 = *lIndiv1[lChoosenTree1];
		const unsigned int lPrimitiveSetIndex1 = lTree1.getPrimitiveSetIndex();
		if(lTree1.size() > 1) {
			bool lTypeNode1 =
			    (lContext1.getSystem().getRandomizer().rollUniform(0.0, 1.0) < lDistrProba);
			while((lTree1[lChoosenNode1].mPrimitive->getNumberArguments() != 0) != lTypeNode1) {
				lChoosenNode1 = lContext1.getSystem().getRandomizer().rollInteger(0, lTree1.size()-1);
			}
		}

		// Choose type of node (branch or leaf) for the second node.
		const bool lTypeNode2 =
		    (lContext2.getSystem().getRandomizer().rollUniform(0.0, 1.0) < lDistrProba);

		// Compute max depth allowable.
		lTree1.setContextToNode(lChoosenNode1, lContext1);
		const unsigned int lTmpMaxDepth1 = lMaxTreeDepth - lContext1.getCallStackSize();
		const unsigned int lTmpMaxDepth2 = lMaxTreeDepth - lTree1.getTreeDepth(lChoosenNode1);
		const unsigned int lMaxDepthTree2 = minOf(lTmpMaxDepth1, lTmpMaxDepth2);

		// Select a node in second individual for the crossover.
		unsigned int lChoosenTree2=0;
		unsigned int lChoosenNode2=0;

#ifdef BEAGLE_HAVE_RTTI
		const std::type_info* lDesiredType = lTree1[lChoosenNode1].mPrimitive->getReturnType(lContext1);
		bool lGoodSelect = selectNodeToMateWithType(lChoosenTree2,
		                   lChoosenNode2,
		                   lTypeNode2,
		                   lDesiredType,
		                   lPrimitiveSetIndex1,
		                   lMaxDepthTree2,
		                   UINT_MAX,
		                   lIndiv2,
		                   lContext2);
//.........这里部分代码省略.........
开发者ID:GhostGambler,项目名称:beagle,代码行数:101,代码来源:CrossoverConstrainedOp.cpp

示例13:

/*!
 *  \brief Insert mutate a GP individual.
 *  \param ioIndividual GP individual to mutate.
 *  \param ioContext Context of the evolution.
 *  \return True if the individual is effectively mutated, false if not.
 */
bool GP::MutationInsertConstrainedOp::mutate(Beagle::Individual& ioIndividual, Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();

	Beagle_LogDetailedM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
	    std::string("Mutating individual with GP::MutationInsertConstrainedOp")
	);

	GP::Individual& lIndividual = castObjectT<GP::Individual&>(ioIndividual);
	GP::Context& lContext = castObjectT<GP::Context&>(ioContext);
	const unsigned int lMaxAttempts = mNumberAttempts->getWrappedValue();
	const unsigned int lMaxTreeDepth = mMaxTreeDepth->getWrappedValue();

	const Factory& lFactory = ioContext.getSystem().getFactory();
	GP::Tree::Alloc::Handle lTreeAlloc =
		castHandleT<GP::Tree::Alloc>(lFactory.getConceptAllocator("Genotype"));

	// Store original context values
	const unsigned int lOldGenotypeIndex = lContext.getGenotypeIndex();
	const GP::Tree::Handle lOldGenotypeHandle = lContext.getGenotypeHandle();

	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
	    "Individual before constrained GP insert mutation"
	);
	Beagle_LogObjectDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
	    ioIndividual
	);

	// Mutation attempts loop
	for(unsigned int i=0; i<lMaxAttempts; ++i) {

		// Choose tree and node to mutate
		const unsigned int lChosenTree = lIndividual.chooseRandomTree(lContext);
		const unsigned int lChosenNodeIndex = lIndividual.chooseRandomNode(lChosenTree, lContext);
		GP::Tree::Handle lOriginalTree = lIndividual[lChosenTree];

		// Compute depth of tree generated by mutation
		lContext.setGenotypeIndex(lChosenTree);
		lContext.setGenotypeHandle(lOriginalTree);
		lContext.emptyCallStack();
		lOriginalTree->setContextToNode(lChosenNodeIndex, lContext);
		const unsigned int lMutationDepth =
		    lContext.getCallStackSize() + lOriginalTree->getTreeDepth(lChosenNodeIndex);

		// Check that mutation will not generate a tree deeper than the maximum allowed depth
		if(lMutationDepth > lMaxTreeDepth) {
			Beagle_LogDebugM(
			    ioContext.getSystem().getLogger(),
			    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
			    std::string("Constrained insert mutation attempt failed as the generated tree will exceed ")+
			    std::string("maximum allowed tree depth")
			);
			continue;
		}

		// Create new tree
		Beagle_LogDebugM(
		    ioContext.getSystem().getLogger(),
		    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
		    std::string("Creating new tree")
		);
		GP::Tree::Handle lNewTree = castHandleT<GP::Tree>(lTreeAlloc->allocate());
		lNewTree->setPrimitiveSetIndex(lOriginalTree->getPrimitiveSetIndex());
		lNewTree->setNumberArguments(lOriginalTree->getNumberArguments());

		// Replace original tree with new tree
		lIndividual[lChosenTree] = lNewTree;
		lContext.setGenotypeHandle(lNewTree);

		// Copy unchanged part of original tree into new tree
		Beagle_LogDebugM(
		    ioContext.getSystem().getLogger(),
		    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
		    std::string("Copying unchanged part of original tree to new tree")
		);
		lNewTree->insert(lNewTree->end(),
		                 lOriginalTree->begin(),
		                 lOriginalTree->begin()+lChosenNodeIndex);
		Beagle_AssertM(lNewTree->size() == lChosenNodeIndex);

		// Generate new branch primitive to insert.
		GP::PrimitiveSet& lPrimitiveSet = lNewTree->getPrimitiveSet(lContext);
		Primitive::Handle lBranchInserted = lPrimitiveSet.select(GP::Primitive::eBranch, lContext);
		if(lBranchInserted==NULL) {
			Beagle_LogDebugM(
			    ioContext.getSystem().getLogger(),
			    "mutation", "Beagle::GP::MutationInsertConstrainedOp",
			    std::string("Constrained insert mutation attempt failed as it seems impossible ")+
//.........这里部分代码省略.........
开发者ID:splodginald,项目名称:MPI-PACC-OpenBeagle,代码行数:101,代码来源:MutationInsertConstrainedOp.cpp

示例14: mated

/*!
 *  \brief Mate two indice integer vector GA individuals for non-wrapping ordered crossover.
 *  \param ioIndiv1   First individual to mate.
 *  \param ioContext1 Evolutionary context of the first individual.
 *  \param ioIndiv2   Second individual to mate.
 *  \param ioContext2 Evolutionary context of the second individual.
 *  \return True if the individuals are effectively mated, false if not.
 */
bool Beagle::GA::CrossoverNWOXOp::mate(Beagle::Individual& ioIndiv1,
									   Beagle::Context&    ioContext1,
									   Beagle::Individual& ioIndiv2,
									   Beagle::Context&    ioContext2)
{
	Beagle_StackTraceBeginM();
	unsigned int lNbGenotypes = minOf<unsigned int>(ioIndiv1.size(), ioIndiv2.size());
	if(lNbGenotypes == 0) return false;
	
	Beagle_LogDebugM(
					 ioContext1.getSystem().getLogger(),
					 "crossover", "Beagle::GA::CrossoverNWOXOp",
					 "Individuals mated (before GA non-wrapping ordered crossover)"
					 );
	Beagle_LogObjectDebugM(
						   ioContext1.getSystem().getLogger(),
						   "crossover", "Beagle::GA::CrossoverNWOXOp",
						   ioIndiv1
						   );
	Beagle_LogObjectDebugM(
						   ioContext1.getSystem().getLogger(),
						   "crossover", "Beagle::GA::CrossoverNWOXOp",
						   ioIndiv2
						   );
	
	for(unsigned int i=0; i<lNbGenotypes; ++i) {
		GA::IntegerVector::Handle lIndividual1 = castHandleT<IntegerVector>(ioIndiv1[i]);
		GA::IntegerVector::Handle lIndividual2 = castHandleT<IntegerVector>(ioIndiv2[i]);
		
		unsigned int lSize = minOf<unsigned int>(lIndividual1->size(), lIndividual2->size());
		unsigned int a = ioContext1.getSystem().getRandomizer().rollInteger(0, lSize-1);
		unsigned int b = ioContext1.getSystem().getRandomizer().rollInteger(0, lSize-1);
		
		if(a > b){std::swap(a, b);}
		bool* lHoleSet1 = new bool[lSize];
		bool* lHoleSet2 = new bool[lSize];
		for(unsigned int j = 0; j < lSize; ++j){
			if(j < a || j > b){
				lHoleSet1[(*lIndividual2)[j]] = false;
				lHoleSet2[(*lIndividual1)[j]] = false;
			}else{
				lHoleSet1[(*lIndividual2)[j]] = true;
				lHoleSet2[(*lIndividual1)[j]] = true;
			}
		}
		std::vector<unsigned int> lChild1;
		std::vector<unsigned int> lChild2;
		for(unsigned int j = 0; j < lSize; ++j){
			if(!lHoleSet1[(*lIndividual1)[j]])
				lChild1.push_back((*lIndividual1)[j]);
			
			if(!lHoleSet2[(*lIndividual2)[j]])
				lChild2.push_back((*lIndividual2)[j]);
		}
		lChild1.insert(lChild1.begin() + a, lIndividual2->begin() + a, lIndividual2->begin() + (b + 1));
		lChild2.insert(lChild2.begin() + a, lIndividual1->begin() + a, lIndividual1->begin() + (b + 1));
		// Transfer the child in the ouput individuals
		for(unsigned int j = 0; j < lSize; ++j){
			(*lIndividual1)[j] = lChild1[j];
			(*lIndividual2)[j] = lChild2[j];
		}
		
		delete[] lHoleSet1;
		delete[] lHoleSet2;
	}
	
	Beagle_LogDebugM(
					 ioContext1.getSystem().getLogger(),
					 "crossover", "Beagle::GA::CrossoverNWOXOp",
					 "Individuals mated (after GA non-wrapping ordered crossover)"
					 );
	Beagle_LogObjectDebugM(
						   ioContext1.getSystem().getLogger(),
						   "crossover",
						   "Beagle::GA::CrossoverNWOXOp",
						   ioIndiv1
						   );
	Beagle_LogObjectDebugM(
						   ioContext1.getSystem().getLogger(),
						   "crossover",
						   "Beagle::GA::CrossoverNWOXOp",
						   ioIndiv2
						   );
	
	return true;
	Beagle_StackTraceEndM("bool GA::CrossoverNWOXOp::mate(Individual& ioIndiv1, Context& ioContext1, Individual& ioIndiv2, Context& ioContext2)");
}
开发者ID:splodginald,项目名称:MPI-PACC-OpenBeagle,代码行数:95,代码来源:CrossoverNWOXOp.cpp

示例15:

bool Beagle::GP::MutationEphemeralOpT<T>::mutate(Beagle::Individual& ioIndividual,
        Beagle::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	Beagle_LogDetailedM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationEphemeralOpT",
	    std::string("Mutating ")+uint2ordinal(ioContext.getGenotypeIndex()+1)+
	    std::string(" individual with GP::MutationEphemeralOpT")
	);

	GP::Individual& lIndividual = castObjectT<GP::Individual&>(ioIndividual);
	GP::Context& lContext = castObjectT<GP::Context&>(ioContext);

	// Get index of potential primitives with parameters that can be selected for mutation.
	std::vector< std::pair<unsigned int,unsigned int> > lPotentialParam;
	for(unsigned int i=0; i<lIndividual.size(); ++i) {
		GP::Tree& lTree = *lIndividual[i];
		for(unsigned int j=0; j<lTree.size(); ++j) {
			if(lTree[j].mPrimitive->getName() == *mEphemeralName) {
				lPotentialParam.push_back(std::make_pair(i,j));
			}
		}
	}

	// Return if there is not potential parameters.
	if(lPotentialParam.empty()) return false;

	// Mutating a primitive
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationEphemeralOpT",
	    "Individual before GP parameters mutation"
	);
	Beagle_LogObjectDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationEphemeralOpT",
	    ioIndividual
	);

	// Store original context values
	unsigned int lOldGenotypeIndex = lContext.getGenotypeIndex();
	GP::Tree::Handle lOldGenotypeHandle = lContext.getGenotypeHandle();

	// Get reference to primitive to mutate and other objects.
	const unsigned int lSelectedParam =
	    lContext.getSystem().getRandomizer().rollInteger(0,lPotentialParam.size()-1);
	GP::Tree::Handle lSelectedTree = lIndividual[lPotentialParam[lSelectedParam].first];
	lContext.setGenotypeIndex(lPotentialParam[lSelectedParam].first);
	lContext.setGenotypeHandle(lSelectedTree);
	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationEphemeralOpT",
	    std::string("Mutating the parameter of the ")+
	    uint2ordinal(lPotentialParam[lSelectedParam].second+1)+
	    std::string(" node in the ")+uint2ordinal(lPotentialParam[lSelectedParam].first+1)+
	    std::string(" tree")
	);

	// Mutate parameter value.
	GP::Primitive::Handle lSelectedPrimit =
	    (*lSelectedTree)[lPotentialParam[lSelectedParam].second].mPrimitive;
	typename GP::EphemeralT<T>::Handle lSelectedEphemeral =
	    castHandleT<typename GP::EphemeralT<T> >(lSelectedPrimit);
	GP::Primitive::Handle lGeneratedPrimit =
	    lSelectedEphemeral->generate(mEphemeralName->getWrappedValue(), lContext);
	(*lSelectedTree)[lPotentialParam[lSelectedParam].second].mPrimitive = lGeneratedPrimit;

	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    "mutation", "Beagle::GP::MutationEphemeralOpT",
	    std::string("Changing the ephemeral from ")+lSelectedPrimit->serialize()+
	    std::string(" to ")+lGeneratedPrimit->serialize()
	);

	// Restore original context values
	lContext.setGenotypeIndex(lOldGenotypeIndex);
	lContext.setGenotypeHandle(lOldGenotypeHandle);

	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationEphemeralOpT",
	    "Individual after GP parameters mutation"
	);
	Beagle_LogObjectDebugM(
	    ioContext.getSystem().getLogger(),
	    "mutation",
	    "Beagle::GP::MutationEphemeralOpT",
	    ioIndividual
	);

	return true;
	Beagle_StackTraceEndM("bool GP::MutationEphemeralOpT<T>::mutate(Individual& ioIndividual, Context& ioContext)");
}
开发者ID:splodginald,项目名称:MPI-PACC-OpenBeagle,代码行数:97,代码来源:MutationEphemeralOpT.hpp


注:本文中的beagle::Context类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。