def swap_tree(tree): # make safe tree if not '"' in tree: tree = nwk.safe_newick_string(tree) # swap two nodes of the tree nodes = list(nwk.nodes_in_tree(tree))[1:] random.shuffle(nodes) # choose two nodes to be swapped nodeA = nodes.pop(0) # get another node that can be interchanged while nodes: nodeB = nodes.pop(0) if nodeB in nodeA or nodeA in nodeB: pass else: break tree = tree.replace(nodeA+',', '#dummyA#,') tree = tree.replace(nodeA+')', '#dummyA#)') tree = tree.replace(nodeB+',', '#dummyB#,') tree = tree.replace(nodeB+')', '#dummyB#)') tree = tree.replace('#dummyA#', nodeB) tree = tree.replace('#dummyB#', nodeA) return nwk.sort_tree(tree).replace('"','')
def swap_tree(tree): # make safe tree if not '"' in tree: tree = nwk.safe_newick_string(tree) # swap two nodes of the tree nodes = list(nwk.nodes_in_tree(tree))[1:] random.shuffle(nodes) # choose two nodes to be swapped nodeA = nodes.pop(0) # get another node that can be interchanged while nodes: nodeB = nodes.pop(0) if nodeB in nodeA or nodeA in nodeB: pass else: break tree = tree.replace(nodeA + ',', '#dummyA#,') tree = tree.replace(nodeA + ')', '#dummyA#)') tree = tree.replace(nodeB + ',', '#dummyB#,') tree = tree.replace(nodeB + ')', '#dummyB#)') tree = tree.replace('#dummyA#', nodeB) tree = tree.replace('#dummyB#', nodeA) return nwk.sort_tree(tree).replace('"', '')
def all_rooted_binary_trees(*taxa): """ Compute all rooted trees. Notes ----- This procedure yields all rooted binary trees for a given set of taxa, as described in :bib:`Felsenstein1978`. It implements a depth-first search. """ if len(taxa) <= 2: yield '(' + ','.join(taxa) + ');' # make queue with taxa included and taxa to be visited queue = [('(' + ','.join(taxa[:2]) + ')', list(taxa[2:]))] out = [] while queue: # add next taxon tree, rest = queue.pop() if rest: next_taxon = rest.pop() nodes = list(nwk.nodes_in_tree(tree)) random.shuffle(nodes) for node in nodes: new_tree = tree.replace(node, '(' + next_taxon + ',' + node + ')') r = [x for x in rest] random.shuffle(r) queue += [(new_tree, r)] if not rest: yield new_tree
def all_rooted_binary_trees(*taxa): """ Compute all rooted trees. Notes ----- This procedure yields all rooted binary trees for a given set of taxa, as described in :bib:`Felsenstein1978`. It implements a depth-first search. """ if len(taxa) <= 2: yield '('+','.join(taxa)+');' # make queue with taxa included and taxa to be visited queue = [('('+','.join(taxa[:2])+')', list(taxa[2:]))] out = [] while queue: # add next taxon tree, rest = queue.pop() if rest: next_taxon = rest.pop() nodes = list(nwk.nodes_in_tree(tree)) random.shuffle(nodes) for node in nodes: new_tree = tree.replace(node, '('+next_taxon+','+node+')') r = [x for x in rest] random.shuffle(r) queue += [(new_tree, r)] if not rest: yield new_tree