2016-04-25 140 views
2

我目前插值用三次樣條函數的測量如圖所示的畫面:更Python的方式尋找曲線交點

Interpolation of a normalised harmonic signal using cubic splines.

的想法是我想要找的全寬半最大插值的。對於我使用的一小段代碼

f = interpolate.interp1d(hhg_data, signal_array, kind='cubic') 
idx2 = np.argsort(np.abs(f(hhg_interp)-0.5)) 

返回我的路口排序指標與線y=0.5。但是,我想要在曲線的左邊緣和右邊緣的解決方案,有時它會給我兩個連續的點。有沒有一種優雅的pythonic方式來避免這種情況?至少比我的哈克解決方案好多了:

idx_sorted = [] 
counter = 0 
counter2 = 0 
while(counter <= 1): 
    if idx2[counter2] != idx2[counter2-1]+1 and idx2[counter2] != idx2[counter2-1]-1: 
     idx_sorted.append(idx2[counter2]) 
     counter+=1 
    counter2+=1 

謝謝你的回答!

回答

0

假設hhg_interp進行排序,並且只有一個最大值和希望做一個gridsearch(即計算出你在離散點的功能,並使用這些值工作),我會做到以下幾點:

# hhg_interp could be something like 
# hhg_interp = linspace(18.5, 19.5, 10000) 
y = f(hhg_interp) # hhg_interp is an array filled with finely 
        # spaced x-axis values 
# get the indices for all y larger than the half maximum (0.5 in this case) 
indices_above_fwhm = np.where(y>0.5)[0] 
# if you're interested in the indices 
# the first element of the "indices larger then the half maximum" array 
# corresponds to your left edge 
index_left_edge = indices_above_fwhm[0] 
# the last element of the "indices larger then the half maximum array" 
# corresponds to your right edge 
index_right_edge = indices_above_fwhm[-1] 


# then you can get the corresponding x-axis values for these indices: 
x_left = hhg_interp[index_left_edge] 
x_right = hhg_interp[index_right_edge] 

# or directly get the x-axis values of the left and right edges 
cond = y > 0.5 # select all points that are above your half maximum 
x_left, x_right = hhg_interp[cond][[0,-1]] # then get the first 
           # and last of the points above maximum 

是你正在尋找的信息?

+0

不太確定,hhg_interp基本上是一個x軸變量的np.array。在這種情況下,你可以把它作爲hhg_interp = linspace(18.5,19.5,10000),只需要一個精細的網格來繪製f。 – Roland

+0

增加了一些用於計算左右邊緣索引的代碼以及一些註釋。這有助於澄清? – cobaltfiftysix

+0

好的,我明白了。感謝它的工作很好。也許我會解決這個想法,最好的適應我的興趣。 – Roland