如何在 R 中生成脉冲序列?

How to generate spike trains in R?

如果这看起来很明显,请原谅我,我是 R 的新手。 因此,我试图获得看起来像矢量 [1 0 1 1 0 0 0 1] 的随机 Spike Train,例如,我已经能够使用以下代码做到这一点:

fr = 100 #Firing rate of 100Hz
dt = 1/1000 #Short duration of time dt
nBins = 10 #10msSpikeTrain 
x = runif(nBins) #Creating a "nBins" length string of random variable 
#falling uniformly between 0 and 1
x
y<- numeric(nBins) # creating an empty vector of size nBins
MyPoissonSpikeTrain = function(x){
for (i in 1:nBins){
if (x[i] < fr*dt)
y[i]=1
else
y[i]=0
}
return(y)
}  
#Creating a function that that returns its values in vector y as 1 if the 
#spike was fired 
#and 0 if the spike wasn't fired. 
#Spike was fired, if randomly generated x value is smaller than fr*dt. 
MyPoissonSpikeTrain(x)

一切正常,但我想创建一个矩阵,其中第一行是上述过程的一个实例,第二行是第二个实例,依此类推。

我希望这个过程发生(比如说)20 次,然后将我找到的每个单独的 y 作为更大矩阵的一行,比如 Y。我知道我需要将我的 y 修改为矩阵而不是向量,然后相应地修改我的 MyPoissonSpikeTrain 函数以使输出创建一个矩阵,但我不知道该怎么做。任何帮助将不胜感激。

这个函数可以简化很多,看看这个:

MyPoissonSpikeTrain = function(fr = 100, dt = 1/1000, nBins = 10){
  x = runif(nBins)
  y = ifelse(x < dt * fr, 0, 1)
  return(y)
}  

现在它是矢量化的,您可以根据需要更改参数。现在生成所需的矩阵:

set.seed(1)
replicate(10, MyPoissonSpikeTrain())
#output
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    1    1    1    1    1    1    1    1     1
 [2,]    1    1    1    1    1    1    1    1    1     0
 [3,]    1    1    1    1    1    1    1    1    1     1
 [4,]    1    1    1    1    1    1    1    1    1     1
 [5,]    1    1    1    1    1    0    1    1    1     1
 [6,]    1    1    1    1    1    0    1    1    1     1
 [7,]    1    1    0    1    0    1    1    1    1     1
 [8,]    1    1    1    1    1    1    1    1    1     1
 [9,]    1    1    1    1    1    1    0    1    1     1
[10,]    0    1    1    1    1    1    1    1    1     1

这里每一列都是一个重复,如果你想反过来使用:t

t(replicate(10, MyPoissonSpikeTrain()))

如果你想改变一些参数:

set.seed(1)
replicate(10, MyPoissonSpikeTrain(fr = 500))
#output
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    1    1    1    1    1    0    1    0     1
 [2,]    0    1    0    0    1    1    1    1    0     0
 [3,]    0    0    0    0    0    0    0    1    1     0
 [4,]    1    0    0    1    0    0    1    0    1     1
 [5,]    1    0    1    1    1    1    1    0    1     0
 [6,]    0    0    0    1    0    0    0    1    0     1
 [7,]    0    1    1    1    0    1    0    1    1     0
 [8,]    0    0    0    1    1    0    0    1    1     1
 [9,]    1    0    0    1    0    0    1    1    1     0
[10,]    1    1    1    1    1    0    0    1    1     1

甚至更好:

MyPoissonSpikeTrain = function(fr = 100, dt = 1/1000, nBins = 10, ...){
  x = runif(nBins, ...)
  y = ifelse(x < dt * fr, 0, 1)
  return(y)
}  

所以你可以传递额外的参数给 runif

set.seed(1)
replicate(10, MyPoissonSpikeTrain(max = 0.5))