def extend(t, P, Q): n = len(t) s = canonical_newick_string(t.write(format=9)) # 1: add the leaf to an external arc # P[m+1] = factor(((1-a)/(m-a))*P[m]) leaves = [node for node in t] for node in leaves: x = node.add_child(name=node.name) y = node.add_child(name=n + 1) z = t.copy() # print "case 1", s, z.write(format=9) Q[canonical_newick_string(z.write(format=9))] = factor( ((1 - a) / (n - a)) * P[s]) x.detach() y.detach() # 2: add the leaf to an internal arc # P[m+1] = factor((g/(m-a))*P[m]) internal = [node for node in t.iter_descendants() if not node.is_leaf()] for node in internal: node.add_features(name="internal") x = t.copy("deepcopy") node.del_feature("name") y = x.search_nodes(name="internal")[0] parent = y.up old = y.detach() new = Tree() new.add_child(old) new.add_child(name=n + 1) parent.add_child(new) # print "case 2", s, x.write(format=9) Q[canonical_newick_string(x.write(format=9))] = factor( (g / (n - a)) * P[s]) # 3: add the leaf to a new root # P[m+1] = factor(g/(m-a)*P[m]) x = t.copy() y = Tree() y.add_child(x) y.add_child(name=n + 1) # print "case 3", s, y.write(format=9) Q[canonical_newick_string(y.write(format=9))] = factor(g / (n - a) * P[s]) # 4: add the leaf to the root # P[m+1] = factor(((len(t.children)-1)*a-g)/(m-a)*P[m]) if not t.is_leaf(): x = t.copy() x.add_child(name=n + 1) # print "case 4r", s, x.write(format=9) Q[canonical_newick_string(x.write(format=9))] = factor( ((len(t.children) - 1) * a - g) / (n - a) * P[s]) # 4: add the leaf to an internal node # P[m+1] = factor(((len(node.children)-1)*a-g)/(m-a)*P[m]) for node in t.iter_descendants(): if not node.is_leaf(): y = node.add_child(name=n + 1) # print "case 4i", s, t.write(format=9) Q[canonical_newick_string(t.write(format=9))] = factor( ((len(node.children) - 2) * a - g) / (n - a) * P[s]) y.detach()
def generate(taxa): if len(taxa) == 3: return [Tree('(' + ','.join(taxa) + ');')] else: res = [] sister = Tree('(' + taxa[-1] + ');') for tree in generate(taxa[:-1]): for node in tree.traverse('preorder'): if not node.is_root(): node.up.add_child(sister) node.detach() sister.add_child(node) res.append(copy.deepcopy(tree)) node.detach() sister.up.add_child(node) sister.detach() return res