【问题标题】:using numpy to randomly distribute DNA sequence reads over genomic features使用 numpy 在基因组特征上随机分布 DNA 序列读数
【发布时间】:2014-02-01 13:10:31
【问题描述】:

您好,我编写了一个脚本,可以随机打乱读取序列映射到的基因。 如果您想确定您在感兴趣的基因上观察到的峰是否具有统计学意义,这将很有用。我使用此代码来计算我感兴趣的基因中峰值的错误发现率。 代码下方:

import numpy as np
import matplotlib.pyplot as plt
iterations = 1000 # number of times a read needs to be shuffled
featurelength = 1000  # length of the gene
a = np.zeros((iterations,featurelength))  # create a matrix with 1000 rows of the feature length
b = np.arange(iterations)                 # a matrix with the number of iterations (0-999)
reads = np.random.randint(10,50,1000)     # a random dataset containing an array of DNA read lengths

下面是填充大矩阵的代码(一):

for i in reads:               # for read with read length i
    r = np.random.randint(-i,featurelength-1,iterations) # generate random read start positions for the read i
    for j in b:               # for each row in a:
        pos = r[j]            # get the first random start position for that row
        if pos < 0:           # start position can be negative because a read does not have to completely overlap with the feature
            a[j][:pos+i]+=1
        else:
            a[j][pos:pos+i]+=1  # add the read to the array and repeat

然后生成热图,看看分布是否大致均匀:

plt.imshow(a)
plt.show()

这会产生所需的结果,但由于有许多 for 循环,所以速度非常慢。 我尝试做花哨的 numpy 索引,但我经常收到“索引过多错误”。

有人对如何做到这一点有更好的想法吗?

【问题讨论】:

  • 你能解释一下循环的目的吗?例如,我不明白你为什么生成r 然后只使用它的一个元素。不能直接生成pos吗?
  • 所以 r 有 1000 个随机数,它们本质上是读取 i 的随机起始位置。所以对于矩阵 a 中的第一行 j,读取的起始位置是 r[j]。我想做的是基本上一次性改变整个矩阵,但由于某种原因,numpy 不允许我这样做。你可以做的是:a[(j,pos)]+=1。你也可以a[(j,tuple(range(pos,pos+1)))]+=1。但是,当您对 r 中的所有随机位置执行此操作时:a[(j,tuple(range(pos,pos+i))),(j2,tuple(range(pos2,pos2+i)))]+=1 等,它会抱怨 IndexError, too many indices 或其他东西
  • 我不认为 fancyindexing 支持按 start:end 数组切片,只能按整数切片。这几乎破坏了我担心的任何进一步的矢量化尝试。
  • @EelcoHoogendoorn:只需将您的 start:end 切片转换为带有arange的整数数组

标签: python random numpy sequence


【解决方案1】:

花式索引有点棘手,但仍然可行:

for i in reads:
    r = np.random.randint(-i,featurelength-1,iterations)
    idx = np.clip(np.arange(i)[:,None]+r, 0, featurelength-1)
    a[b,idx] += 1

稍微解构一下,我们是:

  1. 创建一个简单的索引数组作为列向量,从 0 到 i:np.arange(i)[:,None]

  2. 将r(行向量)中的每个元素添加到a 的列中,广播以生成大小为(i,iterations) 的矩阵,并在a 的列中使用正确的偏移量。

  3. 通过np.clip 将索引限制在[0,featurelength) 范围内。

  4. 最后,我们为每一行 (b) 和相关列 (idx) 指定索引 a。

【讨论】:

  • np.clip 会更简洁。
  • 我的代码:1 次循环,3 次中的最佳:每个循环 3.6 秒 perimosocordiae 的代码:1 次循环,3 次中的最佳:每个循环 1.14 秒。大约快 3 倍,并产生完全相同的结果。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
相关资源
最近更新 更多