我想在 Python 中将 Newick 文件 转换为分层对象(类似于 这篇文章 中发布的内容)。
我的输入是这样的 Newick 文件:
(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9
原帖逐字符解析字符串。为了也存储分支长度,我修改了 JavaScript 文件(来自here),如下所示:
var newick = '// (A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9',
stack = [],
child,
root = [],
node = root;
var na = "";
newick.split('').reverse().forEach(function(n) {
switch(n) {
case ')':
// ')' => begin child node
if (na != "") {
node.push(child = { name: na });
na = "";
}
stack.push(node);
child.children = [];
node = child.children;
break;
case '(':
// '(' => end of child node
if (na != "") {
node.push(child = { name: na });
na = "";
}
node = stack.pop();
// console.log(node);
break;
case ',':
// ',' => separator (ignored)
if (na != "") {
node.push(child = { name: na });
na = "";
}
break;
default:
// assume all other characters are node names
// node.push(child = { name: n });
na += n;
break;
}
});
console.log(node);
现在,我想将这段代码翻译成Python。
这是我的尝试(我知道这是不正确的):
class Node:
def __init__(self):
self.Name = ""
self.Value = 0
self.Children = []
newick = "(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,G:0.8)F:0.9"
stack = []
# root = []
# node = []
for i in list(reversed(newick)):
if i == ')':
if na != "":
node = Node()
node.Name = na
child.append(node)
na = ""
stack.append(node)
# insert logic
child = node.Children
# child.append(child)
elif i == '(':
if (na != ""):
child = Node()
child.Name = na
node.append(child)
na = ""
node = stack.pop()
elif i == ',':
if (na != ""):
node = Node()
node.Name = na
node.append(child)
na = ""
else:
na += n
由于我对 JavaScript 完全陌生,因此我在将代码“翻译”为 Python 时遇到了麻烦。特别是,我不明白以下几行:
child.children = [];
node = child.children;
我怎样才能在Python中正确地编写这个,并提取长度?
对 JavaScript 版本的一些评论:
if (na != '') ...
),这是很容易避免的。node
作为数组的变量名。当您对数组(或 Python 中的列表)使用复数词时,可读性会得到提高。由于最后一点,在翻译成Python之前需要先更正代码。它应该支持拆分名称/长度属性,允许它们中的任何一个都是可选的。此外,它可以为每个创建的节点分配 id 值,并添加
parentid
属性来引用节点的父节点。
我个人更喜欢使用递归编码而不是使用堆栈变量。此外,使用正则表达式 API,您可以轻松对输入进行标记以方便解析:
function parse(newick) {
let nextid = 0;
const regex = /([^:;,()\s]*)(?:\s*:\s*([\d.]+)\s*)?([,);])|(\S)/g;
newick += ";"
return (function recurse(parentid = -1) {
const children = [];
let name, length, delim, ch, all, id = nextid++;;
[all, name, length, delim, ch] = regex.exec(newick);
if (ch == "(") {
while ("(,".includes(ch)) {
[node, ch] = recurse(id);
children.push(node);
}
[all, name, length, delim, ch] = regex.exec(newick);
}
return [{id, name, length: +length, parentid, children}, delim];
})()[0];
}
// Example use:
console.log(parse("(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,G:0.8)F:0.9"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
import re
def parse(newick):
tokens = re.finditer(r"([^:;,()\s]*)(?:\s*:\s*([\d.]+)\s*)?([,);])|(\S)", newick+";")
def recurse(nextid = 0, parentid = -1): # one node
thisid = nextid;
children = []
name, length, delim, ch = next(tokens).groups(0)
if ch == "(":
while ch in "(,":
node, ch, nextid = recurse(nextid+1, thisid)
children.append(node)
name, length, delim, ch = next(tokens).groups(0)
return {"id": thisid, "name": name, "length": float(length) if length else None,
"parentid": parentid, "children": children}, delim, nextid
return recurse()[0]
# Example use:
print(parse("(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,G:0.8)F:0.9"))
关于 JavaScript 代码中的赋值
node = child.children
:这会将“指针”(即 node
)在正在创建的树中更深一层移动,以便在算法的下一次迭代中,任何新节点都会附加到该位置等级。使用 node = stack.pop()
,指针可在树中回溯到上一级。
以下代码可能不是 javascript 代码的精确翻译,但它可以按预期工作。有一些像“n”这样的问题没有被定义。我还添加了将节点名称解析为名称和值以及父字段。
您应该考虑使用已经存在的解析器,例如https://biopython.org/wiki/Phylo,因为它们已经为您提供了处理树的基础设施和算法。
class Node:
# Added parsing of the "na" variable to name and value.
# Added a parent field
def __init__(self, name_val):
name, val_str = name_val[::-1].split(":")
self.name = name
self.value = float(val_str)
self.children = []
self.parent = None
# Method to get the depth of the node (for printing)
def get_depth(self):
current_node = self
depth = 0
while current_node.parent:
current_node = current_node.parent
depth += 1
return depth
# String representation
def __str__(self):
return "{}:{}".format(self.name, self.value)
newick = "(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,G:0.8)F:0.9"
root = None
# na was not defined before.
na = ""
stack = []
for i in list(reversed(newick)):
if i == ')':
if na != "":
node = Node(na)
na = ""
if len(stack):
stack[-1].children.append(node)
node.parent = stack[-1]
else:
root = node
stack.append(node)
elif i == '(':
if (na != ""):
node = Node(na)
na = ""
stack[-1].children.append(node)
node.parent = stack[-1]
stack.pop()
elif i == ',':
if (na != ""):
node = Node(na)
na = ""
stack[-1].children.append(node)
node.parent = stack[-1]
else:
# n was not defined before, changed to i.
na += i
# Just to print the parsed tree.
print_stack = [root]
while len(print_stack):
node = print_stack.pop()
print(" " * node.get_depth(), node)
print_stack.extend(node.children)
最后打印位的输出如下:
F:0.9
A:0.1
B:0.2
E:0.5
C:0.3
D:0.4
G:0.8
这是该输入字符串的 pyparsing 解析器。它使用 pyparsing 的
nestedExpr
解析器生成器,并具有定义的内容参数,以便解析结果键值对,而不仅仅是简单的字符串(这是默认值)。
import pyparsing as pp
# suppress punctuation literals from parsed output
pp.ParserElement.inlineLiteralsUsing(pp.Suppress)
ident = pp.Word(pp.alphas)
value = pp.pyparsing_common.real
element = pp.Group(ident + ':' + value)
parser = pp.OneOrMore(pp.nestedExpr(content=pp.delimitedList(element) + pp.Optional(','))
| pp.delimitedList(element))
tests = """
(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9
"""
parsed_results = parser.parseString(tests)
import pprint
pprint.pprint(parsed_results.asList(), width=20)
给予:
[[['A', 0.1],
['B', 0.2],
[['C', 0.3],
['D', 0.4]],
['E', 0.5]],
['F', 0.9]]
请注意,用于解析实数的 pyparsing 表达式也会在解析时转换为 Python 浮点数。
有一个 Python 库
bigtree
,只需一行代码即可开箱即用地完成此操作。
from bigtree import newick_to_tree
newick_str = "(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9"
# Create the tree
root = newick_to_tree(newick_str, length_attr="length")
# Visualize the tree
root.show(attr_list=["length"])
这将导致输出
F [length=0.9]
├── A [length=0.1]
├── B [length=0.2]
└── E [length=0.5]
├── C [length=0.3]
└── D [length=0.4]
希望这有帮助!
免责声明:我是
bigtree
的作者:)