def __init__(self, weight=1.0, rooted = True, name='') : self.t = Tree(weight=weight, rooted = rooted, name=name)
class TreeBuilder(object) : """ A basic helper for building BioPython trees. Use: - tb = TreeBuilder() - Create some terminals via leaf = tb.createLeaf(name) - use mergeNodes to successively merge nodes. - Call tb.finalize(root-node) to get the tree """ def __init__(self, weight=1.0, rooted = True, name='') : self.t = Tree(weight=weight, rooted = rooted, name=name) def createLeaf(self, name) : """ Create a new leaf. :param name: taxon name :returns: node""" nd = NodeData() nd.taxon = name leaf = Nodes.Node(nd) self.t.add(leaf, None) return leaf def newNode(self) : nd = NodeData() node = Nodes.Node(nd) self.t.add(node, None) return node def mergeNodes(self, subtrees) : """ Join subtrees in subtrees into one sub-tree. Each element in subtrees is a (node,branch) pair, where branch is the length of the branch connecting the node to its parent. :param subtrees: sequence of [node,branch] :returns: node""" nd = NodeData() node = Nodes.Node(nd) self.t.add(node, None) for n1,h1 in subtrees: n1.set_prev(node.id) n1.data.branchlength = h1 node.add_succ([x.id for x,h in subtrees]) return node def finalize(self, rootNode) : """ Convert a node to a proper tree with root rootNode. :param rootNode: node :returns: biopython tree """ t = self.t rr = t.node(t.root) if rootNode.succ : rr.set_succ(rootNode.succ) for p in rootNode.succ : t.node(p).set_prev(t.root) if hasattr(rootNode.data,attributesVarName) : rr.data.attributes = rootNode.data.attributes t.kill(rootNode.id) else : rr.set_succ([rootNode.id]) rootNode.set_prev(t.root) return t