1
votes

I have a Python dictionary in the following form:

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

where 'a', 'b', 'c' are internal nodes, and leaf1 ... leaf6 are leaf nodes(don't have children), and 12, 32, 2, 21, ... 7 are branch lengths of given node or subtree.

I need to convert this dictionary to Newick form in order to draw a tree using external applications.

Newick format:

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

I wrote the following code, but without success:

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
You want to convert a string into a string, or a dictionary into a string? - Mad Physicist
What happened to the internal node names? - Mad Physicist
Possible duplicate of Convert csv to Newick tree - rafaelc
The output format is not clear. Please explain it, and also post any attempts you have made to solve this problem on your own. - Mad Physicist
@RafaelC a dictionary and csv arent very similar at all.. - Grant Williams

1 Answers

0
votes

There is a problem with the way you approach the problem: In your dictionary, it is not clear which nodes are on the top level. This is a solution that works:

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'))

This is what the output looks like:

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