【发布时间】: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