Esempio n. 1
0
// caller must call matrix.ClearData() before calling
// FIXME: setup array of node points by walking backwards from findNode
//  then multiply in a loop
//
Bool FamilyNode::FindOffsetRecurse( const FamilyNode *findNode, Matrix &matrix, Bool local) // = FALSE)
{
  ASSERT( statePtr);

  matrix = ObjectMatrix() * matrix;

  if (this == findNode)
  {
    return TRUE;
  }

  Matrix newMatrix = matrix;

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    if (local && node->nodeType != nodeMesh && node->nodeType != nodeMeshObj)
    {
      continue;
    }

    matrix = newMatrix;

    if (node->FindOffsetRecurse( findNode, matrix, local))
    {
      return TRUE;
    }
  }
  return FALSE;
}
Esempio n. 2
0
size_t WHtreeProcesser::flattenSelection( std::list< size_t > selection, bool keepBaseNodes )
{
    if( keepBaseNodes && !m_tree.testRootBaseNodes() )
    {
        std::cerr << "WARNING@ flattenSelection: base nodes have mixed nodes and leaves, flattening will be standard " << std::endl;
        keepBaseNodes = false;
    }
    while( !selection.empty() )
    {
        size_t thisNode( selection.front() );
        selection.pop_front();
        std::vector< nodeID_t > kids( m_tree.getNode( thisNode ).getChildren() );
        for( size_t i = 0; i < kids.size(); ++i )
        {
            if( kids[i].first )
            {
                if( keepBaseNodes &&  ( m_tree.getNode( kids[i] ).getHLevel() == 1 ) )
                {
                    continue;
                }
                else
                {
                    m_tree.fetchNode( kids[i].second )->setFlag( true );
                    selection.push_back( kids[i].second );
                }
            }
        }
    }

    std::pair< size_t, size_t > pruned( m_tree.cleanup() );

    return pruned.second;
} // end "flattenSelection()" -----------------------------------------------------------------
Esempio n. 3
0
void FamilyNode::RenderColor( const Array<FamilyState> & stateArray, Color color, U32 clipFlags, U32 _controlFlags) // = clipALL, = controlDEF
{
  ASSERT( statePtr);

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    node->RenderColor( stateArray, color, clipFlags, _controlFlags);
  }
}
Esempio n. 4
0
void FamilyNode::SetWorldRecurse( const Matrix &world)
{
  CalcWorldMatrix( world);

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    node->SetWorldRecurse( WorldMatrix());
  }
}
Esempio n. 5
0
void Camera::SetWorldRecurseRender( const Matrix &world, FamilyState *stateArray)
{
  CalcWorldMatrix( world);

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    node->SetWorldRecurseRender( statePtr->WorldMatrix(), stateArray);
  }
  
  SetupMatrix();
}
Esempio n. 6
0
void FamilyNode::SetWorldRecurseRender( const Matrix &world, FamilyState *stateArray)
{
  FamilyState & state = stateArray[name.index];

  CalcWorldMatrix( world, state);

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    node->SetWorldRecurseRender( state.WorldMatrix(), stateArray);
  }
}
Esempio n. 7
0
// removes 'this' from parent leaving its children in place
//
void FamilyNode::Extract()
{
	if (parent)
	{
    // remove from parents list
    parent->children.Unlink( this);

    // add this's children to parent's list
    NList<FamilyNode>::Iterator kids(&children);
    FamilyNode *node;
    while ((node = kids++) != NULL)
    {
      children.Unlink(node);

      node->parent = parent;
      parent->children.Append(node);
    }

    // clear ourselves
		parent = NULL;
 	}
}
Esempio n. 8
0
//  if local == TRUE then find won't cross to attached objs'
//
FamilyNode * FamilyNode::Find( U32 crc, Bool local) // = FALSE)
{
  if (crc == name.crc)
  {
    return this;
  }

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    if (local && node->nodeType != nodeMesh && node->nodeType != nodeMeshObj)
    {
      continue;
    }
    if (FamilyNode *fn = node->Find( crc, local))
    {
      return fn;
    }
  }
  return FALSE;
}
Esempio n. 9
0
// static
void SkPDFPage::GeneratePageTree(const SkTDArray<SkPDFPage*>& pages,
                                 SkPDFCatalog* catalog,
                                 SkTDArray<SkPDFDict*>* pageTree,
                                 SkPDFDict** rootNode) {
    // PDF wants a tree describing all the pages in the document.  We arbitrary
    // choose 8 (kNodeSize) as the number of allowed children.  The internal
    // nodes have type "Pages" with an array of children, a parent pointer, and
    // the number of leaves below the node as "Count."  The leaves are passed
    // into the method, have type "Page" and need a parent pointer. This method
    // builds the tree bottom up, skipping internal nodes that would have only
    // one child.
    static const int kNodeSize = 8;

    SkAutoTUnref<SkPDFName> kidsName(new SkPDFName("Kids"));
    SkAutoTUnref<SkPDFName> countName(new SkPDFName("Count"));
    SkAutoTUnref<SkPDFName> parentName(new SkPDFName("Parent"));

    // curNodes takes a reference to its items, which it passes to pageTree.
    SkTDArray<SkPDFDict*> curNodes;
    curNodes.setReserve(pages.count());
    for (int i = 0; i < pages.count(); i++) {
        SkSafeRef(pages[i]);
        curNodes.push(pages[i]);
    }

    // nextRoundNodes passes its references to nodes on to curNodes.
    SkTDArray<SkPDFDict*> nextRoundNodes;
    nextRoundNodes.setReserve((pages.count() + kNodeSize - 1)/kNodeSize);

    int treeCapacity = kNodeSize;
    do {
        for (int i = 0; i < curNodes.count(); ) {
            if (i > 0 && i + 1 == curNodes.count()) {
                nextRoundNodes.push(curNodes[i]);
                break;
            }

            SkPDFDict* newNode = new SkPDFDict("Pages");
            SkAutoTUnref<SkPDFObjRef> newNodeRef(new SkPDFObjRef(newNode));

            SkAutoTUnref<SkPDFArray> kids(new SkPDFArray);
            kids->reserve(kNodeSize);

            int count = 0;
            for (; i < curNodes.count() && count < kNodeSize; i++, count++) {
                curNodes[i]->insert(parentName.get(), newNodeRef.get());
                kids->append(new SkPDFObjRef(curNodes[i]))->unref();

                // TODO(vandebo): put the objects in strict access order.
                // Probably doesn't matter because they are so small.
                if (curNodes[i] != pages[0]) {
                    pageTree->push(curNodes[i]);  // Transfer reference.
                    catalog->addObject(curNodes[i], false);
                } else {
                    SkSafeUnref(curNodes[i]);
                    catalog->addObject(curNodes[i], true);
                }
            }

            // treeCapacity is the number of leaf nodes possible for the
            // current set of subtrees being generated. (i.e. 8, 64, 512, ...).
            // It is hard to count the number of leaf nodes in the current
            // subtree. However, by construction, we know that unless it's the
            // last subtree for the current depth, the leaf count will be
            // treeCapacity, otherwise it's what ever is left over after
            // consuming treeCapacity chunks.
            int pageCount = treeCapacity;
            if (i == curNodes.count()) {
                pageCount = ((pages.count() - 1) % treeCapacity) + 1;
            }
            newNode->insert(countName.get(), new SkPDFInt(pageCount))->unref();
            newNode->insert(kidsName.get(), kids.get());
            nextRoundNodes.push(newNode);  // Transfer reference.
        }

        curNodes = nextRoundNodes;
        nextRoundNodes.rewind();
        treeCapacity *= kNodeSize;
    } while (curNodes.count() > 1);

    pageTree->push(curNodes[0]);  // Transfer reference.
    catalog->addObject(curNodes[0], false);
    if (rootNode) {
        *rootNode = curNodes[0];
    }
}
Esempio n. 10
0
U32 FamilyNode::GetHierarchy( BuffString *names, U32 &count, Bool local, U32 tabCount, Matrix * matrix) const // = FALSE, = 0, = NULL
{
  if (count >= MAXMESHPERGROUP)
  {
    return count;
  }

  BuffString buff;
  char *p = buff.str;
  U32 i;
  for (i = 0; i < tabCount; i++)
  {
    *p++ = ' ';
  }

  Utils::Strcpy( p, name.str);
  if (names)
  {
    names[count] = buff.str;
  }
  else
  {
    if (matrix)
    {
      CON_DIAG((""));
      LOG_DIAG((""));
    }
    CON_DIAG( ("%s", buff.str) );
    LOG_DIAG( ("%s", buff.str) );

    if (matrix)
    {
      *p = '\0';

      CON_DIAG(("%sright %f,%f,%f", buff.str, matrix->right.x, matrix->right.y, matrix->right.z));
      CON_DIAG(("%sup    %f,%f,%f", buff.str, matrix->up.x,    matrix->up.y,    matrix->up.z));
      CON_DIAG(("%sfront %f,%f,%f", buff.str, matrix->front.x, matrix->front.y, matrix->front.z));
      CON_DIAG(("%sposit %f,%f,%f", buff.str, matrix->posit.x, matrix->posit.y, matrix->posit.z));

      LOG_DIAG(("%sright %f,%f,%f", buff.str, matrix->right.x, matrix->right.y, matrix->right.z));
      LOG_DIAG(("%sup    %f,%f,%f", buff.str, matrix->up.x,    matrix->up.y,    matrix->up.z));
      LOG_DIAG(("%sfront %f,%f,%f", buff.str, matrix->front.x, matrix->front.y, matrix->front.z));
      LOG_DIAG(("%sposit %f,%f,%f", buff.str, matrix->posit.x, matrix->posit.y, matrix->posit.z));
    }
  }

  Matrix newMatrix;
  if (matrix)
  {
    if (count > 0)
    {
      *matrix = ObjectMatrix() * *matrix;
    }
    newMatrix = *matrix;
  }
  count++;

  NList<FamilyNode>::Iterator kids(&children);
  FamilyNode *node;
  while ((node = kids++) != NULL)
  {
    if (local && node->nodeType != nodeMesh && node->nodeType != nodeMeshObj)
    {
      continue;
    }
    if (matrix)
    {
      *matrix = newMatrix;
    }

    tabCount++;
    node->GetHierarchy( names, count, local, tabCount, matrix);
    tabCount--;
  }
  return count;
}
Esempio n. 11
0
std::pair< size_t, size_t > WHtreeProcesser::pruneTree( float condition, size_t safeSize, const HTPROC_MODE pruneType )
{
    if( safeSize == 0 )
    {
        safeSize = m_tree.getNumLeaves(); // any cluster no matter what size may be pruned if he meets the conditions
    }

    if( pruneType == HTPR_SIZERATIO )
    {
        if( condition < 2 )
            throw std::runtime_error( "ERROR @ WHtreeProcesser::pruneTree(): size pruning ratio must be equal or greater than 2" );
    }
    else if( pruneType == HTPR_JOINSIZE )
    {
        condition = std::floor( condition );
        if( condition < safeSize )
            throw std::runtime_error(
                            "ERROR @ WHtreeProcesser::pruneTree(): size pruning lower boundary must be smaller than greater boundary" );
    }
    else if( pruneType == HTPR_JOINLEVEL )
    {
        if( condition <= 0 || condition >= 1 )
        {
            throw std::runtime_error( "ERROR @ WHtreeProcesser::pruneTree(): condition is out of boundaries" );
        }
        if( safeSize >= m_tree.getNumLeaves() )
        {
            throw std::runtime_error(
                     "ERROR @ WHtreeProcesser::pruneTree(): when pruning by distance level a safe size smaller than the roi size must be entered" );
        }
    }

    size_t prunedLeaves( 0 ), prunedNodes( 0 );

    // loop through all leaves and set them to prune if they match discardidng conditions
    for( std::vector< WHnode >::iterator leavesIter( m_tree.m_leaves.begin() ); leavesIter != m_tree.m_leaves.end(); ++leavesIter )
    {
        size_t parentID( leavesIter->getParent().second );
        size_t parentLevel( m_tree.getNode( parentID ).getDistLevel() );

        if( ( pruneType == HTPR_JOINLEVEL ) && ( parentLevel > condition ) )
        {
            leavesIter->setFlag( true );
        }
        else if( ( pruneType == HTPR_SIZERATIO ) || ( pruneType == HTPR_JOINSIZE ) )
        {
            size_t biggerSize( 0 );
            std::vector< nodeID_t > kids( m_tree.getNode( parentID ).getChildren() );
            for( size_t i = 0; i < kids.size(); ++i )
            {
                size_t brotherSize( m_tree.getNode( kids[i] ).getSize() );
                if( brotherSize > biggerSize )
                {
                    biggerSize = brotherSize;
                }
            }
            if( biggerSize > condition )
            {
                leavesIter->setFlag( true );
            }
        }
    }

    // loop through all nodes and set them to prune if they match discarding conditions
    for( std::vector< WHnode >::iterator nodesIter( m_tree.m_nodes.begin() ); nodesIter != m_tree.m_nodes.end() - 1; ++nodesIter )
    { // dont check last node
        size_t parentID( nodesIter->getParent().second );
        size_t nodeSize( nodesIter->getSize() );
        size_t parentLevel( m_tree.getNode( parentID ).getDistLevel() );
        bool pruneBranch( false );

        if( nodeSize < safeSize )
        {
            if( ( pruneType == HTPR_JOINLEVEL ) && ( parentLevel > condition ) )
            {
                pruneBranch = true;
            }
            else if( ( pruneType == HTPR_SIZERATIO ) || ( pruneType == HTPR_JOINSIZE ) )
            {
                size_t biggerSize( 0 );
                std::vector< nodeID_t > kids( m_tree.getNode( parentID ).getChildren() );
                for( size_t i = 0; i < kids.size(); ++i )
                {
                    if( kids[i] == nodesIter->getFullID() )
                    {
                        continue;
                    }
                    size_t brotherSize( m_tree.getNode( kids[i] ).getSize() );
                    if( brotherSize > biggerSize )
                    {
                        biggerSize = brotherSize;
                    }
                }

                if( ( pruneType == HTPR_SIZERATIO ) && ( biggerSize > ( nodeSize * condition ) ) )
                {
                    pruneBranch = true;
                }

                if( ( pruneType == HTPR_JOINSIZE ) && ( biggerSize >=  condition ) )
                {
                    pruneBranch = true;
                }
            }
        }

        if( pruneBranch )
        {
            std::list< nodeID_t > worklist;
            worklist.push_back( nodesIter->getFullID() );
            while( !worklist.empty() )
            {
                WHnode* currentNode( m_tree.fetchNode( worklist.front() ) );
                worklist.pop_front();
                // if current node has already been pruned we continue with the next iteration
                if( currentNode->isFlagged() )
                {
                    continue;
                }
                currentNode->setFlag( true );
                std::vector< nodeID_t > currentKids( currentNode->getChildren() );
                worklist.insert( worklist.end(), currentKids.begin(), currentKids.end() );
            }
        }
    }

    // count total pruned leaves
    for( std::vector< WHnode >::iterator leavesIter( m_tree.m_leaves.begin() ); leavesIter != m_tree.m_leaves.end(); ++leavesIter )
    {
        if( leavesIter->isFlagged() )
        {
            ++prunedLeaves;
        }
    }

    // count total pruned nodes
    for( std::vector< WHnode >::iterator nodesIter( m_tree.m_nodes.begin() ); nodesIter != m_tree.m_nodes.end() - 1; ++nodesIter )
    {
        if( nodesIter->isFlagged() )
            ++prunedNodes;
    }

    if( pruneType == HTPR_SIZERATIO )
    {
        m_tree.m_treeName += ( "_prunedR" + string_utils::toString( safeSize ) + ":" + string_utils::toString( condition ) );
    }
    else if( pruneType == HTPR_JOINSIZE )
    {
        m_tree.m_treeName += ( "_prunedS" + string_utils::toString( condition ) + ":" + string_utils::toString( safeSize ) );
    }
    else if( pruneType == HTPR_JOINLEVEL )
    {
        m_tree.m_treeName += ( "_prunedL" + string_utils::toString( safeSize ) + ":" + string_utils::toString( condition ) );
    }

    std::pair< size_t, size_t > pruned( m_tree.cleanup() );

    pruned.second += m_tree.debinarize();

    return pruned;
} // end "pruneTree()" -----------------------------------------------------------------
Esempio n. 12
0
void CrossoverP(ind& p1,ind& p2,ind& tmpind1,ind& tmpind2,params& p,vector<Randclass>& r)
{ 
	//cout<<"in crossoverP\n";// produces only 1 child.
	vector<ind> parents;
	parents.push_back(p1);
	parents.push_back(p2);

	vector<ind> kids(2);

	int r2,off1,off2,offset,head,it;
		int tmpinssize = 0;
	//if(p.cross==1)
	//{
		for (int r1=0; r1 < 2; r1++)
		{
			if(r1==0)
				r2=1;
			else
				r2=0;
		
			if(parents[r1].line.size()>parents[r2].line.size())
			{
				off1 = r[omp_get_thread_num()].rnd_int(0,parents[r1].line.size()-parents[r2].line.size()-1);
				off2 = 0;
			}
			else if (parents[r2].line.size()>parents[r1].line.size())
			{
				off1 = 0;
				off2 = r[omp_get_thread_num()].rnd_int(0,parents[r2].line.size()-parents[r1].line.size()-1);
			}
			else
			{
				off1=0; 
				off2=0;
			}
			head = r1;
			offset=off1;
			it = 0;
			// assign beginning of parent to kid if it is longer
			while(kids.at(r1).line.size() < offset)
			{
				if (parents[r1].line.at(it)>=100)
				{
					kids.at(r1).args.push_back(parents[r1].args.at(parents[r1].line.at(it)-100));
					kids.at(r1).line.push_back(kids.at(r1).args.size()+99);
				}
				else
					kids.at(r1).line.push_back(parents[r1].line.at(it));
				++it;
			}


			for (unsigned int i=0;i<std::min(parents[r1].line.size(),parents[r2].line.size());i++)
			{
				if (r[omp_get_thread_num()].rnd_flt(0,1)<p.cross_ar)
				{
					if(head==r1)
					{
						head=r2;
						offset=off2;
					}
					else
					{
						head=r1;
						offset=off1;
					}
				}

			
				if(parents[head].line.at(i+offset)>99)
				{// grab arguments
					kids.at(r1).args.push_back(parents[head].args.at(parents[head].line.at(i+offset)-100));
					kids.at(r1).line.push_back(kids.at(r1).args.size()+99);
				}
				else
					kids.at(r1).line.push_back(parents[head].line.at(i+offset));
			
				tmpinssize=0;
				for(unsigned int t=0; t<kids[r1].line.size();t++)
					if(kids[r1].line.at(t)>99) tmpinssize++;
				if(tmpinssize!=kids[r1].args.size())
					cout << "size mismatch" << endl;
			}
		
			
			while(kids.at(r1).line.size() < parents[r1].line.size())
			{
				if (parents[r1].line.at(kids.at(r1).line.size())>=100)
				{
					kids.at(r1).args.push_back(parents[r1].args.at(parents[r1].line.at(kids.at(r1).line.size())-100));
					kids.at(r1).line.push_back(kids.at(r1).args.size()+99);
				}
				else
					kids.at(r1).line.push_back(parents[r1].line.at(kids.at(r1).line.size()));
			}
		}
	//}
	//tmpinssize=0;
	//for(unsigned int t=0; t<kids[0].line.size();t++)
	//	if(kids[0].line.at(t)>99) tmpinssize++;
	//if(tmpinssize!=kids[0].args.size())
	//	cout << "size mismatch" << endl;

	kids.at(0).origin = 'c';
	kids.at(1).origin = 'c';
	tmpind1 = kids.at(0);
	tmpind2 = kids.at(1);

}
Esempio n. 13
0
void Crossover(ind& p1,ind& p2,vector<ind>& tmppop,params& p,vector<Randclass>& r)
{
	vector<ind> parents; parents.reserve(2);
	parents.push_back(p1);
	parents.push_back(p2);

	//makenew(parents[0]);
	//makenew(parents[1]);

	vector<ind> kids(2);

	int r2,off1,off2,offset,head;
	//std::vector<int>::iterator it;
	int tmpinssize = 0;
	vector<int> psize; 
	psize.push_back(p1.line.size());
	psize.push_back(p2.line.size());

	if(p.cross==1) //alternation
	{
		for (int r1=0; r1 < 2; r1++)
		{
			if(r1==0)
				r2=1;
			else
				r2=0;
		
			//if(parents[r1].line.size()>parents[r2].line.size())
			//{
			//	off1 = r[omp_get_thread_num()].rnd_int(0,parents[r1].line.size()-parents[r2].line.size()-1);
			//	off2 = 0;
			//}
			//else if (parents[r2].line.size()>parents[r1].line.size())
			//{
			//	off1 = 0;
			//	off2 = r[omp_get_thread_num()].rnd_int(0,parents[r2].line.size()-parents[r1].line.size()-1);
			//}
			//else
			//{
			//	off1=0; 
			//	off2=0;
			//}
			//head = r1;
			//offset=off1;
			//// assign beginning of parent to kid if it is longer
			//kids.at(r1).line.insert(kids.at(r1).line.end(),parents[r1].line.begin(),parents[r1].line.begin()+offset);

			//for (unsigned int i=0;i<std::min(parents[r1].line.size(),parents[r2].line.size());++i)
			//{
			//	if (r[omp_get_thread_num()].rnd_flt(0,1)<p.cross_ar)
			//	{
			//		if(head==r1)
			//		{
			//			head=r2;
			//			offset=off2;
			//		}
			//		else
			//		{
			//			head=r1;
			//			offset=off1;
			//		}
			//	}
			//		
			//	kids.at(r1).line.push_back(parents[head].line.at(i+offset));
			//}
			//if(kids.at(r1).line.size() < parents[r1].line.size())
			//{
			//	int gap = kids.at(r1).line.size() < parents[r1].line.size()+1;
			//	kids.at(r1).line.insert(kids.at(r1).line.end(),parents[r1].line.end()-gap,parents[r1].line.end());
			//}
				//kids.at(r1).line.push_back(parents[r1].line.at(kids.at(r1).line.size()));

			// new version uses alignment deviation rather than an initial random offset.
			head = r1;
			offset = 0;
			for (unsigned int i=0;i<parents[r1].line.size(); ++i)
			{
				if (r[omp_get_thread_num()].rnd_flt(0,1)<p.cross_ar)
				{
					if(head==r1)
					{
						head=r2;
						
					}
					else
					{
						head=r1;
						//offset=r[omp_get_thread_num()].gasdev()*parents[head].line.size()*p.cross_ar;
					}
					if (p.align_dev) 
						offset=r[omp_get_thread_num()].gasdev();//*parents[head].line.size()*p.cross_ar;
				}
				

				if (i+offset>=parents[head].line.size() || i+offset <= 0) 
					offset = 0;

				if (i < parents[head].line.size() && kids.at(r1).line.size() < p.max_len) 
					kids.at(r1).line.push_back(parents[head].line.at(i+offset));
				
				
			}
			/*if(kids.at(r1).line.size() < parents[r1].line.size())
			{
				int gap = parents[r1].line.size()-kids.at(r1).line.size() +1;
				kids.at(r1).line.insert(kids.at(r1).line.end(),parents[r1].line.end()-gap,parents[r1].line.end());
			}*/
		}
	}
	else if (p.cross==2) // one-point crossover
	{
		if (p.align_dev){
			bool tryagain = true;
			int max_tries = 5;
			int tries = 0;
			while (tryagain && tries < max_tries) {
				int point1 = r[omp_get_thread_num()].rnd_int(0,min(p1.line.size(),p2.line.size()));
				int point2 = point1 + r[omp_get_thread_num()].gasdev(); //*abs(int(p1.line.size()-p2.line.size()))/10;
				int tmp1 = point1;
				int tmp2 = point2;

				point1 += r[omp_get_thread_num()].gasdev(); //*abs(int(p1.line.size()-p2.line.size()))/10;
				int tmp1_1 = point1; 

				if (point1 < 0) 
					point1 = 0;
				else if (point1 > p1.line.size()) {
					point1 = p1.line.size();
				}
		

				if (point2 < 0) 
					point2 = 0;
				else if (point2 > p2.line.size()) {
					int p2size = p2.line.size();
					point2 = p2.line.size();
				}
		

				kids[0].line.assign(parents[0].line.begin(),parents[0].line.begin()+point1);
				kids[0].line.insert(kids[0].line.end(),parents[1].line.begin()+point2,parents[1].line.end());

				kids[1].line.assign(parents[1].line.begin(),parents[1].line.begin()+point2);
				kids[1].line.insert(kids[1].line.end(),parents[0].line.begin()+point1,parents[0].line.end());

				if (kids[0].line.empty() || kids[1].line.empty() || kids[0].line.size()>p.max_len || kids[1].line.size()>p.max_len)
					tryagain = true; 
				else
					tryagain = false;

				++tries;
			
			}
			if (tryagain)
			{
				int point1 = min(p1.line.size(),p2.line.size())/2;
				int point2 = point1;

				kids[0].line.assign(parents[0].line.begin(),parents[0].line.begin()+point1);
				kids[0].line.insert(kids[0].line.end(),parents[1].line.begin()+point2,parents[1].line.end());

				kids[1].line.assign(parents[1].line.begin(),parents[1].line.begin()+point2);
				kids[1].line.insert(kids[1].line.end(),parents[0].line.begin()+point1,parents[0].line.end());
			}
		}
		else{
			int point1 = r[omp_get_thread_num()].rnd_int(0,min(p1.line.size(),p2.line.size()));
			
			kids[0].line.assign(parents[0].line.begin(),parents[0].line.begin()+point1);
			kids[0].line.insert(kids[0].line.end(),parents[1].line.begin()+point1,parents[1].line.end());

			kids[1].line.assign(parents[1].line.begin(),parents[1].line.begin()+point1);
			kids[1].line.insert(kids[1].line.end(),parents[0].line.begin()+point1,parents[0].line.end());
		}

		//int empty_count=0;
		//while(kids[0].line.empty() || kids[1].line.empty() || kids[0].line.size()>p.max_len || kids[1].line.size()>p.max_len && empty_count<10){
		//	int point1 = r[omp_get_thread_num()].rnd_int(0,p1.line.size());
		//	int point2 = r[omp_get_thread_num()].rnd_int(0,p2.line.size());

		//	kids[0].line.assign(parents[0].line.begin(),parents[0].line.begin()+point1);
		//	kids[0].line.insert(kids[0].line.end(),parents[1].line.begin()+point2,parents[1].line.end());

		//	kids[1].line.assign(parents[1].line.begin(),parents[1].line.begin()+point2);
		//	kids[1].line.insert(kids[1].line.end(),parents[0].line.begin()+point1,parents[0].line.end());
		//
		//	++empty_count;
		//}
		//if (empty_count==10) // split parents half and half
		//{	
		//	int point1 = (p1.line.size()-1)/2;
		//	int point2 = (p2.line.size()-1)/2;

		//	kids[0].line.assign(parents[0].line.begin(),parents[0].line.begin()+point1);
		//	kids[0].line.insert(kids[0].line.end(),parents[1].line.begin()+point2,parents[1].line.end());

		//	kids[1].line.assign(parents[1].line.begin(),parents[1].line.begin()+point2);
		//	kids[1].line.insert(kids[1].line.end(),parents[0].line.begin()+point1,parents[0].line.end());
		//}

	}
	else if (p.cross == 3) // sub-tree-like crossover
	{	
		
		for (int r1=0; r1 < 2; ++r1)
		{
			if(r1==0)
				r2=1;
			else
				r2=0;

			int pt1, pt2;

			// specialization for m3gp
			if (p.classification && p.class_m3gp && r[omp_get_thread_num()].rnd_flt(0.0,1.0) > 0.5){
				// find root nodes of r1
				vector<unsigned> roots_r1;
				find_root_nodes(parents[r1].line, roots_r1);
				pt1 = roots_r1[r[omp_get_thread_num()].rnd_int(0,roots_r1.size()-1)];

				vector<unsigned> roots_r2;
				find_root_nodes(parents[r2].line, roots_r2);
				pt2 = roots_r2[r[omp_get_thread_num()].rnd_int(0,roots_r2.size()-1)];
			}
			else{
				pt1 = r[omp_get_thread_num()].rnd_int(0,parents[r1].line.size()-1);
				pt2 = r[omp_get_thread_num()].rnd_int(0,parents[r2].line.size()-1);
			}

			int end1 = pt1;
			int sum_arity = parents[r1].line[pt1].arity_float;
			while (sum_arity > 0 && pt1 > 0)
			{
				--pt1;
				--sum_arity;
				sum_arity+=parents[r1].line[pt1].arity_float;
				
			}
			int begin1 = pt1;

			int end2 = pt2;
			sum_arity = parents[r2].line[pt2].arity_float;
			while (sum_arity > 0 && pt2 > 0)
			{				
				--pt2;
				--sum_arity;
				sum_arity+=parents[r2].line[pt2].arity_float;
			}
			int begin2 = pt2;
			ind st1, st2;
			st1.line.assign(parents[r1].line.begin()+begin1,parents[r1].line.begin()+end1+1);
			st2.line.assign(parents[r2].line.begin()+begin2,parents[r2].line.begin()+end2+1);
			
			kids[r1].line.assign(parents[r1].line.begin(),parents[r1].line.begin()+begin1);
			kids[r1].line.insert(kids[r1].line.end(),parents[r2].line.begin()+begin2,parents[r2].line.begin()+end2+1);
			kids[r1].line.insert(kids[r1].line.end(),parents[r1].line.begin()+end1+1,parents[r1].line.end());

			if (kids[r1].line.size()>p.max_len)
				kids[r1].line = parents[r1].line;
		}
		
		
	}
	//tmpinssize=0;
	//for(unsigned int t=0; t<kids[0].line.size();t++)
	//	if(kids[0].line.at(t)>99) tmpinssize++;
	//if(tmpinssize!=kids[0].args.size())
	//	cout << "size mismatch" << endl;
	assert(~kids[0].line.empty() && ~kids[1].line.empty());
		
	/*assert(kids[0].line.size() >= p.min_len);
	assert(kids[1].line.size() >= p.min_len);*/

	tmpinssize=0;

	kids[0].origin = 'c';
	kids[0].parentfitness = parents[0].fitness;
	kids[1].origin = 'c';
	kids[1].parentfitness = parents[1].fitness;

	//makenew(kids[0]);
	//makenew(kids[1]);

	tmppop.push_back(kids[0]);
	tmppop.push_back(kids[1]);

	//kids.clear();
	//parents.clear();
}
Esempio n. 14
0
void test_copy(void)
{
  knowledge::KnowledgeBase source, dest;
  containers::StringVector kids("kids", source, 1);
  knowledge::CopySet copy_set;

  // create some information in the source knowledge base
  source.set("name", "John Smith");
  source.set("age", Integer(20));
  source.set("occupation", "Explorer");
  source.set("spouse", "Pocahontas");
  kids.set(0, "Thomas Rolfe");

  // TEST 1: Copy everything to destination
  dest.copy(source, copy_set, false);
  if (dest.get("name") == "John Smith" && dest.get("age") == Integer(20) &&
      dest.get("occupation") == "Explorer" &&
      dest.get("spouse") == "Pocahontas" &&
      dest.get("kids.0") == "Thomas Rolfe")
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 1: Full copy is SUCCESS.\n");
  }
  else
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 1: Full copy is FAIL.\n");
    ++madara_fails;
    dest.print();
  }

  // TEST 2: Copy name to destination
  copy_set.clear();
  copy_set["name"] = true;

  dest.copy(source, copy_set, true);
  if (dest.get("name") == "John Smith" && !dest.exists("age") &&
      !dest.exists("occupation") && !dest.exists("spouse") &&
      !dest.exists("kids.0"))
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 2: Lone name copy is SUCCESS.\n");
  }
  else
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 2: Lone name copy is FAIL.\n");
    ++madara_fails;
    dest.print();
  }

  // TEST 3: Add age to destination
  copy_set.clear();
  copy_set["age"] = true;

  dest.copy(source, copy_set, false);
  if (dest.get("name") == "John Smith" && dest.get("age") == Integer(20) &&
      !dest.exists("occupation") && !dest.exists("spouse") &&
      !dest.exists("kids.0"))
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 3: Add age to copy is SUCCESS.\n");
  }
  else
  {
    madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
        "TEST 3: Add age to copy is FAIL.\n");
    dest.print();
  }

  madara_logger_ptr_log(logger::global_logger.get(), logger::LOG_ALWAYS,
      "\nEND OF TESTS CONTEXT CONTENTS:\n"
      "\nSource:\n");
  source.print();

  madara_logger_ptr_log(
      logger::global_logger.get(), logger::LOG_ALWAYS, "\nDest:\n");
  dest.print();
}