Skip to content

Instantly share code, notes, and snippets.

@benfulton
Created February 4, 2020 20:46
Show Gist options
  • Save benfulton/a10583c8ae41897489d415c066c7579f to your computer and use it in GitHub Desktop.
Save benfulton/a10583c8ae41897489d415c066c7579f to your computer and use it in GitHub Desktop.
Extend the leaf branch lengths of a Newick tree so all the paths are the same length
from Bio import Phylo
from io import StringIO
import sys
treedata = sys.argv[1]
handle = StringIO(treedata)
tree = Phylo.read(handle, "newick")
out = StringIO()
def path_length(tree, node):
return sum(y.branch_length if y.branch_length else 0 for y in tree.get_path(node))
max_length = max([path_length(tree, x) for x in tree.get_terminals()])
for leaf in tree.get_terminals():
q = path_length(tree, leaf)
leaf.branch_length += max_length - q
Phylo.write([tree], out, "newick")
print(out.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment