【发布时间】:2015-07-29 11:38:13
【问题描述】:
我有一个非常大的文件(15 亿行),格式如下:
1 67108547 67109226 gene1$transcript1 0 + 1 0
1 67108547 67109226 gene1$transcript1 0 + 2 1
1 67108547 67109226 gene1$transcript1 0 + 3 3
1 67108547 67109226 gene1$transcript1 0 + 4 4
.
.
.
1 33547109 33557650 gene2$transcript1 0 + 239 2
1 33547109 33557650 gene2$transcript1 0 + 240 0
.
.
.
1 69109226 69109999 gene1$transcript1 0 + 351 1
1 69109226 69109999 gene1$transcript1 0 + 352 0
我想要做的是根据第 4 列上的标识符重新组织/排序此文件。该文件由块组成。如果连接第 4、1、2 和 3 列,则为每个块创建唯一标识符。这是字典 all_exons 的键,值是一个 numpy 数组,其中包含第 8 列的所有值。然后我有第二个字典 unique_identifiers 以属性为键从第 4 列开始,并为相应的块标识符列表赋值。作为输出,我以以下形式编写文件:
>gene1
0
1
3
4
1
0
>gene2
2
0
我已经编写了一些代码(见下文),但我的实现速度很慢。运行大约需要 18 个小时。
import os
import sys
import time
from contextlib import contextmanager
import pandas as pd
import numpy as np
def parse_blocks(bedtools_file):
unique_identifiers = {} # Dictionary with key: gene, value: list of exons
all_exons = {} # Dictionary contatining all exons
# Parse file and ...
with open(bedtools_file) as fp:
sp_line = []
for line in fp:
sp_line = line.strip().split("\t")
current_id = sp_line[3].split("$")[0]
identifier="$".join([sp_line[3],sp_line[0],sp_line[1],sp_line[2]])
if(identifier in all_exons):
item = float(sp_line[7])
all_exons[identifier]=np.append(all_exons[identifier],item)
else:
all_exons[identifier] = np.array([sp_line[7]],float)
if(current_id in unique_identifiers):
unique_identifiers[current_id].add(identifier)
else:
unique_identifiers[current_id] =set([identifier])
return unique_identifiers, all_exons
identifiers, introns = parse_blocks(options.bed)
w = open(options.out, 'w')
for gene in sorted(list(identifiers)):
w.write(">"+str(gene)+"\n")
for intron in sorted(list(identifiers[gene])):
for base in introns[intron]:
w.write(str(base)+"\n")
w.close()
如何改进上述代码以加快运行速度?
【问题讨论】:
-
了解如何让您的代码运行得更快的最佳方法是通过分析:stackoverflow.com/questions/582336/…
-
澄清一下:最终目标是以您发布的格式获取输出文件,还是需要将数据组织在字典中?您是否在此文件中也有带有“transcript2”的条目,还是总是“transcript1”?
-
最终目标是获取输出文件。我使用字典的原因是我在生成输入文件时通过管道传输它以节省磁盘空间。不,我没有带有成绩单2 的条目(对不起,我忘了提及这一点)。
-
我做了一个分析,似乎代码在连接时延迟(numpy.core.multiarray.concatenate)。所以问题似乎在于附加到numpy数组......
-
@fitziano:速度比较怎么样?熊猫解决方案与您的方法相比会很有趣......
标签: python numpy dictionary