-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprune_long_tips.py
More file actions
executable file
·63 lines (49 loc) · 1.83 KB
/
prune_long_tips.py
File metadata and controls
executable file
·63 lines (49 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
if __name__ == '__main__':
import newick3, phylo3, numpy, sys
if len(sys.argv) < 3:
print "usage: remove_badtips.py <treefile> <maxdevfactor> [keep=\"<tax1, tax2, ...>\"]"
sys.exit()
treefname = sys.argv[1]
treefile = open(treefname, "r")
tree = newick3.parse(treefile.readline())
maxdevfactor = int(sys.argv[2])
if len(sys.argv) > 3:
keepnames_str = sys.argv[3].split("keep=",1)[1]
keepnames = [n.strip() for n in keepnames_str.split(",")]
else:
keepnames = []
lengths = [t.length for t in tree.leaves()]
avg = numpy.mean(lengths)
for tip in tree.leaves():
if tip.parent == tree:
continue
if tip.length > avg * maxdevfactor:
if tip.label not in keepnames:
print "pruning " + tip.label
tip.prune()
# compress knuckle if there is one
# if len(parent.children) == 1:
# child = parent.children[0]
# if child.label != None:
# rightlabel = child.label
# else:
# rightlabel = ", ".join([leaf.label for leaf in child.leaves()])
# print "compressing a knuckle in the tree: " + leftlabel + " | " + rightlabel
# pp = parent.parent
# pp.remove_child(parent)
# pp.add_child(child)
#nodes_to_remove = []
for n in tree.descendants():
nc = n
while (not nc.istip) and len(nc.children) == 0:
print "pruning an empty tip"
np = nc.parent
nc.prune()
if np:
nc = np
else:
break
outfile = open(treefname.rsplit(".tre",1)[0] + ".pruned.tre","w")
outfile.write(newick3.tostring(tree) + ";")
outfile.close()