This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to remove zero-length edges in newick tree

I want to know whether there is quick way to remove zero-length edges in newick tree, like

input: ((a:1,b:1)Node_0:0,c:1);

output:(a:1,b:1,c:1);

Thanks for any help

phylogenetics algorithm

yes, newick is a format to record a rooted tree

1 answer

Probably there is a slicker way... but this seems to work.

#!/bin/env python3

import ete3 as ete

input = "((a:1,b:1)z:0,c:1);"

# http://etetoolkit.org/docs/latest/tutorial/tutorial_trees.html#reading-and-writing-newick-trees
tree = ete.Tree(newick=input, format=1)

print("Before:", tree.write(format=1))

for node in list(tree.search_nodes(dist=0)):
    parent: ete.Tree
    parent = node.up
    if parent:
        for c in list(parent.get_children()):
            c.detach()
            if (c == node):
                for d in c.get_children():
                    parent.add_child(d)
            else:
                parent.add_child(c)

output = tree.write(format=1)
print("After: ", output)

Thanks very much! That works for me.

Log in to answer this question.