예제 #1
0
/*!
 *  \brief Generate a new ADF primitive from the given specifications.
 *  \param inIndex Tree index for which the primitive is created.
 *  \param inName Name of the primitive generated.
 *  \param inArgsName Name of the arguments associated to the invoker created.
 *  \param ioContext Evolutionary context.
 */
GP::Invoker::Handle GP::ADF::generateInvoker(unsigned int inIndex,
        std::string inName,
        std::string inArgsName,
        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	if(inIndex == UINT_MAX) {
		Beagle_LogDebugM(
		    ioContext.getSystem().getLogger(),
		    "primitive selection","Beagle::GP::ADF::generateInvoker",
		    "Generated ADF with UINT_MAX"
		);

		return new GP::ADF(UINT_MAX, UINT_MAX, inName, inArgsName);
	} else {
		GP::Tree::Handle lTree = ioContext.getIndividual()[inIndex];

		Beagle_LogDebugM(
		    ioContext.getSystem().getLogger(),
		    "primitive selection","Beagle::GP::ADF::generateInvoker",
		    std::string("Generated ADF with index ")+uint2str(inIndex)+" ("+uint2str(lTree->getNumberArguments())+" args)"
		);

		return new GP::ADF(inIndex, lTree->getNumberArguments(), inName, inArgsName);
	}
	Beagle_StackTraceEndM("GP::Invoker::Handle GP::ADF::generateInvoker(unsigned int inIndex, string inName, string inArgsName, GP::Context& ioContext) const");
}
void TreeSTag::removeNOP(Individual& inIndividual, GP::Context& ioContext) {
//	Beagle_LogDebugM(
//					 ioContext.getSystem().getLogger(),
//					 "individual", "TreeSTag",
//					 std::string("Individual before NOP removal: ")+inIndividual.serialize()
//					 );
	
	
	TreeSTag::Handle lTree = castHandleT<TreeSTag>((inIndividual)[0]);
	GP::Individual& lIndividual = castObjectT<GP::Individual&>(inIndividual);
	
	GP::Individual::Handle lOldIndividualHandle = ioContext.getIndividualHandle();
	unsigned int lOldGenotypeIndex = ioContext.getGenotypeIndex();
	GP::Tree::Handle lOldGenotypeHandle = ioContext.getGenotypeHandle();	
	
	ioContext.setIndividualHandle(&lIndividual);
	ioContext.setGenotypeIndex(0);
	ioContext.setGenotypeHandle(lIndividual[0]);
	
	ioContext.getCallStack().clear();
	removeNOPLoop(0,ioContext);
	
	ioContext.setIndividualHandle(lOldIndividualHandle);
	ioContext.setGenotypeIndex(lOldGenotypeIndex);
	ioContext.setGenotypeHandle(lOldGenotypeHandle);
	
//	Beagle_LogDebugM(
//					 ioContext.getSystem().getLogger(),
//					 "individual", "TreeSTag",
//					 std::string("Individual after NOP removal: ")+inIndividual.serialize()
//					 );
}
예제 #3
0
/*!
 *  \brief  Exchange two GP trees on given points.
 *  \param  ioTree1 First tree to mate.
 *  \param  inNode1 Node index of the swap subtree first point.
 *  \param  ioContext1 Evolutionary context relatively to the first tree.
 *  \param  ioTree2 Second tree to mate.
 *  \param  inNode2 Node index of the swap subtree second point.
 *  \param  ioContext2 Evolutionary context relatively to the second tree.
 */
void GP::MutationSwapSubtreeOp::exchangeSubTrees(GP::Tree& ioTree1,
        unsigned int inNode1,
        GP::Context& ioContext1,
        GP::Tree& ioTree2,
        unsigned int inNode2,
        GP::Context& ioContext2)
{
	Beagle_StackTraceBeginM();
	Beagle_AssertM(&ioTree1 != &ioTree2);
	unsigned int lSwapSize1 = ioTree1[inNode1].mSubTreeSize;
	unsigned int lSwapSize2 = ioTree2[inNode2].mSubTreeSize;
	if(lSwapSize1 <= lSwapSize2) {
		std::swap_ranges(ioTree1.begin()+inNode1, ioTree1.begin()+inNode1+lSwapSize1, ioTree2.begin()+inNode2);
		ioTree1.insert(ioTree1.begin()+inNode1+lSwapSize1,
		               ioTree2.begin()+inNode2+lSwapSize1,
		               ioTree2.begin()+inNode2+lSwapSize2);
		ioTree2.erase(ioTree2.begin()+inNode2+lSwapSize1, ioTree2.begin()+inNode2+lSwapSize2);
	} else {
		std::swap_ranges(ioTree1.begin()+inNode1, ioTree1.begin()+inNode1+lSwapSize2, ioTree2.begin()+inNode2);
		ioTree2.insert(ioTree2.begin()+inNode2+lSwapSize2,
		               ioTree1.begin()+inNode1+lSwapSize2,
		               ioTree1.begin()+inNode1+lSwapSize1);
		ioTree1.erase(ioTree1.begin()+inNode1+lSwapSize2, ioTree1.begin()+inNode1+lSwapSize1);
	}
	int lDiffSize = lSwapSize1 - lSwapSize2;
	for(unsigned int i=0; i<(ioContext1.getCallStackSize()-1); i++)
		ioTree1[ioContext1.getCallStackElement(i)].mSubTreeSize -= lDiffSize;
	for(unsigned int j=0; j<(ioContext2.getCallStackSize()-1); j++)
		ioTree2[ioContext2.getCallStackElement(j)].mSubTreeSize += lDiffSize;
	Beagle_StackTraceEndM();
}
예제 #4
0
/*!
 *  \brief Set the value of the named GP primitive of the primitive sets.
 *  \param inName Name of the variable to set.
 *  \param inValue Value of the primitive.
 *  \param ioContext Context of the evaluation.
 *  \throw Beagle::RunTimeException If the named primitive is not found in any sets.
 */
void Coev::GPEvaluationOp::setValue(std::string inName,
                                    const Object& inValue,
                                    GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	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");
	}
	bool lValueFound = false;
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    std::string("Setting the primitives named '")+inName+
	    std::string("' to the value: ")+inValue.serialize()
	);
	for(unsigned int i=0; i<lSuperSet->size(); i++) {
		GP::Primitive::Handle lPrimitive = (*lSuperSet)[i]->getPrimitiveByName(inName);
		if(!lPrimitive) continue;
		lValueFound = true;
		lPrimitive->setValue(inValue);
	}
	if(lValueFound == false) {
		std::string lMessage = "The primitive named '";
		lMessage += inName;
		lMessage += "' was not found in any ";
		lMessage += "of the primitive sets. Maybe the primitive was not properly inserted ";
		lMessage += "or the name is mispelled.";
		throw Beagle_RunTimeExceptionM(lMessage);
	}
	Beagle_StackTraceEndM();
}
예제 #5
0
/*!
 *  \brief Get reference the tree to invoke.
 *  \param ioContext Evolutionary context.
 *  \return Handle to the invoked tree.
 */
GP::Tree::Handle GP::ADF::getInvokedTree(GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	Beagle_AssertM(mIndex < ioContext.getIndividual().size());
	return ioContext.getIndividual()[mIndex];
	Beagle_StackTraceEndM("GP::Tree::Handle GP::ADF::getInvokedTree(GP::Context& ioContext) const");
}
/*!
 *  \brief Initialize a tree.
 *  \param outTree Tree to initialize.
 *  \param inMinDepth Minimum depth of to make tree.
 *  \param inMaxDepth Maximum depth of to make tree.
 *  \param ioContext Evolution context.
 *  \return Size of newly initialized tree.
 */
unsigned int GP::InitGrowOp::initTree(GP::Tree& outTree,
                                      unsigned int inMinDepth,
                                      unsigned int inMaxDepth,
                                      GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();

	if (mKozaGrow->getWrappedValue()) {
		Beagle_LogVerboseM(
		    ioContext.getSystem().getLogger(),
		    "initialization", "Beagle::GP::InitGrowConstrainedOp",
		    "Setting the minimum depth to 2 (as per 'gp.init.kozagrow')"
		);
		inMinDepth=2;
	}

	Beagle_AssertM(inMaxDepth >= inMinDepth);
	Beagle_AssertM(inMinDepth>0);

	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    "initialization", "Beagle::GP::InitGrowOp",
	    std::string("Using the \'grow\' method (with maximum depth ")+uint2str(inMaxDepth)+
	    std::string(" and minimum depth ")+uint2str(inMinDepth)+std::string(") to initialize the ")+
	    uint2ordinal(ioContext.getGenotypeIndex()+1)+std::string(" tree")
	);

	return initSubTreeGrow(outTree, inMinDepth, inMaxDepth, ioContext);
	Beagle_StackTraceEndM("unsigned int GP::InitGrowOp::initTree(GP::Tree &outTree, unsigned int inMinDepth, unsigned int inMaxDepth, GP::Context& ioContext) const");
}
/*!
 *  \brief Initialize a constrained GP tree of a specified depth using the "full" approach.
 *  \param outTree Tree to initialize.
 *  \param inMinDepth Minimum depth to make tree.
 *  \param inMaxDepth Maximum depth to make tree.
 *  \param ioContext Evolutionary context.
 */
unsigned int GP::InitFullConstrainedOp::initTree(GP::Tree& outTree,
        unsigned int inMinDepth,
        unsigned int inMaxDepth,
        GP::Context &ioContext) const
{
	Beagle_StackTraceBeginM();

	const unsigned int lDepth = inMaxDepth;
	Beagle_AssertM(lDepth>0);

	Beagle_LogVerboseM(
	    ioContext.getSystem().getLogger(),
	    "initialization", "Beagle::GP::InitFullConstrainedOp",
	    std::string("Using the constrained \'full\' method (with depth ")+
	    uint2str(lDepth)+std::string(") to initialize the ")+
	    uint2ordinal(ioContext.getGenotypeIndex()+1)+std::string(" tree.")
	);

	unsigned int lSubTreeSize;
	do {
		lSubTreeSize = initConstrainedSubTreeFull(outTree, lDepth, ioContext);
	} while (lSubTreeSize == 0);
	return lSubTreeSize;
	Beagle_StackTraceEndM("unsigned int GP::InitFullConstrainedOp::initTree(GP::Tree& outTree, unsigned int inMinDepth, unsigned int inMaxDepth, GP::Context &ioContext) const");
}
예제 #8
0
/*!
 *  \brief Evaluate the individual fitness for the spambase problem.
 *  \param inIndividual Individual to evaluate.
 *  \param ioContext Evolutionary context.
 *  \return Handle to the fitness measure,
 */
Fitness::Handle SpambaseEvalOp::evaluate(GP::Individual& inIndividual, GP::Context& ioContext)
{
	// Get reference to data set
	DataSetClassification::Handle lDataSet =
	    castHandleT<DataSetClassification>(ioContext.getSystem().getComponent("DataSet"));
	if(lDataSet == NULL) {
		throw Beagle_RunTimeExceptionM("Data set is not present in the system, could not proceed further!");
	}

	// Generate indices used as data subset for fitness evaluation
	std::vector<unsigned int> lSubSet(lDataSet->size());
	for(unsigned int i=0; i<lSubSet.size(); ++i) lSubSet[i] = i;
	std::random_shuffle(lSubSet.begin(), lSubSet.end(),
	                    ioContext.getSystem().getRandomizer());
	if(Spambase_TestSize < lSubSet.size()) {
		lSubSet.resize(Spambase_TestSize);
	}

	// Evaluate sampled test cases
	unsigned int lCorrectCount = 0;
	for(unsigned int i=0; i<Spambase_TestSize; ++i) {
		const bool lPositiveID = ((*lDataSet)[lSubSet[i]].first == 1);
		const Beagle::Vector& lData = (*lDataSet)[lSubSet[i]].second;
		for(unsigned int j=0; j<lData.size(); ++j) {
			std::ostringstream lOSS;
			lOSS << "IN" << j;
			setValue(lOSS.str(), Double(lData[j]), ioContext);
		}
		Bool lResult;
		inIndividual.run(lResult, ioContext);
		if(lResult.getWrappedValue() == lPositiveID) ++lCorrectCount;
	}
	double lFitness = double(lCorrectCount) / Spambase_TestSize;
	return new EC::FitnessSimple(lFitness);
}
void TreeSTag::removeNOPLoop(unsigned int inN, GP::Context& ioContext) {
	GP::Tree& lActualTree = ioContext.getGenotype();
	
	if(lActualTree[inN].mPrimitive->getName() == "NOP") {
		//Decrease the subtree size of the call stack
		for(unsigned i = 0; i < ioContext.getCallStackSize(); ++i) {
			lActualTree[ioContext.getCallStack()[i]].mSubTreeSize -= 1;
		}
		
		//Delete the primitive from the tree
		std::vector< GP::Node,BEAGLE_STLALLOCATOR<GP::Node> >::iterator lPrimitiveIter = lActualTree.begin();
		lPrimitiveIter += inN;
		lActualTree.erase(lPrimitiveIter);

		
//		cout << "Callstack: " << ioContext.getCallStack()[0];
//		for(unsigned int i = 1; i < ioContext.getCallStackSize() ; ++i) {
//			cout << ", " << ioContext.getCallStack()[0];
//		} cout << endl;
//		for(unsigned int i = 0; i < lActualTree.size(); ++i) {
//			cout << i << " : " << lActualTree[i].mPrimitive->getName() << " : " << lActualTree[i].mSubTreeSize << endl;
//		}
		
		removeNOPLoop(inN, ioContext);
		
	} else {
		//Parse all arguments
		ioContext.pushCallStack(inN);
		for(unsigned int i = 0; i < lActualTree[inN].mPrimitive->getNumberArguments(); ++i) {
			removeNOPLoop(lActualTree[inN].mPrimitive->getChildrenNodeIndex(i,ioContext), ioContext);
		}
		ioContext.popCallStack();
	}
}
예제 #10
0
/*!
 *  \brief Return indices of the trees that can be invoked by the module.
 *  \param outCandidates Indices of tree that can be selected as invokable in the actual context.
 *  \param inNumberArguments Number of arguments for which the selection is desired.
 *  \param ioContext Evolutionary context.
 */
void GP::Module::getCandidatesToInvoke(std::vector<unsigned int>& outCandidates,
                                       unsigned int inNumberArguments,
                                       GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	outCandidates.clear();
	for(unsigned int i=0; i<ioContext.getCallStackSize(); ++i) {
		if(ioContext.getGenotype()[ioContext.getCallStackElement(i)].mPrimitive->getName() == getName())
			return;
	}
	Component::Handle lComponent = ioContext.getSystem().getComponent("ModuleVector");
	GP::ModuleVectorComponent::Handle lModVector =
	    castHandleT<GP::ModuleVectorComponent>(lComponent);
	if(lModVector==NULL) {
		throw Beagle_RunTimeExceptionM(std::string("GP system is not configured with a module vector. ")+
		                               std::string("Consider adding a GP::ModuleVectorComponent object to the system."));
	}
	for(unsigned int i=0; i<lModVector->size(); ++i) {
		if((*lModVector)[i]==NULL) continue;
		const unsigned int lNbArgsTree = (*lModVector)[i]->getNumberArguments();
		if(inNumberArguments == GP::Primitive::eAny) outCandidates.push_back(i);
		else if((inNumberArguments==GP::Primitive::eBranch) && (lNbArgsTree>0))
			outCandidates.push_back(i);
		else if(inNumberArguments == lNbArgsTree) outCandidates.push_back(i);
	}
	Beagle_StackTraceEndM();
}
예제 #11
0
/*!
 *  \brief Validate the arguments position in the tree.
 *  \param ioContext Evolutionary context.
 *  \return True if the argument is correctly positioned, false if not.
 *  \throw Beagle::AssertException If the context is in a bad state.
 */
bool GP::Argument::validate(GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	if(GP::Primitive::validate(ioContext) == false) return false;
	if(ioContext.getGenotypeIndex() == 0) return false;
	if(mIndex >= ioContext.getGenotype().getNumberArguments()) return false;
	return true;
	Beagle_StackTraceEndM();
}
예제 #12
0
/*!
 *  \brief  Generate a new random ephemeral Double constant between [-1,1].
 *  \param  inName Name of the constant.
 *  \param  ioContext Context to use to generate the value.
 *  \return Handle to the ephemeral Double constant generated.
 */
GP::Primitive::Handle EphemeralDoubleWide::generate(Beagle::string inName, GP::Context& ioContext)
{
  Beagle_StackTraceBeginM();
  double factor = ioContext.getSystem().getRandomizer().rollUniform(-1.,1.);
  double exp = ioContext.getSystem().getRandomizer().rollUniform(-4.,3.);
  Double::Handle lValue = new Double(factor*pow(10, exp));
  return new EphemeralDoubleWide(lValue, inName);
  Beagle_StackTraceEndM("GP::Primitive::Handle SinsGP::EphemeralDoubleWide::generate(string inName, GP::Context& ioContext)");
}
예제 #13
0
/*!
 *  \brief Return a reference to the actual argument.
 *  \param inNumberArguments
 *  \param ioContext Evolutionary context.
 *  \return Handle to argument.
 */
GP::Primitive::Handle GP::Argument::giveReference(unsigned int inNumberArguments, GP::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	if(mIndex!=eGenerator) return this;
	const unsigned int lTreeNbArgs = ioContext.getGenotype().getNumberArguments();
	Beagle_AssertM(lTreeNbArgs > 0);
	const unsigned int lGenIndex =
	    ioContext.getSystem().getRandomizer().rollInteger(0,(lTreeNbArgs-1));
	return generateArgument(lGenIndex);
	Beagle_StackTraceEndM();
}
예제 #14
0
/*!
 *  \brief Return selection weight of the argument primitive.
 *  \param inNumberArguments Number of arguments to get weight for.
 *  \param ioContext Evolutionary context.
 *  \return Selection weight for the given number of arguments.
 */
double GP::Argument::getSelectionWeight(unsigned int inNumberArguments,
                                        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	if(ioContext.getGenotypeIndex() == 0) return 0.0;
	if((inNumberArguments==0) || (inNumberArguments==GP::Primitive::eAny)) {
		const unsigned int lTreeNbArgs = ioContext.getGenotype().getNumberArguments();
		if(lTreeNbArgs > 0) return double(lTreeNbArgs);
	}
	return 0.0;
	Beagle_StackTraceEndM();
}
예제 #15
0
/*!
 *  \brief Initialize a GP sub-tree of a specified depth using the "grow" approach.
 *  \param ioTree Tree containing the sub-tree to initialize.
 *  \param inMinDepth Minimal depth of the sub-tree to initialize.
 *  \param inMaxDepth Maximal depth of the sub-tree to initialize.
 *  \param ioContext Evolutionary context.
 *  \return Generated sub-tree size.
 */
unsigned int GP::InitGrowOp::initSubTreeGrow(GP::Tree& ioTree,
        unsigned int inMinDepth,
        unsigned int inMaxDepth,
        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	Beagle_AssertM(inMaxDepth >= inMinDepth);
	Beagle_AssertM(inMinDepth>0);
	GP::PrimitiveSet& lPrimitSet = ioTree.getPrimitiveSet(ioContext);
	GP::Primitive::Handle lPrimit = NULL;
	if(inMinDepth > 1) {
		lPrimit = lPrimitSet.select(GP::Primitive::eBranch, ioContext);
		if(!lPrimit) {
			std::string lMessage = "There is no branch (primitive with arguments) in the ";
			lMessage += uint2ordinal(ioContext.getGenotypeIndex()+1);
			lMessage += " primitive set!";
			throw Beagle_RunTimeExceptionM(lMessage);
		}
		lPrimit = lPrimit->giveReference(GP::Primitive::eBranch, ioContext);
	} else if(inMaxDepth == 1) {
		lPrimit = lPrimitSet.select(GP::Primitive::eTerminal, ioContext);
		if(!lPrimit) {
			std::string lMessage = "There is no leaf (primitive without argument) in the ";
			lMessage += uint2ordinal(ioContext.getGenotypeIndex()+1);
			lMessage += " primitive set!";
			throw Beagle_RunTimeExceptionM(lMessage);
		}
		lPrimit = lPrimit->giveReference(GP::Primitive::eTerminal, ioContext);
	} else {
		lPrimit = lPrimitSet.select(GP::Primitive::eAny, ioContext);
		if(!lPrimit) {
			std::string lMessage = "There is no primitive in the ";
			lMessage += uint2ordinal(ioContext.getGenotypeIndex()+1);
			lMessage += " primitive set!";
			throw Beagle_RunTimeExceptionM(lMessage);
		}
		lPrimit = lPrimit->giveReference(GP::Primitive::eAny, ioContext);
	}
	unsigned int lNodeIndex = ioTree.size();
	ioTree.push_back(GP::Node(lPrimit, 1));
	unsigned int lSubTreeSize = 1;
	unsigned int lMinDepth = (inMinDepth > 1) ? (inMinDepth-1) : 1;
	for(unsigned int i=0; i<ioTree[lNodeIndex].mPrimitive->getNumberArguments(); i++) {
		lSubTreeSize += initSubTreeGrow(ioTree, lMinDepth, inMaxDepth-1, ioContext);
	}
	ioTree[lNodeIndex].mSubTreeSize = lSubTreeSize;
	return lSubTreeSize;
	Beagle_StackTraceEndM("unsigned int GP::InitGrowOp::initSubTreeGrow(GP::Tree& ioTree, unsigned int inMinDepth, unsigned int inMaxDepth, GP::Context& ioContext) const");
}
예제 #16
0
/*!
 *  \brief Execute argument primitive.
 *  \param outResult Result containing value of argument.
 *  \param ioContext Evolutionary context.
 */
void GP::Argument::execute(GP::Datum& outResult, GP::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "evaluation", "Beagle::GP::Argument",
	    std::string("Executing the ")+uint2ordinal(mIndex+1)+" argument"
	);
	switch (mSharedData->mEvalMode) {
	case ePreCompute:
		// The result of evaluating the argument has already been calculated.
		Beagle_AssertM(mIndex < mSharedData->mCaches.back()->size());
		mSharedData->mTypeAllocator->copy(outResult, *(*mSharedData->mCaches.back())[mIndex]);
		break;
	case eJustInTime:
		// Evaluate the argument because we're not caching them.
		forceEvaluation(outResult, ioContext);
		break;
	case eCaching:
		// Check first if the argument has been evaluated (i.e. is it in the cache?)
		// If it has been evaluated then get it from the cache; otherwise evaluate it.
		Beagle_AssertM(mIndex < mSharedData->mCaches.back()->size());
		if((*mSharedData->mCaches.back())[mIndex]!=NULL) {
			Beagle_LogDebugM(
			    ioContext.getSystem().getLogger(),
			    "evaluation", "Beagle::GP::Argument",
			    "Getting result from the cache"
			);
			mSharedData->mTypeAllocator->copy(outResult, *(*mSharedData->mCaches.back())[mIndex]);
		} else {
			Object::Bag::Handle lCurrentCache = mSharedData->mCaches.back();
			mSharedData->mCaches.pop_back();
			forceEvaluation(outResult, ioContext);
			mSharedData->mCaches.push_back(lCurrentCache);
			(*lCurrentCache)[mIndex] = mSharedData->mTypeAllocator->clone(outResult);
			Beagle_LogDebugM(
			    ioContext.getSystem().getLogger(),
			    "evaluation", "Beagle::GP::Argument",
			    "Result added to cache"
			);
		}
		break;
	default:
		throw Beagle_InternalExceptionM(std::string("Undefined evaluation mode (")+
		                                uint2str(mSharedData->mEvalMode)+std::string(") for arguments!"));
	}

	Beagle_StackTraceEndM();
}
예제 #17
0
/*!
 *  \brief Randomly select a node that takes arguments from a specific
 *    tree in the individual.
 *  \return Randomly selected tree
 */
unsigned int GP::Individual::chooseRandomNodeWithArgs(unsigned int inTree,
        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	const GP::Tree& lTree = *(operator[](inTree));
	unsigned int lSize = lTree.size();
	if (lSize < 2) {
		std::ostringstream lOSS;
		lOSS << "In GP::Individual::chooseRandomNodeWithArgs(): ";
		lOSS << "Could not choose a node with arguments because the specified tree has fewer ";
		lOSS << "than two (" << lSize << ") nodes, hence there are no such nodes";
		lOSS << " in the tree. This occurred while calling chooseRandomNodeWithArgs() with an ";
		lOSS << "inTree value of " << inTree;
		throw Beagle_RunTimeExceptionM(lOSS.str());
	}

	// Loop through the tree adding appropriate nodes into the roulette
	RouletteT<unsigned int> lRoulette;
	for (unsigned int i=0; i<lSize; i++) {
		if(lTree[i].mSubTreeSize > 1) lRoulette.insert(i);
	}

	// Select node with roulette
	Beagle_AssertM(!lRoulette.empty());
	return lRoulette.select(ioContext.getSystem().getRandomizer());
	Beagle_StackTraceEndM();
}
예제 #18
0
/*!
 *  \brief Randomly select a node from a specific tree in the individual.
 *  \return Randomly selected tree
 *
 *  Each node has an equal probability of being selected.
 */
unsigned int GP::Individual::chooseRandomNode(unsigned int inTree, GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	Beagle_AssertM(operator[](inTree)->size()!=0);
	return ioContext.getSystem().getRandomizer().rollInteger(0, operator[](inTree)->size()-1);
	Beagle_StackTraceEndM();
}
예제 #19
0
/*!
 *  \brief Return indices of the trees that can be invoked by the ADF.
 *  \param outCandidates Indices of tree that can be selected as invokable in the actual context.
 *  \param inNumberArguments Number of arguments for which the selection is desired.
 *  \param ioContext Evolutionary context.
 */
void GP::ADF::getCandidatesToInvoke(std::vector<unsigned int>& outCandidates,
                                    unsigned int inNumberArguments,
                                    GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	outCandidates.clear();
	for(unsigned int i=(ioContext.getGenotypeIndex()+1); i<ioContext.getIndividual().size(); ++i) {
		GP::Tree::Handle lTree = castHandleT<GP::Tree>(ioContext.getIndividual()[i]);
		const unsigned int lNbArgsTree = lTree->getNumberArguments();
		if(inNumberArguments == GP::Primitive::eAny) outCandidates.push_back(i);
		else if((inNumberArguments == GP::Primitive::eBranch) && (lNbArgsTree>0))
			outCandidates.push_back(i);
		else if(inNumberArguments == lNbArgsTree) outCandidates.push_back(i);
	}
	Beagle_StackTraceEndM("void GP::ADF::getCandidatesToInvoke(std::vector<unsigned int>& outCandidates, unsigned int inNumberArguments, GP::Context& ioContext) const");
}
예제 #20
0
/*!
 *  \brief Invoke GP tree to execute as ADF.
 *  \param outResult Result of GP tree invocation
 *  \param ioTree Tree to invoke.
 *  \param ioContext Evolutionary context.
 */
void GP::ADF::invoke(GP::Datum& outResult, GP::Tree::Handle ioTree, GP::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	GP::Tree::Handle lOldGenotypeHandle = ioContext.getGenotypeHandle();
	unsigned int lOldGenotypeIndex = ioContext.getGenotypeIndex();
	ioContext.setGenotypeHandle(ioTree);
	ioContext.setGenotypeIndex(mIndex);
	ioContext.incrementNodesExecuted();
	ioContext.pushCallStack(0);
	(*ioTree)[0].mPrimitive->execute(outResult, ioContext);
	ioContext.popCallStack();
	ioContext.checkExecutionTime();
	ioContext.setGenotypeHandle(lOldGenotypeHandle);
	ioContext.setGenotypeIndex(lOldGenotypeIndex);
	Beagle_StackTraceEndM("void GP::ADF::invoke(GP::Datum& outResult, GP::Tree::Handle ioTree, GP::Context& ioContext)");
}
예제 #21
0
/*!
 *  \brief Validate the module position in the tree.
 *  \param ioContext Evolutionary context.
 *  \return True if the module is correctly positioned, false if not.
 *  \throw Beagle::AssertException If the context is in a bad state.
 */
bool GP::Module::validate(GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	for(unsigned int i=0; i<ioContext.getCallStackSize(); ++i) {
		if(ioContext.getGenotype()[ioContext.getCallStackElement(i)].mPrimitive->getName() == getName())
			return false;
	}
	Component::Handle lComponent = ioContext.getSystem().getComponent("ModuleVector");
	GP::ModuleVectorComponent::Handle lModVector =
	    castHandleT<GP::ModuleVectorComponent>(lComponent);
	if(lModVector==NULL) {
		throw Beagle_RunTimeExceptionM(std::string("GP system is not configured with a module vector. ")+
		                               std::string("Consider adding a GP::ModuleVectorComponent object to the system."));
	}
	Beagle_AssertM((*lModVector)[mIndex]!=NULL);
	if((*lModVector)[mIndex]->getNumberArguments() != getNumberArguments()) return false;
	return GP::Primitive::validate(ioContext);
	Beagle_StackTraceEndM();
}
예제 #22
0
/*!
 *  \brief Build a roulette of nodes that can be selected following the constraints penalties.
 *  \param ioRoulette Roulette of nodes that can be selected following the constraints given.
 *  \param inSelectABranch True if node to select must be a branch, false if it must a leaf.
 *  \param inNodeReturnType Desired return type for the nodes to be selected.
 *  \param inMaxSubTreeDepth Maximum sub tree depth allowed of the node to be selected.
 *  \param inMaxSubTreeSize Maximum sub tree size allowed of the node to be selected.
 *  \param inActualIndex Index in actual tree of the node processed.
 *  \param inTree Tree processed.
 *  \param ioContext Evolutionary context.
 *  \return Max depth of subtree processed.
 */
unsigned int STGP::CrossoverConstrainedOp::buildRouletteWithType(
    RouletteT< std::pair<unsigned int,unsigned int> >& ioRoulette,
    bool inSelectABranch,
    const std::type_info* inNodeReturnType,
    unsigned int inMaxSubTreeDepth,
    unsigned int inMaxSubTreeSize,
    unsigned int inActualIndex,
    GP::Tree& inTree,
    GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	const unsigned int lNbArgs = inTree[inActualIndex].mPrimitive->getNumberArguments();
	const unsigned int lSubTreeSize = inTree[inActualIndex].mSubTreeSize;
	const bool lGoodArity = ((inTree.size()==1) || ((lNbArgs==0) != inSelectABranch));
	ioContext.pushCallStack(inActualIndex);
	const std::type_info* lNodeType = inTree[inActualIndex].mPrimitive->getReturnType(ioContext);
	const bool lCompatibleTyping = ((inNodeReturnType==NULL) || (lNodeType==NULL) ||
	                                (inNodeReturnType==lNodeType));
	unsigned int lChildIndex = inActualIndex+1;
	unsigned int lMaxDepthDown = 0;
	for(unsigned int i=0; i<lNbArgs; ++i) {
		unsigned int lChildDepth = buildRouletteWithType(ioRoulette,
		                           inSelectABranch,
		                           inNodeReturnType,
		                           inMaxSubTreeDepth,
		                           inMaxSubTreeSize,
		                           lChildIndex,
		                           inTree,
		                           ioContext);
		lChildIndex += inTree[lChildIndex].mSubTreeSize;
		if(lChildDepth > lMaxDepthDown) lMaxDepthDown = lChildDepth;
	}
	++lMaxDepthDown;
	const unsigned int lMaxDepthUp = ioContext.getCallStackSize();
	ioContext.popCallStack();
	if(lGoodArity && lCompatibleTyping && (lSubTreeSize<=inMaxSubTreeSize) &&
	        (lMaxDepthDown<=inMaxSubTreeDepth) && (lMaxDepthUp<=inMaxSubTreeDepth)) {
		std::pair<unsigned int,unsigned int> lPair(ioContext.getGenotypeIndex(), inActualIndex);
		ioRoulette.insert(lPair, 1.0);
	}
	return lMaxDepthDown;
	Beagle_StackTraceEndM();
}
예제 #23
0
/*!
 *  \brief Initialize a tree.
 *  \param outTree Tree to initialize.
 *  \param inMinDepth Minimum depth to make tree.
 *  \param inMaxDepth Maximum depth to make tree.
 *  \param ioContext Evolution context.
 *  \return Size of newly initialized tree.
 */
unsigned int GP::InitHalfOp::initTree(GP::Tree &outTree,
                                      unsigned int inMinDepth,
                                      unsigned int inMaxDepth,
                                      GP::Context &ioContext) const
{
	Beagle_StackTraceBeginM();
	if(ioContext.getSystem().getRandomizer().rollUniform(0.0, 1.0) < 0.5)
		return mInitFullOp.initTree(outTree, inMinDepth, inMaxDepth, ioContext);
	return mInitGrowOp.initTree(outTree, inMinDepth, inMaxDepth, ioContext);
	Beagle_StackTraceEndM();
}
예제 #24
0
/*!
 *  \brief Read an argument primitive from XML subtree.
 *  \param inIter XML iterator to read primitive from.
 *  \param ioContext Evolutionary context.
 */
void GP::Argument::readWithContext(PACC::XML::ConstIterator inIter, GP::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	GP::Primitive::readWithContext(inIter, ioContext);
	std::string lIndexValue = inIter->getAttribute("id");
	if(lIndexValue.empty()==false) {
		mIndex = str2uint(lIndexValue);
		Beagle_AssertM(mIndex < ioContext.getGenotype().getNumberArguments());
	}
	Beagle_StackTraceEndM();
}
예제 #25
0
/*!
 *  \brief Randomly select a tree from the individual.
 *  \return Randomly selected tree
 *
 *  The selection is biased towards trees with a greater number of nodes
 *  (i.e. each node has an equal probability of being selected).
 */
unsigned int GP::Individual::chooseRandomTree(GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	unsigned int lChosenNode = ioContext.getSystem().getRandomizer().rollInteger(0, getTotalNodes()-1);
	unsigned int lChosenTree = 0;
	for(; (lChosenTree+1)<size(); lChosenTree++) {
		if(lChosenNode < (*this)[lChosenTree]->size()) break;
		else lChosenNode -= (*this)[lChosenTree]->size();
	}
	return lChosenTree;
	Beagle_StackTraceEndM();
}
예제 #26
0
/*!
 *  \brief Push execution context to prepare the execution of the argument.
 *  \param inNumberArguments Number of arguments of called tree.
 *  \param ioContext Evolutionary context.
 */
void GP::Argument::pushExecutionContext(unsigned int inNumberArguments, GP::Context& ioContext)
{
	Beagle_StackTraceBeginM();
	switch(mSharedData->mEvalMode) {
	case eCaching: {
		Object::Bag::Handle lNewCache = new Object::Bag(inNumberArguments, NULL);
		mSharedData->mCaches.push_back(lNewCache);
		Context::Alloc::Handle lContextAlloc =
			castHandleT<Context::Alloc>(ioContext.getSystem().getFactory().getConceptAllocator("Context"));
		GP::Context::Handle lNewEvalContext =
			castHandleT<GP::Context>(lContextAlloc->clone(ioContext));
		mSharedData->mEvalContext.push_back(lNewEvalContext);
		break;
	}
	case eJustInTime: {
		Context::Alloc::Handle lContextAlloc =
		    castHandleT<Context::Alloc>(ioContext.getSystem().getFactory().getConceptAllocator("Context"));
		GP::Context::Handle lNewEvalContext =
		    castHandleT<GP::Context>(lContextAlloc->clone(ioContext));
		mSharedData->mEvalContext.push_back(lNewEvalContext);
		break;
	}
	case ePreCompute: {
		Object::Bag::Handle lNewCache = new Object::Bag(inNumberArguments, NULL);
		lNewCache->resize(inNumberArguments);
		for(unsigned int i=0; i<inNumberArguments; ++i) {
			Object::Handle lArgI = mSharedData->mTypeAllocator->allocate();
			getArgument(i, *lArgI, ioContext);
			(*lNewCache)[i] = lArgI;
		}
		mSharedData->mCaches.push_back(lNewCache);
	}
	default: {
		throw Beagle_InternalExceptionM(std::string("Undefined evaluation mode (")+
		                                uint2str(mSharedData->mEvalMode)+std::string(") for the arguments!"));
	}
	}
	Beagle_StackTraceEndM();
}
예제 #27
0
/*!
 *  \brief Get reference the tree to invoke.
 *  \param ioContext Evolutionary context.
 *  \return Handle to the invoked tree.
 */
GP::Tree::Handle GP::Module::getInvokedTree(GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	Component::Handle lComponent = ioContext.getSystem().getComponent("ModuleVector");
	GP::ModuleVectorComponent::Handle lModVector =
	    castHandleT<GP::ModuleVectorComponent>(lComponent);
	if(lModVector==NULL) {
		throw Beagle_RunTimeExceptionM(std::string("GP system is not configured with a module vector. ")+
		                               std::string("Consider adding a GP::ModuleVectorComponent object to the system."));
	}
	Beagle_AssertM(mIndex < lModVector->size());
	Beagle_AssertM((*lModVector)[mIndex] != NULL);
	return (*lModVector)[mIndex];
	Beagle_StackTraceEndM();
}
예제 #28
0
void GP::Argument::forceEvaluation(GP::Datum& outResult, GP::Context& ioContext)
{
	Beagle_LogDebugM(
	    ioContext.getSystem().getLogger(),
	    "evaluation", "Beagle::GP::Argument",
	    std::string("Evaluating the ")+uint2ordinal(mIndex+1)+" argument"
	);

	GP::Context::Handle lActualContext = mSharedData->mEvalContext.back();
	mSharedData->mEvalContext.pop_back();
	lActualContext->setAllowedNodesExecution(ioContext.getAllowedNodesExecution());
	lActualContext->setAllowedExecutionTime(ioContext.getAllowedExecutionTime());
	lActualContext->setNodesExecutionCount(ioContext.getNodesExecutionCount());
	lActualContext->getExecutionTimer() = ioContext.getExecutionTimer();
	getArgument(mIndex, outResult, *lActualContext);
	ioContext.getExecutionTimer() = lActualContext->getExecutionTimer();
	ioContext.setNodesExecutionCount(lActualContext->getNodesExecutionCount());
	ioContext.setAllowedExecutionTime(lActualContext->getAllowedExecutionTime());
	ioContext.setAllowedNodesExecution(lActualContext->getAllowedNodesExecution());
	mSharedData->mEvalContext.push_back(lActualContext);
}
예제 #29
0
/*!
 *  \brief Randomly select a node that takes no argument from a specific
 *    tree in the individual.
 *  \return Randomly selected tree
 */
unsigned int GP::Individual::chooseRandomNodeWithoutArgs(unsigned int inTree,
        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	// Loop through the tree adding appropriate nodes into the roulette
	unsigned int lSize = operator[](inTree)->size();
	RouletteT<unsigned int> lRoulette;
	for (unsigned int i=0; i<lSize; i++) {
		if (operator[](inTree)->operator[](i).mSubTreeSize == 1) {
			lRoulette.insert(i);
		}
	}
	// Select node with roulette
	Beagle_AssertM(!lRoulette.empty());
	return lRoulette.select(ioContext.getSystem().getRandomizer());
	Beagle_StackTraceEndM();
}
예제 #30
0
/*!
 *  \brief Generate a new Module primitive from the given specifications.
 *  \param inIndex Tree index for which the primitive is created.
 *  \param inName Name of the primitive generated.
 *  \param inArgsName Name of the arguments associated to the invoker created.
 *  \param ioContext Evolutionary context.
 */
GP::Invoker::Handle GP::Module::generateInvoker(unsigned int inIndex,
        std::string inName,
        std::string inArgsName,
        GP::Context& ioContext) const
{
	Beagle_StackTraceBeginM();
	Component::Handle lComponent = ioContext.getSystem().getComponent("ModuleVector");
	GP::ModuleVectorComponent::Handle lModVector =
	    castHandleT<GP::ModuleVectorComponent>(lComponent);
	if(lModVector==NULL) {
		throw Beagle_RunTimeExceptionM(std::string("GP system is not configured with a module vector. ")+
		                               std::string("Consider adding a GP::ModuleVectorComponent object to the system."));
	}
	GP::Tree::Handle lTree = (*lModVector)[inIndex];
	Beagle_AssertM(lTree != NULL);
	return new GP::Module(inIndex, lTree->getNumberArguments(), inName, inArgsName);
	Beagle_StackTraceEndM();
}