如何将Python字典转换为Newick格式?

时间:2018-04-24 13:32:02

标签: python python-2.7

我有一个以下形式的Python字典:

{
    'a': {'leaf1': 12, 'leaf2': 32},
    'b': {'a': 2, 'leaf3': 21, 'leaf4': 3},
    'c': {'leaf5': 5, 'leaf6': 7}
}

其中'a''b''c'是内部节点,leaf1 ... leaf6是叶节点(没有子节点), 1232221,... 7是给定节点或子树的分支长度。

我需要将此字典转换为Newick形式,以便使用外部应用程序绘制树。

Newick格式:

(((leaf1:12,leaf2:32):2,leaf3:21, leaf4:3),leaf5:5,leaf6:7);

我编写了以下代码,但没有成功:

def get_newick(self,dic):      
        roots=[node for node,children in dic.items() if sum([1 if len(child)>1 else 0 for child in children.keys()])==len(children.keys())]                       
        nonrooted=[node for node,children in dic.items() if sum([1 if len(child)>1 else 0 for child in children.keys()])!=len(children.keys())]        
        dic1={}
        for subtree in nonrooted:
            patt=[]
            for child,v in dic[subtree].items():
                if child in roots:
                    patt.append(tuple(["%s:%d"%(k,v) for k,v in dic[child].items()]))
                    roots.remove(child)
                elif len(child)>1:
                    patt.append("%s:%d"%(child,v))
            dic1[subtree]=patt         

1 个答案:

答案 0 :(得分:0)

解决问题的方式存在问题:在字典中,尚不清楚哪些节点位于顶层。这是一个可行的解决方案:

def newickify(node_to_children, root_node) -> str:
    visited_nodes = set()

    def newick_render_node(name, distance: float) -> str:
        assert name not in visited_nodes, "Error: The tree may not be circular!"

        if name not in node_to_children:
            # Leafs
            return F'{name}:{distance}'
        else:
            # Nodes
            visited_nodes.add(name)
            children = node_to_children[name]
            children_strings = [newick_render_node(child, children[child]) for child in children.keys()]
            children_strings = ",".join(children_strings)
            return F'({children_strings}){name}:{distance}'

    newick_string = newick_render_node(root_node, 0) + ';'

    # Ensure no entries in the dictionary are left unused.
    assert visited_nodes == set(node_to_children.keys()), "Error: some nodes aren't in the tree"

    return newick_string


node_to_children = {
    'root': {'b': 3, 'c': 5},
    'a': {'leaf1': 12, 'leaf2': 32},
    'b': {'a': 2, 'leaf3': 21, 'leaf4': 3},
    'c': {'leaf5': 5, 'leaf6': 7}
}

print(newickify(node_to_children, root_node='root'))

输出结果如下:

(((leaf1:12,leaf2:32)a:2,leaf3:21,leaf4:3)b:3,(leaf5:5,leaf6:7)c:5)root:0;
相关问题