def EstimateBackground(y,iterations=500,reduction=1,smoothing=5,pre_smooth=10): ''' BACKGROUND ESTIMATION This algorithm is pure python version of the more advanced one included in the advanced fitting module of pymca. Firstly the background is smoothed and reduced by some factor (faster). The average background intensity is calculated by using a kernel smoothing algorithm (longer kernel = more smoothing). At each point the intensity is set to the real data or the average, whichever is lower. Repeated iterations result in more smoothing. The ends are fixed to their real values to prevent propagating end effects ''' #copy the spectrum, smooth it then compress by 'reduction' background = smooth(y.copy(),'hanning',pre_smooth) if reduction > 1: background = background[::reduction] #for each iteration replace any value over the 5point average with the #average, then replace the start and end points fix_start,fix_end = background[0],background[-1] for i in range(iterations): averages = smooth(background,'flat', smoothing) background = np.where(background>averages,averages,background) background[0],background[-1] = fix_start,fix_end #expand the background and trim it to have the same size as the original spectrum if reduction > 1: background = smooth(background.repeat(reduction)[0:len(y)],'hanning',reduction) #t2 = time.clock() #print 'Refined background in %f seconds '%(t2-t1) return background
def SNIPwrong(y): p = 10 #extend data to exclude end effects #ny = np.r_[2*y[0]-y[p:1:-1],y,2*y[-1]-y[-1:-p:-1]] s = smooth(y,'hanning', 21) #work space w = np.zeros((2,y.size)) kernel2 = np.zeros(2*p+1) kernel2[0] = kernel2[-1] = 0.5 kernel4 = np.zeros(2*p+1) kernel4[0] = kernel4[-1] = -1/6. kernel4[2*p/4] = kernel4[6*p/4] = 4./6 while(1): #w[0,:] = np.convolve(ny,kernel2,'same') w[0,p/2:-p/2] = (y[:-p]+y[p:])/2. #w[1,:] = np.convolve(ny,kernel4,'same') w[1,p/2:-p/2] = (y[:-p]+y[p:])/-6. #w[1,p/2:-3*p/4] += 4*(y[p/2:-3*p/4])/6. #w[1,3*p/4:-p/2] += 4*(y[3*p/4:-p/2])/6. y = np.vstack([s,w.max(0)]).min(0) yield y#[p-1:-p+1]
def generate(p=21): background = LLS(y.copy()) #background2 = LLS(y.copy()) background = smooth(background,'hanning',p) #background2 = smooth(background2,'hanning',11) background = background[::reduction] #background2 = background2[::reduction] #back2func = SNIP(background2) i=1 ind=(p-1)/2 while(1): averages = smooth(background[ind:-ind],'hanning', p) background[ind:-ind] = np.where(background[ind:-ind]>averages,averages,background[ind:-ind]) #averages = smooth(background2[10:-10],'hanning', 21) #background2 = back2func.next() i+=1 if i==50: break yield invLLS(background)#,invLLS(background2)
def SNIP(y,m=60,reverse=False): w = np.empty((2,y.size)) z = np.empty((2,y.size)) w[0,:] = smooth(y,'hanning', 15) if reverse: nums = xrange(m,3,-1) else: nums = xrange(3,m,1) for p in nums: z[1,p:-p] = (-w[0,:-2*p]+4*w[0,p/2:-3*p/2]+4*w[0,3*p/2:-p/2]-w[0,2*p:])/6. z[0,p:-p] = (w[0,:-2*p]+w[0,2*p:])/2. w[1,:] = z.max(0) w[0,:] = w.min(0) return w[0,:]