2014-03-02 23 views
1

我需要存儲並操作(添加新節點,搜索等)樹,其中每個節點都是一對x,y座標。我發現ete2模塊可以與樹一起工作,但我無法理解如何將節點保存爲元組或座標列表。 ete2可以嗎?ete2如果一個節點是一對座標,如何操作

編輯:

我也跟着教程這裏http://pythonhosted.org/ete2/tutorial/tutorial_trees.html#trees 要創建一個簡單的樹:

t1 = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);") 

其中A,B,C是一個節點的名稱和數量是有距離的。

t2 = Tree("(A,B,(C,D));") 

我不需要名字或距離,但元組或列表的一棵樹,像水木清華:

t3 = Tree("([12.01, 10.98], [15.65, 12.10],([21.32, 6.31], [14.53, 10.86]));") 

但是最後輸入返回語法錯誤,在關於教程ete2我找不到任何類似的例子。作爲一個變體,我認爲我可以將座標保存爲屬性,但將屬性保存爲字符串。我需要使用座標進行操作,每次從字符串到浮點數都是非常棘手的,反之亦然。

+0

你應該有一些代碼,讓我們看看你都試過 – PyNEwbie

+0

我加入它,@PyNEwbie – Olga

回答

2

您可以使用任何類型的數據annotate ete trees。只需給每個節點命名,使用這些名稱創建一個樹結構,然後用座標對樹進行註釋。

from ete2 import Tree 

name2coord = { 
'a': [1, 1], 
'b': [1, 1], 
'c': [1, 0], 
'd': [0, 1], 
} 

# Use format 1 to read node names of all internal nodes from the newick string 
t = Tree('((a:1.1, b:1.2)c:0.9, d:0.8);', format=1)  

for n in t.get_descendants(): 
    n.add_features(coord = name2coord[n.name]) 

# Now you can operate with the tree and node coordinates in a very easy way: 
for leaf in t.iter_leaves(): 
    print leaf.name, leaf.coord 
# a [1, 1] 
# b [1, 1] 
# d [0, 1] 

print t.search_nodes(coord=[1,0]) 
# [Tree node 'c' (0x2ea635)] 

您可以複製,使用泡菜保存和恢復註釋樹:

t.copy('cpickle') 
# or 
import cPickle 
cPickle.dump(t, open('mytree.pkl', 'w')) 
tree = cPickle.load(open('mytree.pkl')) 
相關問題