将树状图保存为newick格式

时间:2015-01-29 18:42:44

标签: python scipy dendrogram

如何将scipy生成的树形图保存到Newick format

1 个答案:

答案 0 :(得分:13)

您需要链接矩阵Z,它是scipy树形图函数的输入,并将其转换为Newick格式。此外,您还需要一个列表' leaf_names'用你的叶子的名字。这是一个能完成这项工作的功能:

from scipy.cluster import hierarchy
def getNewick(node, newick, parentdist, leaf_names):
    if node.is_leaf():
        return "%s:%.2f%s" % (leaf_names[node.id], parentdist - node.dist, newick)
    else:
        if len(newick) > 0:
            newick = "):%.2f%s" % (parentdist - node.dist, newick)
        else:
            newick = ");"
        newick = getNewick(node.get_left(), newick, node.dist, leaf_names)
        newick = getNewick(node.get_right(), ",%s" % (newick), node.dist, leaf_names)
        newick = "(%s" % (newick)
        return newick

tree = hierarchy.to_tree(Z,False)
getNewick(tree, "", tree.dist, leaf_names)