0

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.

Hirak Sarkar
  • 479
  • 1
  • 4
  • 18
  • If I use your code and to a `print t1` after all, i get `(8,(5)3)`. That seems to have a leaf "5" appended to the branch "3". – xbello Nov 11 '14 at 08:56
  • @xbello Okay the problem is it shows that it as appended as a child but the object seems to be missing for example if now I execute `cp1 = t1.find_node_with_taxon_label('5')` it is showing nothing. That means If I want to add another child to it I can not do it anymore. – Hirak Sarkar Nov 11 '14 at 23:46

1 Answers1

1

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.

xbello
  • 7,223
  • 3
  • 28
  • 41
  • Great! I found that in the code 10 minutes ago. But thanks a lot for the answer. Good thing is dendropy tag starts with this question. Now it would be easy to find things. – Hirak Sarkar Nov 12 '14 at 08:18