![](/img/trans.png)
[英]Filling zeros in numpy array that are between non-zero elements with the same value
[英]Enforce minimum spacing between non-zero elements in array
我正在嘗試生成零和1的數組,其中零之間的間隔是泊松分布的。
我相信這段代碼可以解決問題:
import numpy as np
dt = 0.05
n_t = 500 / dt # desired length of array
r = 100
spike_train = (np.random.rand(n_t) < r * dt).astype(int)
但是,我還想在1與2之間設置一個最小間距,例如任何兩個1之間至少要有兩個零。
什么是有效的方法?
這是一種合理有效的方法。 它的工作原理是(1)首先忽略最小等待時間。 (2)計算事件間時間(3)添加最小等待時間,(4)返回絕對時間,丟棄已移出右端的事件。 它可以在不到一秒鍾的時間內創建10 ** 7個樣本。
import numpy as np
def train(T, dt, rate, min_wait):
p = dt*rate
# correct for minimum wait
if p:
p = 1 / (1 / p - min_wait)
if p > 0.1:
print("warning: probability too high for approximation to be good")
n = int(np.ceil(T/dt))
raw_times, = np.where(np.random.random(n) < p)
raw_times[1:] += min_wait - raw_times[:-1]
good_times = raw_times.cumsum()
cut = good_times.searchsorted(n)
result = np.zeros(n, int)
result[good_times[:cut]] = 1
return result
我以這種邏輯(不太優雅)來保持分布:
def assure_2zeros(l):
for idx in range(len(l)):
# detect the problem when the ones are adjacent
if l[idx] == 1 and l[idx+1] == 1:
# check forward for a zero that could be realocated to split the ones
for i in range(idx+2, len(l)-1):
# check to not create other problems
if l[i] == 0 and l[i-1]== 0 and l[i+1]== 0:
del l[i]
l.insert(idx+1, 0)
break
# if doesnt found any zero forward, check backward
else:
for i in range(idx-1, 0, -1):
if l[i] == 0 and l[i-1]== 0 and l[i+1]== 0:
del l[i]
l.insert(idx+1, 0)
break
# detects the problem when there are one zero between the ones
if l[idx] == 1 and l[idx+2] == 1:
for i in range(idx+3, len(l)-1):
if l[i] == 0 and l[i-1]== 0 and l[i+1]== 0:
del l[i]
l.insert(idx+1, 0)
break
else:
for i in range(idx-1, 0, -1):
if l[i] == 0 and l[i-1]== 0 and l[i+1]== 0:
del l[i]
l.insert(idx+1, 0)
break
return l
注意,當有兩個相鄰的if時,第一個if將在它們之間插入一個零,然后它將輸入第二個if並將第二個零插入。 但是,當列表的末尾或開頭有兩個或一個零時,它將失敗。 可以在if語句中添加更多條件,但是對於您的情況,有很多零,我認為它可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.