def __load_tree_txt__(self, fn): tree = Phylo.BaseTree.Tree() try: rows = [ l.decode('utf-8').rstrip().split("\t")[0] for l in open(fn, 'rb') ] except IOError: raise IOError() clades = [r.split(self.lev_sep) for r in rows] tree = BTree() tree.root = BClade() def add_clade_rec(father, txt_tree): fl = set([t[0] for t in txt_tree]) father.clades = [] for c in fl: nclade = BClade(branch_length=1.0, name=c) father.clades.append(nclade) children = [ t[1:] for t in txt_tree if len(t) > 1 and t[0] == c ] if children: add_clade_rec(nclade, children) add_clade_rec(tree.root, clades) self.ignore_branch_len = 1 return tree.as_phyloxml()
def __load_tree_txt__( self, fn ): tree = Phylo.BaseTree.Tree() try: rows = [l.decode('utf-8').rstrip().split("\t")[0] for l in open(fn, 'rb')] except IOError: raise IOError() clades = [r.split(lev_sep) for r in rows] tree = BTree() tree.root = BClade() def add_clade_rec( father, txt_tree ): fl = set([t[0] for t in txt_tree]) father.clades = [] for c in fl: nclade = BClade( branch_length = 1.0, name = c ) father.clades.append( nclade ) children = [t[1:] for t in txt_tree if len(t)>1 and t[0] == c] if children: add_clade_rec( nclade, children ) add_clade_rec( tree.root, clades ) self.ignore_branch_len = 1 return tree.as_phyloxml()
def exp_newick(inp, labels, outfile, tree_format='phyloxml'): n_leaves = int(inp[-1][-1]) from Bio import Phylo import collections from Bio.Phylo.BaseTree import Tree as BTree from Bio.Phylo.BaseTree import Clade as BClade tree = BTree() tree.root = BClade() subclades = {} sb_cbl = {} for i, (fr, to, bl, nsub) in enumerate(inp): if fr < n_leaves: fr_c = BClade(branch_length=-1.0, name=labels[int(fr)]) subclades[fr] = fr_c sb_cbl[fr] = bl if to < n_leaves: to_c = BClade(branch_length=-1.0, name=labels[int(to)]) subclades[to] = to_c sb_cbl[to] = bl for i, (fr, to, bl, nsub) in enumerate(inp): fr_c = subclades[fr] to_c = subclades[to] cur_c = BClade(branch_length=bl) cur_c.clades.append(fr_c) cur_c.clades.append(to_c) subclades[i + n_leaves] = cur_c def reset_rec(clade, fath_bl): if clade.branch_length < 0: clade.branch_length = fath_bl return for c in clade.clades: reset_rec(c, clade.branch_length) clade.branch_length = fath_bl - clade.branch_length tree.root = cur_c reset_rec(tree.root, 0.0) tree.root.branch_length = 0.0 Phylo.write(tree, outfile, tree_format)