2017-06-02 261 views
0

我正在嘗試使用Python編寫的IDL代碼通過其標準偏差函數中的一系列值計算背景噪音。下面的代碼:將IDL代碼翻譯爲Python

; (INPUT) 
; data = 1-D array of intensities 
; (OUTPUT) 
; bck,sig = background and fluctuations (1 sig level) 
; ndata = number of values upon which bck,sig are computed 
; POSITIVE = retains only data values > 0 
; NSIG = number of sigmas 

    if not(keyword_set(NSIG)) then nsig=3.  
    if keyword_set(POSITIVE) then begin 
    test=where(data gt 0.) 
    if test(0) ne -1 then data2=data(test) else begin 
     bck=0 & sig=-1 & ndata=0 & goto,out 
    endelse 
    endif else data2=data 
    if n_elements(data2) gt 1 then begin 
    bck=mean(data2,/double) & sig=stddev(data2,/double) 
    endif else begin 
    bck=data2(0) & sig=0 & ndata=1 & goto,out 
    endelse 
    ndata=1 

loop: 
    test=where(abs(data2-bck) lt nsig*sig) 
    if n_elements(test) eq 1 then goto,out 
    ndata=n_elements(test) 
    moy=mean(data2(test),/double) 
    sig=stddev(data2(test),/double) 
    if moy eq bck then goto,out 
    bck=moy 
    goto,loop 

out: 
    return 
end 

代碼的心臟是循環的,這裏是我試圖複製它:

def bg(array): 
    temp = [] 
    for i in range(len(array)): 
     if array[i]-np.mean(array) < 3*np.std(array): 
      temp.append(array[i]) 
    avg=mean(temp) 
    return avg 

這是正確的嗎?原始代碼是否只能找到那些低於3 * std的值的平均值?

這一行中的1實際上意味着什麼? if n_elements(test) eq 1 then goto,out

回答

0

看起來這就是代碼正在做的事情。它只會計算在nsig之下的點的平均值。

if n_elements(test) eq 1 then goto,out表示如果測試中只有一個元素,則轉至out行,然後執行返回。

一般而言,goto語句應該在IDL中避免,它們有使代碼非常混亂且難以調試的傾向。