以newick格式保存NetworkX树

时间:2017-09-27 09:37:33

标签: python networkx

我在networkx中创建了一个图表并获取了它的bfs树。

G = nx.Graph()

# build a graph

tree = nx.bfs_tree(G, '1')

现在我想将newick format中的树保存到文件中。最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

this answer的启发,我做了类似的事情:

import networkx as nx
import matplotlib.pyplot as plt

def recursive_search(dict, key):
    if key in dict:
        return dict[key]
    for k, v in dict.items():
        item = recursive_search(v, key)
        if item is not None:
            return item

def bfs_edge_lst(graph, n):
    return list(nx.bfs_edges(graph, n))

def load_graph(filename):
    G = nx.Graph()
    # build the graph
    return G

def tree_from_edge_lst(elst):
    tree = {'1': {}}
    for src, dst in elst:
        subt = recursive_search(tree, src)
        subt[dst] = {}
    return tree

def tree_to_newick(tree):
    items = []
    for k in tree.keys():
        s = ''
        if len(tree[k].keys()) > 0:
            subt = tree_to_newick(tree[k])
            if subt != '':
                s += '(' + subt + ')'
        s += k
        items.append(s)
    return ','.join(items)

g = load_graph('dataset.txt')
elst = bfs_edge_lst(g, '1')
tree = tree_from_edge_lst(elst)
newick = tree_to_newick(tree) + ';'

答案 1 :(得分:0)

受@hklel的回答启发,我编写了以下代码:

import networkx as nx

def tree_to_newick(g, root=None):
    if root is None:
        roots = list(filter(lambda p: p[1] == 0, g.in_degree()))
        assert 1 == len(roots)
        root = roots[0][0]
    subgs = []
    for child in g[root]:
        if len(g[child]) > 0:
            subgs.append(tree_to_newick(g, root=child))
        else:
            subgs.append(child)
    return "(" + ','.join(subgs) + ")"

tree_to_newick(nx.Graph(), None)

似乎可行...