簡體   English   中英

以 newick 格式保存 NetworkX 樹

[英]Save NetworkX tree in newick format

我在networkx創建了一個圖形並獲得了它的 bfs 樹。

G = nx.Graph()

# build a graph

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

現在我想將樹以newick 格式保存到文件中。 做到這一點的最佳方法是什么?

受到這個答案的啟發,我做了這樣的事情:

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

受到@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)

它似乎工作...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM