Created
February 4, 2020 20:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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