Python DNA序列中子序列出现频率


Python DNA序列在使用的时候有很多需要我们注意的东西,其实在不断的学习中有很多问题存在,下面我们就详细的看看如何进行相关的技术学校。ms是我师弟的rotation project:给定一堆Python DNA序列,即由字符A, C, G, T组成的字符串,统计所有长度为n的子序列出现的频率。

比如 ACGTACGT,子序列长度为2,于是 AC=2, CG=2, GT=2, TA=1,其余长度为2的子序列频率为0.

最先想到的就是建一个字典,key是所有可能的子序列,value是这个子序列出现的频率。Python DNA序列但是当子序列比较长的时候,比如 n=8,需要一个有65536 (4的8次方) 个key-value pair的字典,且每个key的长度是8字符。这样ms有点浪费内存。。

于是想到,所有的长度为n的子序列是有序且连续的,所以可以映射到一个长度为4的n次方的的list里。令 A=0, C=1, G=2, T=3,则把子序列 ACGT 转换成 0*4^3 + 1*4^2 + 2*4 + 3 = 27, 映射到list的第27位。如此,list的index对应子序列,而list这个index位置则储存这个子序列出现的频率。

于是我们先要建立2个字典,表示ACGT和0123一一对应的关系:

  1. i2mD = {0:'A', 1:'C', 2:'G', 3:'T'}  
  2. m2iD = dict(A=0,C=1,G=2,T=3)  
  3. # This is just another way to initialize a 
    dictionary 

以及下面的子序列映射成整数函数:

  1. def motif2int(motif):  
  2. '''convert a sub-sequence/motif to a non-negative 
    integer'''  
  3. total = 0 
  4. for i, letter in enumerate(motif):  
  5. total += m2iD[letter]*4**(len(motif)-i-1)  
  6. return total  
  7. Test:  
  8. >>> motif2int('ACGT') 

虽然我们内部把子序列当成正整数来存储确切地说,其实这个整数是没有存在内存里的,而是由其在list的index表示的),为了方便生物学家们看,输出时还是转换回子序列比较好。

于是有了下面的整数映射成子序列函数,其中调用了另外一个函数baseN(),来源在此,感谢作者~

  1. def baseN(n,b):  
  2. '''convert non-negative decimal integer n to  
  3. equivalent in another base b (2-36)'''  
  4. return ((n == 0) and '0' ) or ( baseN(n // b, b).lstrip('0') + \  
  5. "0123456789abcdefghijklmnopqrstuvwxyz"[n % b])  
  6. def int2motif(n, motifLen):  
  7. '''convert non-negative integer n to a sub-sequence/motif with length motifLen'''  
  8. intBase4 = baseN(n,4)  
  9. return ''.join(map(lambda x: i2mD[int(x)],'0'*(motifLen-len(intBase4))+intBase4))  
  10. Test:  
  11. >>> int2motif(27,4)  
  12. 'ACGT'  

以下代码从命令行读入一个存有DNA序列的fasta文件,以及子序列长度,并输出子序列和频率。注意以下代码需要Biopython module。

  1. if __name__ == '__main__':  
  2. import sys  
  3. from Bio import SeqIO  
  4. # read in the fasta file name and motif length  
  5. # from command line parameters  
  6. fastafile = sys.argv[1]  
  7. motifLen = int(sys.argv[2])  
  8. # list to store subsequence frequency  
  9. frequencyL = [0]*4**motifLen  
  10. # go over each DNA sequence in the fasta file  
  11. # and count the frequency of subsequences  
  12. it = SeqIO.parse(open(fastafile),'fasta')  
  13. for rec in it:  
  14. chrom = rec.seq.tostring()  
  15. for i in range(len(chrom)-motifLen+1):  
  16. motif = chrom[i:i+motifLen]  
  17. frequencyL[motif2int(motif)] += 1  
  18. # print frequency result to screen  
  19. for i, frequency in enumerate(frequencyL):  
  20. print int2motif(i, motifLen), frequency  

以上就是对Python DNA序列的相关介绍。

相关内容

    暂无相关文章

评论关闭