使用混沌游戏表示基因序列[Python程序]

时间:2017-06-12 10:09:50

标签: python dna-sequence representation chaos

我需要使用混沌游戏表示来表示许多基因序列我从BoštjanCigan的博客(https://bostjan-cigan.com/chaos-game-representation-of-gene-structure-in-python/)获得了这个python代码

作者:Bostjan Cigan

https://bostjan-cigan.com

    import collections
    from collections import OrderedDict
    from matplotlib import pyplot as plt
    from matplotlib import cm

    import pylab
    import math

    f = open("ensemblSeq.fa")
    s1 = f.read()
    data = "".join(s1.split("\n")[1:])

    def count_kmers(sequence, k):
        d = collections.defaultdict(int)
        for i in xrange(len(data)-(k-1)):
            d[sequence[i:i+k]] +=1
        for key in d.keys():
             if "N" in key:
                 del d[key]
        return d

    def probabilities(kmer_count, k):
        probabilities = collections.defaultdict(float)
        N = len(data)
        for key, value in kmer_count.items():
            probabilities[key] = float(value) / (N - k + 1)
        return probabilities

    def chaos_game_representation(probabilities, k):
        array_size = int(math.sqrt(4**k))
        chaos = []
        for i in range(array_size):
            chaos.append([0]*array_size)

        maxx = array_size
        maxy = array_size
        posx = 1
        posy = 1
         for key, value in probabilities.items():
             for char in key:
                 if char == "T":
                    posx += maxx / 2
                 elif char == "C":
                    posy += maxy / 2
                 elif char == "G":
                     posx += maxx / 2
                     posy += maxy / 2
                 maxx = maxx / 2
                 maxy /= 2
             chaos[posy-1][posx-1] = value
             maxx = array_size
             maxy = array_size
             posx = 1
             posy = 1

         return chaos

      f3 = count_kmers(data, 3)
      f4 = count_kmers(data, 4)

      f3_prob = probabilities(f3, 3)
      f4_prob = probabilities(f4, 4)

      chaos_k3 = chaos_game_representation(f3_prob, 3)
      pylab.title('Chaos game representation for 3-mers')
      pylab.imshow(chaos_k3, interpolation='nearest', cmap=cm.gray_r)
      pylab.show()

      chaos_k4 = chaos_game_representation(f4_prob, 4)
      pylab.title('Chaos game representation for 4-mers')
      pylab.imshow(chaos_k4, interpolation='nearest', cmap=cm.gray_r)
      pylab.show()

这段代码工作正常但我有很多序列文件我需要遍历文件夹中的每个fasta文件,并获得存储在一个文件夹中的单个图,其中图像文件的名称对应于fasta文件的名称我该怎么办?根据我的需要修改代码

我是python以及StackOverflow的新手,如果有任何错误,请忽略

提前致谢

1 个答案:

答案 0 :(得分:0)

因此,如果要在目录中的每个文件上应用代码,执行此操作的一种非常简单的方法是调用for循环内的所有文件。我建议如下:

import collections
import os
from collections import OrderedDict
from matplotlib import pyplot as plt
from matplotlib import cm

import pylab
import math

def count_kmers(sequence, k):
    d = collections.defaultdict(int)
    for i in xrange(len(data)-(k-1)):
        d[sequence[i:i+k]] +=1
    for key in d.keys():
         if "N" in key:
             del d[key]
    return d

def probabilities(kmer_count, k):
    probabilities = collections.defaultdict(float)
    N = len(data)
    for key, value in kmer_count.items():
        probabilities[key] = float(value) / (N - k + 1)
    return probabilities

def chaos_game_representation(probabilities, k):
    array_size = int(math.sqrt(4**k))
    chaos = []
    for i in range(array_size):
        chaos.append([0]*array_size)

    maxx = array_size
    maxy = array_size
    posx = 1
    posy = 1
    for key, value in probabilities.items():
        for char in key:
            if char == "T":
                posx += maxx / 2
            elif char == "C":
                posy += maxy / 2
            elif char == "G":
                 posx += maxx / 2
                 posy += maxy / 2
            maxx = maxx / 2
            maxy /= 2
        chaos[posy-1][posx-1] = value
        maxx = array_size
        maxy = array_size
        posx = 1
        posy = 1
    return chaos

if __name__ == "__main__":
    PATH = os.getcwd()
    filelist = sorted([os.path.join(PATH, f) for f in os.listdir(PATH) if f.endswith('.fa')])
    for file in filelist:
        f = open(file)
        s1 = f.read()
        data = "".join(s1.split("\n")[1:])
        f3 = count_kmers(data, 3)
        f4 = count_kmers(data, 4)

        f3_prob = probabilities(f3, 3)
        f4_prob = probabilities(f4, 4)

        chaos_k3 = chaos_game_representation(f3_prob, 3)
        pylab.title('Chaos game representation for 3-mers')
        pylab.imshow(chaos_k3, interpolation='nearest', cmap=cm.gray_r)
        pylab.savefig(os.path.splitext(file)[0]+'chaos3.png')
        pylab.show()

        chaos_k4 = chaos_game_representation(f4_prob, 4)
        pylab.title('Chaos game representation for 4-mers')
        pylab.imshow(chaos_k4, interpolation='nearest', cmap=cm.gray_r)
        pylab.savefig(os.path.splitext(file)[0]+'chaos4.png')
        pylab.show()

我只是绕了一圈并添加了pylab.savefig()来电。此外,我使用os从您的目录中获取文件名。它现在应该工作。

相关问题