Adding new nodes to a Tree

47 views
Skip to first unread message

hsa...@cs.stonybrook.edu

unread,
Nov 9, 2014, 10:05:17 PM11/9/14
to dendrop...@googlegroups.com

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..

Sourya Bhattacharyya

unread,
Jun 16, 2015, 5:14:03 AM6/16/15
to dendrop...@googlegroups.com
In addition, you may use the following statement:

n.parent_node = cp

This will explicitly set the parent information of the node n

Then you apply 

t1.update_splits()

and check whether the tree t1 has the new taxon information.

Please notify whether it works.

Jeet Sukumaran

unread,
Jun 16, 2015, 8:25:20 AM6/16/15
to dendrop...@googlegroups.com
Both approaches work fine:

~~~
import dendropy

t1 = dendropy.Tree.get(
data="(8,3);",
schema="newick")
cp = t1.find_node_with_taxon_label("3")
n1 = dendropy.Node(taxon=t1.taxon_namespace.require_taxon(label="5"))
cp.add_child(n1)
n2 = dendropy.Node(taxon=t1.taxon_namespace.require_taxon(label="6"))
cp.add_child(n2)
print(t1.as_string(schema="newick"))
~~

or

~~
import dendropy

t1 = dendropy.Tree.get(
data="(8,3);",
schema="newick")
cp = t1.find_node_with_taxon_label("3")
n1 = dendropy.Node(taxon=t1.taxon_namespace.require_taxon(label="5"))
n1.parent_node = cp
n2 = dendropy.Node(taxon=t1.taxon_namespace.require_taxon(label="6"))
n2.parent_node = cp
print(t1.as_string(schema="newick"))
~~
> --
> You received this message because you are subscribed to the Google
> Groups "DendroPy Users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to dendropy-user...@googlegroups.com
> <mailto:dendropy-user...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.

--



--------------------------------------
Jeet Sukumaran
--------------------------------------
jeetsu...@gmail.com
--------------------------------------
Blog/Personal Pages:
http://jeetworks.org/
GitHub Repositories:
http://github.com/jeetsukumaran
Photographs (as stream):
http://www.flickr.com/photos/jeetsukumaran/
Photographs (by galleries):
http://www.flickr.com/photos/jeetsukumaran/sets/
--------------------------------------

Reply all
Reply to author
Forward
0 new messages