python-3.x - 按序列大小对 fasta 进行排序

标签 python-3.x sorting bioinformatics fasta

我目前想按序列大小对 hudge fasta 文件(+10**8 行和序列)进行排序。 fasta 是生物学中用于存储序列(遗传或蛋白质)的明确定义的格式:

>id1

sequence 1 # 可以在几行

>id2

序列 2

...

我运行了一个以 tsv 格式提供给我的工具:

标识符、长度和标识符的字节位置。

现在我正在做的是按长度列对这个文件进行排序,然后我解析这个文件并使用 seek 来检索相应的序列,然后将它附加到一个新文件。

# this fonction will get the sequence using seek
def get_seq(file, bites):  

    with open(file) as f_:
        f_.seek(bites, 0) # go to the line of interest
        line = f_.readline().strip() # this line is the begin of the 
                                     #sequence
        to_return = "" # init the string which will contains the sequence

        while not line.startswith('>') or not line:  # while we do not 
                                                     # encounter another identifiant
        to_return += line
        line = f_.readline().strip()

    return to_return
# simply append to a file the id and the sequence
def write_seq(out_file, id_, sequence):

    with open(out_file, 'a') as out_file:
        out_file.write('>{}\n{}\n'.format(id_.strip(), sequence))

# main loop will parse the index file and call the function defined below
with open(args.fai) as ref:

    indice = 0

    for line in ref:

        spt = line.split()
        id_ = spt[0]
        seq = get_seq(args.i, int(spt[2]))
        write_seq(out_file=args.out, id_=id_, sequence=seq)

我的问题是以下真的很慢这正常吗(需要几天)?我有另一种方法吗?我不是一个纯粹的信息学家,所以我可能会漏掉一些要点,但我相信索引文件并使用搜索是实现这一目标的最佳方式,我错了吗?

最佳答案

似乎为每个序列打开两个文件可能对运行时间有很大影响。您可以将文件句柄而不是文件名传递给您的获取/写入函数,但我建议使用已建立的 fasta 解析器/索引器,如 biopython 或 samtools。这是一个使用 samtools 的(未经测试的)解决方案:

subprocess.call(["samtools", "faidx", args.i])
with open(args.fai) as ref:

    for line in ref:

        spt = line.split()
        id_ = spt[0]
        subprocess.call(["samtools", "faidx", args.i, id_, ">>", args.out], shell=True)

关于python-3.x - 按序列大小对 fasta 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41239521/

相关文章:

python - 无法执行lua代码,从文件读取

sorting - ASPxGridView 分组汇总排序 - 对里面的内容进行排序,而不是对外面的汇总进行排序

c++ - 使用 vector 的合并排序 C++

algorithm - Bioperl 程序执行错误

python-3.x - 如何使用python删除GKE(Google Kubernetes Engine)集群?

python-3.x - 简单的 salesforce 批量更新插入未按预期工作

java - Java8 中使用多个键对映射列表进行排序

python - 使用python切片一行文本文件

bash - 在 UNIX 中重命名 fasta/fastq 文件中的条目

python - 是否有任何支持 Python 3 语法的 IDE?