如果一个节点是一对坐标,如何操作

2024-05-13 13:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要存储并操作(添加新节点、搜索等)一棵树,其中每个节点都是一对x,y坐标。我找到了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是节点的名称,数字是距离。在

或者

^{pr2}$

我不需要名字或距离,只需要一棵元组或列表树,例如:

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

但是最后一个输入返回语法错误,在关于ete2的教程中,我找不到任何类似的例子。作为一个变体,我想我可以将坐标保存为属性,但属性存储为字符串。我需要用坐标来操作,每次从一个字符串到另一个浮点,这是很棘手的。在


Tags: 模块字符串treehttp编辑距离列表属性
1条回答
网友
1楼 · 发布于 2024-05-13 13:32:00

您可以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)]

可以使用pickle复制、保存和恢复带注释的树:

^{pr2}$

相关问题 更多 >