I would like to create a tree by dynamically adding nodes to an already existing tree in DendroPy. So here is how I am proceeding,
>>> t1 = dendropy.Tree(stream=StringIO("(8,3)"),schema="newick")
Now That creates a small tree with two children having Taxon labels 8 and 3. Now I want to add a new leaf to the node with taxon label 3. In order to do that I want the node object.
>>> cp = t1.find_node_with_taxon_label('3')
I want to use add child function at that point which is an attribute of a node.
>>> n = dendropy.Node(taxon='5',label='5')
>>> cp.add_child(n)
But even after adding the node when I am printing all the node objects in t1, It is returning the only children 8 and 3 that it was initialized with. Please help me to understand how to add nodes in an existing tree in dendropy..
Now if we print t1 we would see the tree. But even after adding the elements I could not find the objects that are added. For example if we do a
>>> cp1 = t1.find_node_with_taxon_label('5')
It is not returning the object related to 5.
To add a taxon you have to explicitly create and add it to the tree:
t1 = dendropy.Tree(stream=StringIO("(8,3)"),schema="newick")
# Explicitly create and add the taxon to the taxon set
taxon_1 = dendropy.Taxon(label="5")
t1.taxon_set.add_taxon(taxon_1)
# Create a new node and assign a taxon OBJECT to it (not a label)
n = dendropy.Node(taxon=taxon_1, label='5')
# Now this works
print t1.find_node_with_taxon_label("5")
The key is that find_node_with_taxon_label
search in the t1.taxon_set
list of taxons.