Skip to main content
 首页 » 编程设计

python之在 Python 中使用大字典优化性能

2024年10月25日10EasonJim

背景: 我正在尝试创建一个简单的 python 程序,它允许我通过转录组坐标获取转录本的一部分,并获取其序列和基因组坐标。 我不是经验丰富的生物信息学家或程序员,更像是生物学家,但我考虑这样做的方式是将每个转录本拆分为其核苷酸,并与每个核苷酸一起存储在一个元组中,包括其基因组坐标和内部坐标成绩单。这样我就可以使用 python 获取特定转录本的一部分(比如最后 200 个核苷酸)并获取序列和构建它的各种基因组窗口。最终目标比这更复杂(最终程序会收到一组以距离翻译起始位点(ATG)的距离形式的坐标,并将每个坐标随机分配给一个随机转录本,并输出序列和基因组坐标)

这是我为此编写的代码,它从包含每个外显子的坐标和序列的 BED 文件中获取信息(以及转录长度、起始 (ATG) 密码子位置、终止密码子位置等信息) :

from __future__ import print_function 
from collections import OrderedDict 
from collections import defaultdict 
import time 
import sys 
import os 
 
with open("canonicals_metagene_withseq.bed") as f: 
    for line in f: 
        content.append(line.strip().split()) 
        all_transcripts.append(line.strip().split()[3]) 
all_transcripts = list(OrderedDict.fromkeys(all_transcripts)) 
genes = dict.fromkeys(all_transcripts) 
n=0 
for line in content: 
    n+=1 
    if genes[line[3]] is not None: 
        seq=[] 
        i=0 
        for nucleotide in line[14]: 
            seq.append((nucleotide,int(line[9])+i,int(line[1])+i)) 
            i+=1 
        if line[5] == '+': 
            genes[line[3]][5].extend(seq) 
        elif line[5] == '-': 
            genes[line[3]][5] = seq + genes[line[3]][5]  
    else: 
        seq=[] 
        i=0 
        for nucleotide in line[14]: 
            seq.append((nucleotide,int(line[9])+i,int(line[1])+i)) 
            i+=1 
        genes[line[3]] = [line[0],line[5],line[11],line[12],line[13],seq] 
    sys.stdout.write("\r") 
    sys.stdout.write(str(n)) 
    sys.stdout.flush() 

这是 BED 文件外观的示例:

Chr Start   End Transcript_ID   Exon_Type   Strand  Ex_Start    Ex_End  Ex_Length   Ts_Start    Ts_End  Ts_Length   ATG Stop    Sequence 
chr1    861120  861180  uc001abw.1      5UTR    +       0       60      80      0       60      2554    80      2126    GCAGATCCCTGCGG 
chr1    861301  861321  uc001abw.1      5UTR    +       60      80      80      60      80      2554    80      2126    GGAAAAGTCTGAAG 
chr1    861321  861393  uc001abw.1      CDS     +       0       72      2046    80      152     2554    80      2126    ATGTCCAAGGGGAT 
chr1    865534  865716  uc001abw.1      CDS     +       72      254     2046    152     334     2554    80      2126    AACCGGGGGCGGCT 
chr1    866418  866469  uc001abw.1      CDS     +       254     305     2046    334     385     2554    80      2126    AGTCCACACCCACT 

我想创建一个字典,其中每个转录本 id 是键,存储的值是转录本的长度、它所在的染色体、链、ATG 的位置、终止密码子的位置最重要的是 - 序列的元组列表。

基本上,代码可以工作。但是,一旦字典开始变大,它的运行速度就会非常非常慢。

所以,我想知道的是,我怎样才能让它运行得更快?目前它在 bed 文件的第 60,000 行左右变得非常慢。也许有一种更有效的方法来做我想做的事情,或者只是一种更好的方法来为此存储数据。

BED 文件是使用 UCSC 表中的 awk 自定义制作的。

编辑: 分享我学到的... 我现在知道瓶颈在于创建一本大词典。 如果我将程序更改为按基因迭代并每次以类似的机制创建一个新列表,使用以下代码:

for transcript in groupby(content, lambda x: x[3]): 
    a = list(transcript[1]) 
    b = a[0] 
    gene = [b[0],b[5],b[11],b[12],b[13]] 
    seq=[] 
    n+=1 
    sys.stdout.write("\r") 
    sys.stdout.write(str(n)) 
    sys.stdout.flush() 
    for exon in a: 
        i=0 
        for nucleotide in list(exon)[14]: 
            seq.append((nucleotide,int(list(exon)[9])+i,int(list(exon)[1])+i)) 
            i+=1 
    gene.append(seq) 

它运行不到 4 分钟,而在以前的版本中一次创建包含所有基因的大字典需要一个小时才能运行。

请您参考如下方法:

提高代码效率的一个方法是在读取文件时添加到字典中。

with open("canonicals_metagene_withseq.bed") as f: 
for line in f: 
    all_transcripts.append(line.strip().split()[3]) 
    add_to_content_dict(line) 

然后您的 add_to_content_dict() 函数看起来像 for line in content: 循环中的代码

(参见 here)


另外,你必须这样定义你的 defaultdict,我没有看到 genes 或另一个 dict 在哪里被定义为 defaultdict。