Example #1
0
TEST(DomTreeTest, DomTreeInitTest)
{
    LOG_INFO << "pid = " << getpid() << " begin to run";
    EXPECT_FALSE(false);

    Node* head = new Text("html");
    Element* p = new Element("a");
    p->AddAttr("href", "http://abc/");
    p->AddAttr("color", "yellow");
    Node* txt = new Text("def");
    Node* txt2 = new Text("Head");

    head->AddChild(p);
    p->AddChild(txt);
    head->AddChild(txt2);

    ostringstream oss;
    head->ToString(oss, 0);
    LOG_INFO << "\n" << oss.str();
    string out(
            "html\n"
            "--Tagname is a Key colorValue yellow Key hrefValue http://abc/\n"
            "----def\n"
            "--Head\n");
    ASSERT_EQ(out, oss.str());

    delete head;
    delete p;
    delete txt;
    delete txt2;

}
Example #2
0
pair<Node*, unordered_map<Node*, Node*> > PolySolverNAD::PolytomizeNAD(Node* nadNode, Node* speciesTree, unordered_map<Node*, Node*> lcaMapping)
{
    set<Node*> leftSubtrees, rightSubtrees;
    Node* s = lcaMapping[nadNode];

    //TODO : there should be a way not to iterate uselessly into a taken subtree (preorder traversal that we stop)
    TreeIterator* it = nadNode->GetPostOrderIterator();
    while (Node* n = it->next())
    {
        if (n != nadNode)
        {
            //here we maximal subtree either on the left or right
            if (lcaMapping[n] != s && lcaMapping[n->GetParent()] == s)
            {
                if (lcaMapping[n]->HasAncestor(s->GetChild(0)))
                {
                    leftSubtrees.insert(n);
                }
                else    //if (lcaMapping[n]->HasAncestor(s->GetChild(1))) should be the only possibility here
                {
                    rightSubtrees.insert(n);
                }
            }
        }
    }
    nadNode->CloseIterator(it);


    Node* newShizzle = new Node(false);
    Node* left = newShizzle->AddChild();
    Node* right = newShizzle->AddChild();
    unordered_map<Node*, Node*> newMapping;

    for (set<Node*>::iterator itLeft = leftSubtrees.begin(); itLeft != leftSubtrees.end(); itLeft++)
    {
        Node* copy = GeneSpeciesTreeUtil::Instance()->CopyTreeWithNodeMapping((*itLeft), lcaMapping, newMapping);
        left->AddSubTree(copy);
    }

    for (set<Node*>::iterator itRight = rightSubtrees.begin(); itRight != rightSubtrees.end(); itRight++)
    {
        Node* copy = GeneSpeciesTreeUtil::Instance()->CopyTreeWithNodeMapping((*itRight), lcaMapping, newMapping);
        right->AddSubTree(copy);
    }

    newMapping[newShizzle] = s;
    if (left->GetNbChildren() > 1)
    {
        newMapping[left] = GeneSpeciesTreeUtil::Instance()->GetSingleNodeLCAMapping(left, speciesTree, newMapping);
    }
    if (right->GetNbChildren() > 1)
    {
        newMapping[right] = GeneSpeciesTreeUtil::Instance()->GetSingleNodeLCAMapping(right, speciesTree, newMapping);
    }

    newShizzle->DeleteSingleChildDescendants();

    return make_pair(newShizzle, newMapping);
}
Example #3
0
int main(int argc, char** argv) {
    qRegisterMetaType<ComponentA>("ComponentA");
    qRegisterMetaType<ComponentB>("ComponentB");

    Node base;
    base.AddChild(new Node)->AddComponent(new ComponentA);
    base.AddChild(new Node)->AddChild(new Node);
    Node* n = base.AddChild(new Node);
    n->AddComponent(new ComponentA);
    n->AddComponent(new ComponentB);

    //base.Display();
    //

    // yaml test
    YAML::Emitter out;
    out << YAML::BeginMap;
    out << YAML::Key << "metadata" << YAML::Value;
        out << YAML::BeginMap;
        out << YAML::Key << "author" << YAML::Value << "opatut";
        out << YAML::Key << "date" << YAML::Value << "2011-10-23";
        out << YAML::EndMap;


    out << YAML::Key << "rootnode" << YAML::Value;
    base.Serialize(out);

    std::string yaml(out.c_str());

    std::cout << "Output YAML:" << std::endl << "========" << std::endl;
    std::cout << yaml << std::endl;

    std::cout << "Base:" << std::endl << "========" << std::endl;
    base.Display();
    
    std::istringstream stream;
    stream.str(yaml);

    YAML::Parser parser(stream);
    YAML::Node doc;
    parser.GetNextDocument(doc);
    Node* read = Node::Deserialize(doc["rootnode"]);
    std::cout << "Read:" << std::endl << "========" << std::endl;
    read->Display();



    return 0;
}
Example #4
0
Node* Node::Deserialize(const YAML::Node& node) {
    Node* n = new Node;

    std::string uuid;
    node["uuid"] >> uuid;
    std::cout << "::LOADING " << uuid << std::endl;
    n->mId = boost::uuids::string_generator()(uuid);

    try {
        for(unsigned i = 0; i < node["children"].size(); i++) {
            Node* c = Deserialize(node["children"][i]);
            if(c != nullptr)
                n->AddChild(c);
        }
    } catch(YAML::TypedKeyNotFound<std::string> e) {}

    try {
        for(unsigned i = 0; i < node["components"].size(); i++) {
            Component* c = Component::Deserialize(node["components"][i]);
            if(c != nullptr)
                n->AddComponent(c);
        }
    } catch(YAML::TypedKeyNotFound<std::string> e) {}

    return n;
}
Example #5
0
Node* Node::InsertParentWith(Node* sibling)
{
    Node* prevParent = this->parent;

    if (!prevParent)
        return NULL;

    int sindex = -1;
    for (int i = 0; i < prevParent->GetNbChildren(); i++)
    {
        if (prevParent->GetChild(i) == sibling)
        {
            sindex = i;
            break;
        }
    }

    if (sindex == -1)
        return NULL;

    Node* newParent = prevParent->AddChild();

    prevParent->RemoveChild(this);
    prevParent->RemoveChild(sibling);

    newParent->AddSubTree(this);
    newParent->AddSubTree(sibling);

    return newParent;

}
Example #6
0
void DOTHeal::ClientExecute()
{//todo casting times (based on lag)
	/*particleStartNode_->SetPosition(node_->GetPosition());
	emitterStartFX_->SetEmitting(true);*/

	int clientID = message_->ReadInt();
	lagTime_ += message_->ReadFloat();

	Node* noed = gameMode_->GetClientIDNode(clientID);
	noed->AddChild(noed->GetComponent<DOTHeal>()->particleEndNode_);
	victoria_ = noed->GetPosition();
	victoria_.y_ += noed->GetComponent<DOTHeal>()->beeBox_.Size().y_;
	noed->GetComponent<DOTHeal>()->particleEndNode_->SetWorldPosition(victoria_);
	noed->GetComponent<DOTHeal>()->emitterEndFX_->SetEmitting(true);
	noed->GetComponent<DOTHeal>()->dothealed_ = true;
	noed->GetComponent<DOTHeal>()->DOTHealElapsedTime_ = lagTime_;
	//noed->GetComponent<DOTHeal>()->SubscribeToEvent(E_UPDATE, HANDLER(DOTHeal, HandleUpdate));
	noed->GetComponent<DOTHeal>()->particleEndNode_->GetComponent<SoundSource3D>()->Play(main_->cache_->GetResource<Sound>("Sounds/dotheal/dotheal.ogg"));

	gameMode_->RequestAnimation(clientID_,"attack", false, 1);

	VariantMap vm;
	vm[SoundRequest::P_NODE] = node_;
	vm[SoundRequest::P_SOUNDTYPE] = SoundPlayer::SOUNDTYPE_CAST_;
	SendEvent(E_SOUNDREQUEST,vm);

	clientExecuting_ = true;
	elapsedTime_ = lagTime_;
	//SubscribeToEvent(E_UPDATE, HANDLER(DOTHeal, HandleUpdate));
}
Example #7
0
void PhoneBook::AddEntry(const Entry& anEntry) {
    const char* pName = anEntry.Name();
    if (pName && pName != '\0') {
        int length = strlen(pName);
        char key;
        Node* currNode = iRoot;
        Node* childNode = NULL;
        Entry blankEntry(NULL, NULL);
        
        for (int index = 0; index < length; index++) {
            key = pName[index];
            childNode = currNode->GetChildNodeByKey(key);
            //if this is a new node, create one
            if (!childNode) {
                //If we have reaches the last character, then its a terminal node
                if (index == length-1) {
                    //So store the Entry
                    childNode = new Node(key, anEntry);
                    childNode->IsTerminal(true);
                }
                else {
                    //Not a terminal node, so dont have to store anything, store some dummy value
                    childNode = new Node(key, blankEntry);
                }

                //Add the Node to the currNode
                currNode->AddChild(childNode);
                currNode = childNode;
            }
            else {
                currNode = childNode;
            }
        }
    }
}
Example #8
0
File: pyx.cpp Project: JunC74/PYX
void test()
{
	Node *bar = Node::Create();
	
	GeometryModel * bar_mode = GeometryModel::CreateSquare(40, 5, 0, 0, 
		TextureLoader::GetInstance()->LoadTexture2D("Tex/yellow.jpg"));
	Sprite *bar_sprite = Sprite::CreateWithModel(bar_mode);

	GeometryModel * bg_mode = GeometryModel::CreateSquare(40, 5, 0, 0, 
		TextureLoader::GetInstance()->LoadTexture2D("Tex/white.jpg"));
	Sprite *bg_sprite = Sprite::CreateWithModel(bg_mode);
	bg_sprite->SetTranslationZ(-0.1);

	bar->AddChild(bg_sprite);
	bar->AddChild(bar_sprite);
	bar_sprite->SetScaleX(0.5);
	Root::GetInstance()->GetNode()->AddChild(bar);
}
Example #9
0
bool nglZipFS::BuildIndex()
{
  int res;
  unzFile Zip = mpPrivate->mZip;
  unz_global_info global_info;

  if (UNZ_OK != unzGetGlobalInfo(Zip, &global_info))
    return false;

  if (UNZ_OK != unzGoToFirstFile(Zip))
    return false;

  do 
  {
    unz_file_info file_info;
    unz_file_pos file_pos;
    char filename[4096];

    if (UNZ_OK != unzGetCurrentFileInfo(Zip, &file_info, filename, 4096, NULL, 0, NULL, 0))
      return false;

    if (UNZ_OK != unzGetFilePos(Zip, &file_pos))
      return false;

    uint len = strlen(filename);
    bool IsDir = (filename[len-1] == '\\') || (filename[len-1] == '/');
    std::list<nglPath> List;

    nglZipPath::Decompose(filename, List);

    std::list<nglPath>::iterator it;
    std::list<nglPath>::iterator end = List.end();

    Node* pPath = &mRoot;

    int i = List.size();
    for (it = List.begin(); it != end; ++it)
    {
      nglString name = (*it).GetPathName();
      Node* pChild = pPath->Find(name);
      if (!pChild)
      {
        //printf("zipfile: %s\n", name.GetChars());
        pChild = new Node(name, file_info.uncompressed_size, file_pos.pos_in_zip_directory, file_pos.num_of_file, i == 1 && !IsDir);
        pPath->AddChild(pChild);
      }
      pPath = pChild;
      i--;
    }
  }
  while (UNZ_OK == (res = unzGoToNextFile(Zip)));

  if (res == UNZ_END_OF_LIST_OF_FILE)
    return true;
  return false;
}
Example #10
0
void SceneImporter<real>::ReadNodeHeader( std::istream& stream, Node<real>* ioNode )
{
	std::string parentName = ReadNextToken( stream ); ReadNextExactToken( stream, "," );
	Transformation<real> transformation = ReadTransformation( stream );

	Node<real>* parent = GetNode( parentName );

	if ( parent )
		parent->AddChild( ioNode );

	ioNode->SetLocalTransformation( transformation );
}
Example #11
0
Node* Node::GraftOnParentEdge(Node* nodeToGraft)
{
    if (this->IsRoot())
        throw "Can graft on root";
    Node* parent = this->GetParent();

    parent->RemoveChild(this);
    Node* n = parent->AddChild();
    n->AddSubTree(this);
    n->AddSubTree(nodeToGraft);

    return n;
}
Example #12
0
void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
{
    Scene* scene = GetScene();
    if (!scene)
        return;

    MemoryBuffer buf(value);
    // If nothing in the buffer, parent is the root node
    if (buf.IsEof())
    {
        scene->AddChild(this);
        return;
    }

    unsigned baseNodeID = buf.ReadNetID();
    Node* baseNode = scene->GetNode(baseNodeID);
    if (!baseNode)
    {
        LOGWARNING("Failed to find parent node " + String(baseNodeID));
        return;
    }

    // If buffer contains just an ID, the parent is replicated and we are done
    if (buf.IsEof())
        baseNode->AddChild(this);
    else
    {
        // Else the parent is local and we must find it recursively by name hash
        StringHash nameHash = buf.ReadStringHash();
        Node* parentNode = baseNode->GetChild(nameHash, true);
        if (!parentNode)
            LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
        else
            parentNode->AddChild(this);
    }
}
Example #13
0
bool Graph::Search()
{
    number_nodes_generated = 0;
    max_nodes_stored       = 0;

    root = new Node(problem->GetInitialState(), 0, 0, 0.0, problem->Heuristic(problem->GetInitialState()), 0);
    fringe->Insert(root);
    closed.Clear();

    while(!fringe->Empty())
    {
        Node *node = fringe->Remove();
        if(problem->GoalTest(node->GetState()))
        {
            solution.SetFromNode(node);
            return true;
        }
        if(!closed.Contains(node))
        {
            closed.Insert(node);
            std::vector<ActionStatePair> successors;
            problem->FindSuccessors(node->GetState(), successors);
            std::vector<ActionStatePair>::iterator i;

            number_nodes_generated += successors.size();
            max_nodes_stored       += successors.size();

            for(i = successors.begin(); i != successors.end(); i++)
            {
                Node *new_node = new Node(i->GetState(),
                                          node,
                                          i->GetAction(),
                                          (node->GetPathCost() +
                                           problem->StepCost(node->GetState(), i->GetAction(), i->GetState())),
                                          problem->Heuristic(i->GetState()),
                                          (node->GetDepth() + 1)
                                         );
                node->AddChild(new_node);
                fringe->Insert(new_node);
            }
        }
    }
    return false;
}
TEST(PreorderIterator, VerticalGraph) {
    Graph graph;

    Node* lastNode = &graph.CreateNode();
    for (size_t i = 0; i < 10; ++i) {
        Node* newNode = &graph.CreateNode();
        lastNode->AddChild(newNode->id());
        lastNode = newNode;
    }

    std::vector<NodeId> expected_nodes = {
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<size_t> expected_depths = {
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<size_t> expected_child_index = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
    ExpectTraversal(expected_nodes, expected_depths, expected_child_index, graph);
}
Example #15
0
void Trie::AddWord( string s )
{
	int i=0;
	Node* tmp = root;

	while ( i < s.length() )
	{
		Node* c = tmp->FindChild( s.at(i) );

		if ( c == NULL )
		{
			Node *n = new Node( s.at(i) );
			tmp->AddChild( n );
			tmp = n;
		} else {
			tmp = c;
		}
		i++;
	}
}
void AlignmentGraph::AttachUnalignedSourceWords()
{
  // Find the unaligned source words (if any).
  std::set<int> unaligned;
  for (int i = 0; i < m_sourceNodes.size(); ++i) {
    const Node &sourceNode = (*m_sourceNodes[i]);
    if (sourceNode.GetParents().empty()) {
      unaligned.insert(i);
    }
  }

  // Determine the attachment point for each one and attach it.
  for (std::set<int>::iterator p = unaligned.begin();
       p != unaligned.end(); ++p) {
    int index = *p;
    Node *attachmentPoint = DetermineAttachmentPoint(index);
    Node *sourceNode = m_sourceNodes[index];
    attachmentPoint->AddChild(sourceNode);
    sourceNode->AddParent(attachmentPoint);
  }
}
AlignmentGraph::AlignmentGraph(const ParseTree *t,
                               const std::vector<std::string> &s,
                               const Alignment &a)
{
  // Copy the parse tree nodes and add them to m_targetNodes.
  m_root = CopyParseTree(t);

  // Create a node for each source word.
  m_sourceNodes.reserve(s.size());
  for (std::vector<std::string>::const_iterator p(s.begin());
       p != s.end(); ++p) {
    m_sourceNodes.push_back(new Node(*p, SOURCE));
  }

  // Connect source nodes to parse tree leaves according to the given word
  // alignment.
  std::vector<Node *> targetTreeLeaves;
  GetTargetTreeLeaves(m_root, targetTreeLeaves);
  for (Alignment::const_iterator p(a.begin()); p != a.end(); ++p) {
    Node *src = m_sourceNodes[p->first];
    Node *tgt = targetTreeLeaves[p->second];
    src->AddParent(tgt);
    tgt->AddChild(src);
  }

  // Attach unaligned source words (if any).
  AttachUnalignedSourceWords();

  // Populate node spans.
  std::vector<Node *>::const_iterator p(m_sourceNodes.begin());
  for (int i = 0; p != m_sourceNodes.end(); ++p, ++i) {
    (*p)->PropagateIndex(i);
  }

  // Calculate complement spans.
  CalcComplementSpans(m_root);
}
void RealisticWaterState::Initialize()
{
  SDLState::Initialize(); // initialize window

  mPhysx.Setup(-9.81);
  mPhysx.Initialize();
  mGPURenderer.Initialize();
  mModelLoader.Setup(&mGPURenderer);



  // camera
  mCamera.Setup("cameraPosition", "viewMat", "projMat", &mGPURenderer);
  mCamera.SetSceneNode(&mRootNode);
  mCamera.PerspectiveMatrix(45.0,1024.0,768.0, .1,100.0);
  mCamera.SetPosition(0,2.5,5);
  mRootNode.AddAction(&mCamera);
  mRootNode.AddAsset(&mCamera);
  mCamera.SetSceneNode(&mRootNode);

  mPS.Setup(&mCamera, &mGPURenderer);
  mPS.Initialize();

  mGPURenderer.SetParticleSystem(&mPS);


  // light1
  Light* light1 = new Light();
  light1->Setup("light", &mGPURenderer);
  light1->SetColor(glm::vec3(1,1,1));
  light1->SetPosition(glm::vec3(25,50,35));
  light1->SetQuadraticAttenuation(0.0001);
  mGPURenderer.AddLight(light1);
  // light1
  Light* light2 = new Light();
  light2->Setup("light", &mGPURenderer);
  light2->SetColor(glm::vec3(1,1,1));
  light2->SetPosition(glm::vec3(-35,50,50));
  light2->SetQuadraticAttenuation(0.0001);
  mGPURenderer.AddLight(light2);

  PhysicsMaterial mat;
  mat.mDensity = .5;
  mat.mDynamicFriction = 0.5;
  mat.mStaticFriction = 0.5;
  mat.mRestitution = 0.5;


  Node* baseObjSubnode = new Node();
  mModelLoader.Load("./", "boxwithhole.obj", baseObjSubnode);
  Node* baseObjRootnode = new Node();
  baseObjRootnode->AddChild(baseObjSubnode);
  glm::mat4 scale = glm::mat4(1.0);
  scale = glm::scale(scale, glm::vec3(1.5,2,1.5));
  baseObjSubnode->SetLocalTransform(scale);

//  mRootNode.AddChild(baseObjRootnode);
  mPhysx.AddObject(baseObjRootnode, PhysicsEngine::RIGID_STATIC, mat);


  std::vector<uint32_t> ind;
  uint32_t index = 0;

  /*
   * set positions of Particles
   * added indices(needed for physx system
   */

  for(GLfloat k = 0; k < 40; k+= .01) // a bit of a hack works for now..
  {
    for(GLfloat i = 0; i < .1; i+= .05)
    {
      for(GLfloat j = 0; j < .1; j+= .05)
      {
        //      glm::vec3 tmp = glm::vec3(i-10, i*j/10, j-10);

        mPositions[3*index+0] = i-.05;
        mPositions[3*index+1] = k/100;
        mPositions[3*index+2] = j-.05;

        //      pos.push_back(tmp);
        ind.push_back(index++);
      }
    }
  }

  std::cout << "number of particles " << ind.size() << std::endl;

  mNumParticles = index;
  if(mPhysx.CreateFluid(ind.size(), ind.data(), mPositions) == false)
  {
    std::cout << "success creating fluid\n";
  }


  // initial key states
  for(int i = 0; i < 256; i++)
    mKeysPressed[i] = false;
  std::cout.flush();
  glClearColor(0.7,0.7,0.7,1);
}
Example #19
0
pair<Node*, Node*> PolySolverNAD::GetRandomPolytomy(int k, int verbose)
{
    Node* speciesTree = new Node(false);

    double s_size_factor = 2.5 * (double)(rand() % 1000)/1000.0 + 0.5;  //between 0.5 and 3

    for (int i = 0; i < s_size_factor*k; i++)
    {
        Node* c = speciesTree->AddChild();
        c->SetLabel("S" + Util::ToString(i));
    }

    speciesTree->BinarizeRandomly();

    //get an ordering of the internal nodes...this will let us pick one at random
    vector<Node*> internalNodes;

    TreeIterator* it = speciesTree->GetPostOrderIterator(false);
    while (Node* s = it->next())
    {
        if (!s->IsLeaf())
        {
            internalNodes.push_back(s);
        }

    }
    speciesTree->CloseIterator(it);

    //generate k gene subtrees
    unordered_map<Node*, Node*> lcaMapping;
    vector<Node*> forest;
    map<Node*, Node*> geneLeftSpecies;
    map<Node*, Node*> geneRightSpecies;

    for (int i = 0; i < k; i++)
    {
        Node* g = new Node(false);
        g->SetLabel("G" + Util::ToString(i));

        //pick an lca for g at random
        Node* lca = internalNodes[rand() % internalNodes.size()];
        lca->SetLabel(lca->GetLabel() + "_" + Util::ToString(i));
        lcaMapping[g] = lca;

        //add something left and right to enforce s(g) = lca
        //by adding a species specific to g on both sides
        bool done = false;
        TreeIterator* itLeft = lca->GetChild(0)->GetPostOrderIterator();
        while (Node* s = itLeft->next())
        {
            if (!done)
            {
                string slbl = s->GetLabel();
                if (slbl[0] == 'S') //got an original species leaf
                {
                    Node* sg = s->AddChild();
                    sg->SetLabel("XL" + Util::ToString(i));

                    Node* gs = g->AddChild();
                    gs->SetLabel("XL" + Util::ToString(i));

                    lcaMapping[gs] = sg;
                    done = true;

                    geneLeftSpecies[g] = s;
                }
            }
        }
        lca->CloseIterator(itLeft);


        done = false;
        TreeIterator* itRight = lca->GetChild(1)->GetPostOrderIterator();
        while (Node* s = itRight->next())
        {
            if (!done)
            {
                string slbl = s->GetLabel();
                if (slbl[0] == 'S') //got an original species leaf
                {
                    Node* sg = s->AddChild();
                    sg->SetLabel("XR" + Util::ToString(i));

                    Node* gs = g->AddChild();
                    gs->SetLabel("XR" + Util::ToString(i));

                    lcaMapping[gs] = sg;
                    done = true;

                    geneRightSpecies[g] = s;
                }
            }
        }
        lca->CloseIterator(itRight);

        forest.push_back(g);
    }

    int AD_prob = rand() % 50 + 25; //between 25-75% chances of having a dup

    //ok, we have a forest.  Now, everything is either S or NAD (no species are shared since we created one specific to each gene)
    //so here we add a couple AD
    for (int i = 0; i < forest.size(); i++)
    {
        Node* g1 = forest[i];
        Node* s1 = lcaMapping[g1];
        for (int j = i + 1; j < forest.size(); j++)
        {
            Node* g2 = forest[j];
            Node* s2 = lcaMapping[g2];

            //they're related...make them AD if we're lucky enough
            if (s1->HasAncestor(s2) || s2->HasAncestor(s1))
            {
                int r = rand() % 100;

                //add a species near the g1left species s.t. g1 and g2 will share a gene of this species
                if (r < AD_prob)
                {
                    Node* s_to_add_to = geneLeftSpecies[g1];
                    if (!s1->HasAncestor(s2))
                        s_to_add_to = geneLeftSpecies[g2];

                    Node* dspecies = s_to_add_to->AddChild();
                    dspecies->SetLabel("AD_" + g1->GetLabel() + "_" + g2->GetLabel());

                    Node* newg1 = g1->AddChild();
                    newg1->SetLabel(dspecies->GetLabel());
                    lcaMapping[newg1] = dspecies;

                    Node* newg2 = g2->AddChild();
                    newg2->SetLabel(dspecies->GetLabel());
                    lcaMapping[newg2] = dspecies;
                }
            }
        }
    }



    //if everything was done correctly, binarizing S
    speciesTree->BinarizeRandomly();
    speciesTree->DeleteSingleChildDescendants();

    string sstr = NewickLex::ToNewickString(speciesTree);
    if (verbose > 0)
        cout<<"S="<<sstr<<endl;

    Node* poly = new Node(false);
    for (int i = 0; i < forest.size(); i++)
    {
        forest[i]->BinarizeRandomly();


        poly->AddSubTree(forest[i]);
    }

    string gstr = NewickLex::ToNewickString(poly);
    if (verbose > 0)
        cout<<"G="<<"="<<gstr<<endl;


    //we have to recreate the species tree, or later on lca mapping will get messed up FOR UNKNOWN REASONS !
    string spNewick = NewickLex::ToNewickString(speciesTree);
    delete speciesTree;

    speciesTree = NewickLex::ParseNewickString(spNewick, true);

    lcaMapping.clear();

    return make_pair(poly, speciesTree);
}
Example #20
0
void MainWindow::Load(const nglPath& p)
{    
  mpScrollView->Clear();
  ///////////////////////////////

  nglString cmdline;
  //cmdline.Add("/usr/bin/nm -n -U -arch i386 ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
  cmdline.Add("/usr/bin/nm -n -U ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
  printf("Launching\n%ls\n", cmdline.GetChars());
  FILE * file = popen(cmdline.GetStdString().c_str(), "r");
  nglOMemory omem;
  uint32 res = 0;
  do
  {
    char buf[1025];
    memset(buf, 0, 1025);
    uint32 res = fread(buf, 1024, 1, file);
    //printf("%s", buf);
    omem.Write(buf, 1024, 1);
  } while (!feof(file));
  pclose(file);
  
  printf("redirection done\n");
  nglIStream* pStream = new nglIMemory(omem.GetBufferData(), omem.GetBufferSize());;
  
  nglString line;
  
  uint64 lastaddr = 0;
  nglString lastsymbol;
  
  std::map<nglString, Node*> methods;
  std::map<nglString, Node*> classes;
  
  printf("read result\n");
  while (pStream->ReadLine(line))
  {
    // Read address
    int32 c = 0;
    while (line[c] && line[c] != ' ')
      c++;
    nglString a(line.Extract(0, c));
    uint64 address = a.GetCUInt(16);

    c++;
    // Read type char
    nglChar type = line[c];
    
    // Read Symbol if we are on a method / function decl
    if (type == 't')
    {
      c++;

      if (!lastsymbol.IsEmpty())
      {
        uint64 lastsize = address - lastaddr;
        
        std::map<nglString, Node*>::iterator it = methods.find(lastsymbol);
        
        bool skip = false;
        Node* pMethod = NULL;
        if (it != methods.end())
        {
          pMethod = it->second;
          pMethod->SetSize(pMethod->GetSize() + lastsize);
          //it->second += lastsize;
          skip = true;
        }
        else
        {
          //NGL_OUT(_T("new method \t %ls\n"), lastsymbol.GetChars());
          pMethod = new Node(lastsymbol);
          pMethod->SetSize(lastsize);
          methods[lastsymbol] = pMethod;
        }
        
        NGL_ASSERT(pMethod != NULL);
        
        if (!skip) // The method already exist so no need to add it to its class
        {
          int32 pos = lastsymbol.Find(':');
          if (pos > 0 && lastsymbol[pos+1] == ':')
          {
            nglString classname = lastsymbol.GetLeft(pos);
            //NGL_OUT(_T("new class %ls\n"), classname.GetChars());
            
            std::map<nglString, Node*>::iterator it = classes.find(classname);
            Node* pNode = NULL;
            if (it != classes.end())
            {
              pNode = it->second;
              pNode->SetSize(it->second->GetSize() + lastsize);
            }
            else
            {
              pNode = new Node(classname);
              pNode->SetSize(lastsize);
              classes[classname] = pNode;
            }
            
            pNode->AddChild(pMethod);
          }
        }
      }
      
      lastaddr = address;
      lastsymbol = line.GetRight(line.GetLength() - c);
    }
  }
  printf("done\n");
  
  printf("build tree\n");
  delete pStream;
  
  std::list<std::pair<nglString, Node*> > sorted;
  {
    std::map<nglString, Node*>::const_iterator it = classes.begin();
    std::map<nglString, Node*>::const_iterator end = classes.end();
    
    while (it != end)
    {
      //NGL_OUT(_T("add unsorted %ls\n"), it->first.GetChars());
      sorted.push_back(std::pair<nglString, Node*>(it->first, it->second) );
      ++it;
    }
  }
  
  sorted.sort(cmp);
  
  nuiTreeNode* pTree = new nuiTreeNode(new nuiLabel(_T("Classes")));
  
  {
    std::list<std::pair<nglString, Node*> >::const_iterator it = sorted.begin();
    std::list<std::pair<nglString, Node*> >::const_iterator end = sorted.end();
    
    while (it != end)
    {
      //NGL_OUT(_T("%lld\t\t%ls\n"), it->second->GetSize(), it->first.GetChars());
      pTree->AddChild(it->second);
      ++it;
    }
  }
  
  nuiTreeView* pTreeView = new nuiTreeView(pTree);
  mpScrollView->AddChild(pTreeView);
  printf("done\n");
}