Ran update_copyright.py, updating all the copyright blurbs and adding AUTHORS.
[hooke.git] / hooke / plugin / generalvclamp.py
index 1c71de0e03ab61074a9501cc31ce5f54e11fb301..9c0593e925940f8f845c59ba17c9db0a30f64005 100644 (file)
@@ -1,12 +1,29 @@
-#!/usr/bin/env python
+# Copyright (C) 2008-2010 Alberto Gomez-Casado
+#                         Fabrizio Benedetti
+#                         Marco Brucale
+#                         Massimo Sandal <devicerandom@gmail.com>
+#                         W. Trevor King <wking@drexel.edu>
+#
+# This file is part of Hooke.
+#
+# Hooke is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation, either
+# version 3 of the License, or (at your option) any later version.
+#
+# Hooke is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Hooke.  If not, see
+# <http://www.gnu.org/licenses/>.
 
-'''
-generalvclamp.py
+"""Plugin regarding general velocity clamp measurements
+"""
 
-Plugin regarding general velocity clamp measurements
-'''
-
-from libhooke import WX_GOOD, ClickedPoint
+from hooke.libhooke import WX_GOOD, ClickedPoint
 import wxversion
 wxversion.select(WX_GOOD)
 from wx import PostEvent
@@ -20,13 +37,13 @@ import warnings
 warnings.simplefilter('ignore',np.RankWarning)
 
 
-class generalvclampCommands:
-    
+class generalvclampCommands(object):
+
     def _plug_init(self):
         self.basecurrent=None
         self.basepoints=None
         self.autofile=''
-    
+
     def do_distance(self,args):
         '''
         DISTANCE
@@ -55,7 +72,7 @@ class generalvclampCommands:
         Measure the force difference (in pN) between two points
         ---------------
         Syntax: force
-        '''    
+        '''
         if self.current.curve.experiment == 'clamp':
             print 'This command makes no sense for a force clamp experiment.'
             return
@@ -63,15 +80,15 @@ class generalvclampCommands:
         print str(dy*(10**12))+' pN'
         to_dump='force '+self.current.path+' '+str(dy*(10**12))+' pN'
         self.outlet.push(to_dump)
-        
-        
+
+
     def do_forcebase(self,args):
         '''
         FORCEBASE
         (generalvclamp.py)
         Measures the difference in force (in pN) between a point and a baseline
         took as the average between two points.
-        
+
         The baseline is fixed once for a given curve and different force measurements,
         unless the user wants it to be recalculated
         ------------
@@ -82,19 +99,19 @@ class generalvclampCommands:
         '''
         rebase=False #if true=we select rebase
         maxpoint=False #if true=we measure the maximum peak
-        
+
         plot=self._get_displayed_plot()
         whatset=1 #fixme: for all sets
         if 'rebase' in args or (self.basecurrent != self.current.path):
             rebase=True
         if 'max' in args:
             maxpoint=True
-               
+
         if rebase:
             print 'Select baseline'
             self.basepoints=self._measure_N_points(N=2, whatset=whatset)
             self.basecurrent=self.current.path
-        
+
         if maxpoint:
             print 'Select two points'
             points=self._measure_N_points(N=2, whatset=whatset)
@@ -109,82 +126,92 @@ class generalvclampCommands:
             points=self._measure_N_points(N=1, whatset=whatset)
             #whatplot=points[0].dest
             y=points[0].graph_coords[1]
-        
+
         #fixme: code duplication
         boundaries=[self.basepoints[0].index, self.basepoints[1].index]
         boundaries.sort()
         to_average=plot.vectors[whatset][1][boundaries[0]:boundaries[1]] #y points to average
-        
+
         avg=np.mean(to_average)
         forcebase=abs(y-avg)
         print str(forcebase*(10**12))+' pN'
         to_dump='forcebase '+self.current.path+' '+str(forcebase*(10**12))+' pN'
         self.outlet.push(to_dump)
-\r
+
     def plotmanip_multiplier(self, plot, current):
         '''
-        Multiplies all the Y values of an SMFS curve by a value stored in the 'force_multiplier'\r
+        Multiplies all the Y values of an SMFS curve by a value stored in the 'force_multiplier'
         configuration variable. Useful for calibrations and other stuff.
         '''
-        
+
         #not a smfs curve...
         if current.curve.experiment != 'smfs':
             return plot
-        
+
         #only one set is present...
         if len(self.plots[0].vectors) != 2:
             return plot
-        
+
         #multiplier is 1...
         if (self.config['force_multiplier']==1):
-            return plot\r
-\r
+            return plot
+
         for i in range(len(plot.vectors[0][1])):
-            plot.vectors[0][1][i]=plot.vectors[0][1][i]*self.config['force_multiplier']        \r
-\r
+            plot.vectors[0][1][i]=plot.vectors[0][1][i]*self.config['force_multiplier']        
+
         for i in range(len(plot.vectors[1][1])):
-            plot.vectors[1][1][i]=plot.vectors[1][1][i]*self.config['force_multiplier']\r
-\r
-        return plot            \r
+            plot.vectors[1][1][i]=plot.vectors[1][1][i]*self.config['force_multiplier']
+
+        return plot            
    
     
     def plotmanip_flatten(self, plot, current, customvalue=False):
         '''
         Subtracts a polynomial fit to the non-contact part of the curve, as to flatten it.
-        the best polynomial fit is chosen among polynomials of degree 1 to n, where n is 
+        the best polynomial fit is chosen among polynomials of degree 1 to n, where n is
         given by the configuration file or by the customvalue.
-        
+
         customvalue= int (>0) --> starts the function even if config says no (default=False)
         '''
-        
+
         #not a smfs curve...
         if current.curve.experiment != 'smfs':
             return plot
-        
+
         #only one set is present...
         if len(self.plots[0].vectors) != 2:
             return plot
-        
+
         #config is not flatten, and customvalue flag is false too
         if (not self.config['flatten']) and (not customvalue):
             return plot
-        
+
         max_exponent=12
         delta_contact=0
-        
+
         if customvalue:
             max_cycles=customvalue
         else:
             max_cycles=self.config['flatten'] #Using > 1 usually doesn't help and can give artefacts. However, it could be useful too.
-        
+
         contact_index=self.find_contact_point()
-        
+
         valn=[[] for item in range(max_exponent)]
         yrn=[0.0 for item in range(max_exponent)]
         errn=[0.0 for item in range(max_exponent)]
         
+        #Check if we have a proper numerical value
+        try:
+            zzz=int(max_cycles)
+        except:
+            #Loudly and annoyingly complain if it's not a number, then fallback to zero
+            print '''Warning: flatten value is not a number!
+            Use "set flatten" or edit hooke.conf to set it properly
+            Using zero.'''
+            max_cycles=0
+        
         for i in range(int(max_cycles)):
-            
+
             x_ext=plot.vectors[0][0][contact_index+delta_contact:]
             y_ext=plot.vectors[0][1][contact_index+delta_contact:]
             x_ret=plot.vectors[1][0][contact_index+delta_contact:]
@@ -200,22 +227,22 @@ class generalvclampCommands:
                     return plot
 
             best_exponent=errn.index(min(errn))
-            
+
             #extension
             ycorr_ext=y_ext-yrn[best_exponent]+y_ext[0] #noncontact part
-            yjoin_ext=np.array(plot.vectors[0][1][0:contact_index+delta_contact]) #contact part        
+            yjoin_ext=np.array(plot.vectors[0][1][0:contact_index+delta_contact]) #contact part
             #retraction
             ycorr_ret=y_ret-yrn[best_exponent]+y_ext[0] #noncontact part
             yjoin_ret=np.array(plot.vectors[1][1][0:contact_index+delta_contact]) #contact part
-                
+
             ycorr_ext=np.concatenate((yjoin_ext, ycorr_ext))
             ycorr_ret=np.concatenate((yjoin_ret, ycorr_ret))
-        
+
             plot.vectors[0][1]=list(ycorr_ext)
             plot.vectors[1][1]=list(ycorr_ret)
-        
+
         return plot
-            
+
     #---SLOPE---
     def do_slope(self,args):
         '''
@@ -242,60 +269,73 @@ class generalvclampCommands:
         if fitspan == 0:
             # Gets the Xs of two clicked points as indexes on the current curve vector
             print 'Click twice to delimit chunk'
-            clickedpoints=[]
             points=self._measure_N_points(N=2,whatset=1)
-            clickedpoints=[points[0].index,points[1].index]
-            clickedpoints.sort()
         else:
             print 'Click once on the leftmost point of the chunk (i.e.usually the peak)'
-            clickedpoints=[]
             points=self._measure_N_points(N=1,whatset=1)
-            clickedpoints=[points[0].index-fitspan,points[0].index]
-        
-        # Calls the function linefit_between
+            
+        slope=self._slope(points,fitspan)
+
+        # Outputs the relevant slope parameter
+        print 'Slope:'
+        print str(slope)
+        to_dump='slope '+self.current.path+' '+str(slope)
+        self.outlet.push(to_dump)
+
+    def _slope(self,points,fitspan):
+               # Calls the function linefit_between
         parameters=[0,0,[],[]]
+        try:
+            clickedpoints=[points[0].index,points[1].index]
+            clickedpoints.sort()
+        except:
+            clickedpoints=[points[0].index-fitspan,points[0].index]        
+
         try:
             parameters=self.linefit_between(clickedpoints[0],clickedpoints[1])
         except:
             print 'Cannot fit. Did you click twice the same point?'
             return
-          
+             
         # Outputs the relevant slope parameter
         print 'Slope:'
         print str(parameters[0])
-        to_dump='slope '+self.current.path+' '+str(parameters[0])
+        to_dump='slope '+self.curve.path+' '+str(parameters[0])
         self.outlet.push(to_dump)
-                
+
         # Makes a vector with the fitted parameters and sends it to the GUI
         xtoplot=parameters[2]
         ytoplot=[]
         x=0
         for x in xtoplot:
             ytoplot.append((x*parameters[0])+parameters[1])
-            
+
         clickvector_x, clickvector_y=[], []
         for item in points:
             clickvector_x.append(item.graph_coords[0])
             clickvector_y.append(item.graph_coords[1])
 
         lineplot=self._get_displayed_plot(0) #get topmost displayed plot
-        
+
         lineplot.add_set(xtoplot,ytoplot)
         lineplot.add_set(clickvector_x, clickvector_y)
-                
-        
+
+
         if lineplot.styles==[]:
             lineplot.styles=[None,None,None,'scatter']
         else:
             lineplot.styles+=[None,'scatter']
         if lineplot.colors==[]:
-            lineplot.styles=[None,None,None,None]
+            lineplot.colors=[None,None,'black',None]
         else:
-            lineplot.colors+=[None,None]
+            lineplot.colors+=['black',None]
         
         
         self._send_plot([lineplot])
 
+        return parameters[0]   
+
+
     def linefit_between(self,index1,index2,whatset=1):
         '''
         Creates two vectors (xtofit,ytofit) slicing out from the
@@ -310,12 +350,9 @@ class generalvclampCommands:
         # Translates the indexes into two vectors containing the x,y data to fit
         xtofit=self.plots[0].vectors[whatset][0][index1:index2]
         ytofit=self.plots[0].vectors[whatset][1][index1:index2]
-        
+
         # Does the actual linear fitting (simple least squares with numpy.polyfit)
         linefit=[]
         linefit=np.polyfit(xtofit,ytofit,1)
 
         return (linefit[0],linefit[1],xtofit,ytofit)
-    
-    
-