2 # -*- coding: utf-8 -*-
7 Force spectroscopy curves filtering of flat curves
8 Licensed under the GNU LGPL version 2
10 Other plugin dependencies:
11 procplots.py (plot processing plugin)
14 from hooke.libhooke import WX_GOOD
17 wxversion.select(WX_GOOD)
18 import xml.dom.minidom
22 from numpy import diff
25 from .. import libpeakspot as lps
26 from .. import curve as lhc
29 class flatfiltsCommands(object):
32 #configurate convfilt variables
33 convfilt_configurator=ConvfiltConfig()
34 self.convfilt_config=convfilt_configurator.load_config('convfilt.conf')
36 def do_flatfilt(self,args):
40 Filters out flat (featureless) curves of the current playlist,
41 creating a playlist containing only the curves with potential
45 flatfilt [min_npks min_deviation]
47 min_npks = minmum number of points over the deviation
50 min_deviation = minimum signal/noise ratio
53 If called without arguments, it uses default values, that
54 should work most of the times.
63 min_deviation=int(args[1])
67 print 'Processing playlist...'
71 for item in self.current_list:
75 notflat=self.has_features(item, median_filter, min_npks, min_deviation)
76 print 'Curve',item.path, 'is',c,'of',len(self.current_list),': features are ',notflat
79 print 'Curve',item.path, 'is',c,'of',len(self.current_list),': cannot be filtered. Probably unable to retrieve force data from corrupt file.'
83 item.curve=None #empty the item object, to further avoid memory leak
84 notflat_list.append(item)
86 if len(notflat_list)==0:
87 print 'Found nothing interesting. Check your playlist, could be a bug or criteria could be too much stringent'
90 print 'Found ',len(notflat_list),' potentially interesting curves'
91 print 'Regenerating playlist...'
93 self.current_list=notflat_list
94 self.current=self.current_list[self.pointer]
97 def has_features(self,item,median_filter,min_npks,min_deviation):
99 decides if a curve is flat enough to be rejected from analysis: it sees if there
100 are at least min_npks points that are higher than min_deviation times the absolute value
103 Algorithm original idea by Francesco Musiani, with my tweaks and corrections.
107 item.identify(self.drivers)
108 #we assume the first is the plot with the force curve
109 #do the median to better resolve features from noise
110 flat_plot=self.plotmanip_median(item.curve.default_plots()[0], item, customvalue=median_filter)
111 flat_vects=flat_plot.vectors
112 item.curve.close_all()
113 #needed to avoid *big* memory leaks!
117 #absolute value of derivate
118 yretdiff=diff(flat_vects[1][1])
119 yretdiff=[abs(value) for value in yretdiff]
120 #average of derivate values
121 diffmean=numpy.mean(yretdiff)
125 for value in yretdiff:
126 if value/diffmean > min_deviation:
134 del flat_plot, flat_vects, yretdiff
138 ################################################################
139 #-----CONVFILT-------------------------------------------------
140 #-----Convolution-based peak recognition and filtering.
141 #Requires the libpeakspot.py library
143 def has_peaks(self, plot, abs_devs=None, maxpeak=True, window=10):
145 Finds peak position in a force curve.
146 FIXME: should be moved in libpeakspot.py
149 abs_devs=self.convfilt_config['mindeviation']
152 xret=plot.vectors[1][0]
153 yret=plot.vectors[1][1]
154 #Calculate convolution.
155 convoluted=lps.conv_dx(yret, self.convfilt_config['convolution'])
157 #surely cut everything before the contact point
158 cut_index=self.find_contact_point(plot)
159 #cut even more, before the blind window
160 start_x=xret[cut_index]
162 for value in xret[cut_index:]:
163 if abs((value) - (start_x)) > self.convfilt_config['blindwindow']*(10**-9):
166 cut_index+=blind_index
167 #do the dirty convolution-peak finding stuff
168 noise_level=lps.noise_absdev(convoluted[cut_index:], self.convfilt_config['positive'], self.convfilt_config['maxcut'], self.convfilt_config['stable'])
169 above=lps.abovenoise(convoluted,noise_level,cut_index,abs_devs)
170 peak_location,peak_size=lps.find_peaks(above,seedouble=self.convfilt_config['seedouble'])
172 #take the minimum or the maximum of a peak
173 for i in range(len(peak_location)):
174 peak=peak_location[i]
175 valpk=min(yret[peak-window:peak+window]) #maximum in force (near the unfolding point)
176 index_pk=yret[peak-window:peak+window].index(valpk)+(peak-window)
179 valpk=max(yret[peak:peak+window]) #minimum in force, near the baseline
180 index_pk=yret[peak:peak+window].index(valpk)+(peak)
182 # Let's explain that for the minimum. Immaging that we know that there is a peak at position/region 100 and you have found its y-value,
183 # Now you look in the array, from 100-10 to 100+10 (if the window is 10).
184 # This "100-10 to 100+10" is substancially a new array with its index. In this array you have 20
185 # elements, so the index of your y-value will be 10.
186 # Now to find the index in the TOTAL array you have to add the "position" of the "region" (that in this case
187 # correspond to 100) and also substract the window size ---> (+100-10)
189 peak_location[i]=index_pk
191 return peak_location,peak_size
194 def exec_has_peaks(self,item,abs_devs):
196 encapsulates has_peaks for the purpose of correctly treating the curve objects in the convfilt loop,
197 to avoid memory leaks
199 item.identify(self.drivers)
200 #we assume the first is the plot with the force curve
201 plot=item.curve.default_plots()[0]
203 if 'flatten' in self.config['plotmanips']:
204 #If flatten is present, use it for better recognition of peaks...
205 flatten=self._find_plotmanip('flatten') #extract flatten plot manipulator
206 plot=flatten(plot, item, customvalue=1)
208 peak_location,peak_size=self.has_peaks(plot,abs_devs)
209 #close all open files
210 item.curve.close_all()
211 #needed to avoid *big* memory leaks!
214 return peak_location, peak_size
216 #------------------------
217 #------commands----------
218 #------------------------
219 def do_peaks(self,args):
223 Test command for convolution filter / test.
225 Syntax: peaks [deviations]
226 absolute deviation = number of times the convolution signal is above the noise absolute deviation.
230 args=self.convfilt_config['mindeviation']
235 print 'Wrong argument, using config value'
236 abs_devs=float(self.convfilt_config['mindeviation'])
238 defplots=self.current.curve.default_plots()[0] #we need the raw, uncorrected plots
240 if 'flatten' in self.config['plotmanips']:
241 flatten=self._find_plotmanip('flatten') #extract flatten plot manipulator
242 defplots=flatten(defplots, self.current)
244 print 'You have the flatten plot manipulator not loaded. Enabling it could give you better results.'
246 peak_location,peak_size=self.has_peaks(defplots,abs_devs)
247 print 'Found '+str(len(peak_location))+' peaks.'
248 to_dump='peaks '+self.current.path+' '+str(len(peak_location))
249 self.outlet.push(to_dump)
252 #if no peaks, we have nothing to plot. exit.
253 if len(peak_location)==0:
256 #otherwise, we plot the peak locations.
257 xplotted_ret=self.plots[0].vectors[1][0]
258 yplotted_ret=self.plots[0].vectors[1][1]
259 xgood=[xplotted_ret[index] for index in peak_location]
260 ygood=[yplotted_ret[index] for index in peak_location]
262 recplot=self._get_displayed_plot()
263 recplot.vectors.append([xgood,ygood])
264 if recplot.styles==[]:
265 recplot.styles=[None,None,'scatter']
266 recplot.colors=[None,None,None]
268 recplot.styles+=['scatter']
269 recplot.colors+=[None]
271 self._send_plot([recplot])
273 def do_convfilt(self,args):
277 Filters out flat (featureless) curves of the current playlist,
278 creating a playlist containing only the curves with potential
282 convfilt [min_npks min_deviation]
284 min_npks = minmum number of peaks
285 (to set the default, see convfilt.conf file; CONVCONF and SETCONF commands)
287 min_deviation = minimum signal/noise ratio *in the convolution*
288 (to set the default, see convfilt.conf file; CONVCONF and SETCONF commands)
290 If called without arguments, it uses default values.
293 min_npks=self.convfilt_config['minpeaks']
294 min_deviation=self.convfilt_config['mindeviation']
298 min_npks=int(args[0])
299 min_deviation=int(args[1])
303 print 'Processing playlist...'
304 print '(Please wait)'
308 for item in self.current_list:
312 peak_location,peak_size=self.exec_has_peaks(item,min_deviation)
313 if len(peak_location)>=min_npks:
317 print 'Curve',item.path, 'is',c,'of',len(self.current_list),': found '+str(len(peak_location))+' peaks.'+isok
319 peak_location,peak_size=[],[]
320 print 'Curve',item.path, 'is',c,'of',len(self.current_list),': cannot be filtered. Probably unable to retrieve force data from corrupt file.'
322 if len(peak_location)>=min_npks:
323 item.peak_location=peak_location
324 item.peak_size=peak_size
325 item.curve=None #empty the item object, to further avoid memory leak
326 notflat_list.append(item)
328 #Warn that no flattening had been done.
329 if not ('flatten' in self.config['plotmanips']):
330 print 'Flatten manipulator was not found. Processing was done without flattening.'
331 print 'Try to enable it in your configuration file for better results.'
333 if len(notflat_list)==0:
334 print 'Found nothing interesting. Check your playlist, could be a bug or criteria could be too much stringent'
337 print 'Found ',len(notflat_list),' potentially interesting curves'
338 print 'Regenerating playlist...'
340 self.current_list=notflat_list
341 self.current=self.current_list[self.pointer]
345 def do_setconv(self,args):
349 Sets the convfilt configuration variables
351 Syntax: setconv variable value
354 #FIXME: a general "set dictionary" function has to be built
356 print self.convfilt_config
358 if not (args[0] in self.convfilt_config.keys()):
359 print 'This is not an internal convfilt variable!'
360 print 'Run "setconv" without arguments to see a list of defined variables.'
364 print self.convfilt_config[args[0]]
367 self.convfilt_config[args[0]]=eval(args[1])
368 except NameError: #we have a string argument
369 self.convfilt_config[args[0]]=args[1]
372 #########################
373 #HANDLING OF CONFIGURATION FILE
374 class ConvfiltConfig(object):
376 Handling of convfilt configuration file
378 Mostly based on the simple-yet-useful examples of the Python Library Reference
379 about xml.dom.minidom
381 FIXME: starting to look a mess, should require refactoring
388 def load_config(self, filename):
389 myconfig=file(filename)
390 #the following 3 lines are needed to strip newlines. otherwise, since newlines
391 #are XML elements too, the parser would read them (and re-save them, multiplying
393 #yes, I'm an XML n00b
394 the_file=myconfig.read()
395 the_file_lines=the_file.split('\n')
396 the_file=''.join(the_file_lines)
398 self.config_tree=xml.dom.minidom.parseString(the_file)
400 def getText(nodelist):
401 #take the text from a nodelist
402 #from Python Library Reference 13.7.2
404 for node in nodelist:
405 if node.nodeType == node.TEXT_NODE:
409 def handleConfig(config):
410 noiseabsdev_elements=config.getElementsByTagName("noise_absdev")
411 convfilt_elements=config.getElementsByTagName("convfilt")
412 handleAbsdev(noiseabsdev_elements)
413 handleConvfilt(convfilt_elements)
415 def handleAbsdev(noiseabsdev_elements):
416 for element in noiseabsdev_elements:
417 for attribute in element.attributes.keys():
418 self.config[attribute]=element.getAttribute(attribute)
420 def handleConvfilt(convfilt_elements):
421 for element in convfilt_elements:
422 for attribute in element.attributes.keys():
423 self.config[attribute]=element.getAttribute(attribute)
425 handleConfig(self.config_tree)
426 #making items in the dictionary machine-readable
427 for item in self.config.keys():
429 self.config[item]=eval(self.config[item])
430 except NameError: #if it's an unreadable string, keep it as a string