I'm very new to DendroPy. What I want to do seems simple but I can't figure how to do it correctly and I didn't find anything on the internet.
I want to add a node midway between two nodes in a existing rooted dendropy tree.
from dendropy import Tree, Taxon, Node
t1 = Tree.get_from_string(
"(((sp1: 0.35, sp2: 0.15):0.75, sp3:1): 0.5, (sp4: 0.5, sp5: 0.05)MRCA_sp4&sp5: 1)root;",
"newick", rooting='force-rooted'
)
t1.print_plot()
mrca = t1.mrca(taxon_labels=["sp4", "sp5"])
print(mrca.description())
Tree and MRCA node description
The MRCA of sp4 and sp5 is found correctly. Now I'm trying to add a node midway between MRCA and root, using the code below:
def add_node_midway_between_2_nodes(lowernode, taxon_label=None, node_label=None):
newtaxon = Taxon(label=taxon_label)
newnode = Node(taxon=newtaxon, label=node_label)
newnode.parent_node = lowernode.parent_node
newnode.edge_length = lowernode.edge_length/2
lowernode.parent_node = newnode
lowernode.edge_length = newnode.edge_length
return newnode
node = add_node_midway_between_2_nodes(mrca, node_label="midway between root and MRCA sp4&sp5")
t1.print_plot()
str_t1 = t1.as_string(schema='newick')
print(str_t1)
Tree with a node between root and MRCA sp4&sp5
[&R] (((sp1:0.35,sp2:0.15):0.75,sp3:1.0):0.5,((sp4:0.5,sp5:0.05)MRCA_sp4&sp5:0.5)midway_between_root_and_MRCA_sp4&sp5:0.5)root;
Looking at the plot and at the string it seems to have worked. But then when I try to compute the MRCA of sp4 et sp5 again, it doesn't find "MRCA sp4&sp5" anymore but the root node.
mrca = t1.mrca(taxon_labels=["sp4", "sp5"])
print(mrca.description())
Output = Description of root node
Going through parent_node from sp5, I do still find "MRCA sp4&sp5".
Out of desperation, I tried to redo the tree using the string str_t1, but it doesn't work either and even gives me another result (just as incorrect): the node "midway between root and MRCA sp4&sp5"
t1 = Tree.get_from_string(
str_t1,
"newick", rooting='force-rooted'
)
mrca = t1.mrca(taxon_labels=["sp4", "sp5"])
print(mrca.description())
Output = description of node "midway between root and MRCA sp4&sp5"
So what is a clean way to add a node midway between two nodes, that doesn't create weird events afterward?
Thank you very much
Your code is mostly working but you should
update_taxon_namespace
andupdate_bipartitions
to apply any changes of a tree topology correctly as it was recommended in documentation. So, in your case, it would look like this:NB!
Updating taxa namespace should be prior to updating bipartitions as the latter has to use a correct
TaxonNamespace
. Otherwise, you still get the strange behavior.Howbeit, it is better to use builtin
Node
methods for fine tree reconstruction. For instance, I would rewrite the function such way:Nonetheless,
Tree.mrca
still shows an improper node:Although, this is not a bug in the case as this is just a feature of the method. Due to this in the source code:
For example, if we add a child to the new node, it works well: