f9f2f33d9d5ad0e9aa4795eaf2e01d0a5ad95f8f
[hooke.git] / tutorial.py
1 #!/usr/bin/env python
2
3 '''
4 TUTORIAL PLUGIN FOR HOOKE
5
6 This plugin contains example commands to teach how to write an Hooke plugin, including description of main Hooke
7 internals.
8 (c)Massimo Sandal 2007
9 '''
10
11 import libhookecurve as lhc
12
13 import numpy as np
14
15 '''
16 SYNTAX OF DATA TYPE DECLARATION:
17     type = type of object
18     [ type ] = list containing objects of type
19     {typekey:typearg} = dictionary with keys of type typekey and args of type typearg
20     ( type ) = tuple containing objects of type
21 '''
22
23
24 class tutorialCommands:
25     '''
26     Here we define the class containing all the Hooke commands we want to define
27     in the plugin.
28     
29     Notice the class name!!
30     The syntax is filenameCommands. That is, if your plugin is pluggy.py, your class
31     name is pluggyCommands.
32     
33     Otherwise, the class will be ignored by Hooke.
34     ''' 
35     
36     def _plug_init(self):
37         '''
38         This is the plugin initialization.
39         When Hooke starts and the plugin is loaded, this function is executed.
40         If there is something you need to do when Hooke starts, code it in this function.
41         '''
42         print 'I am the Tutorial plugin initialization!'
43         
44         #Here we initialize a local configuration variable; see plotmanip_absvalue() for explanation.
45         self.config['tutorial_absvalue']=0 
46         pass
47     
48     def do_nothing(self,args):
49         '''
50         This is a boring but working example of an actual Hooke command.
51         A Hooke command is a function of the xxxxCommands class, which is ALWAYS defined
52         this way:
53         
54         def do_nameofcommand(self,args)
55         
56         *do_            is needed to make Hooke understand this function is a command
57         *nameofcommand  is how the command will be called in the Hooke command line.
58         *self           is, well, self
59         *args           is ALWAYS needed (otherwise Hooke will crash executing the command). We will see
60                         later what args is.
61         
62         Note that if you now start Hooke with this plugin activated and you type in the Hooke command
63         line "help nothing" you will see this very text as output. So the help of a command is a
64         string comment below the function definition, like this one.
65         
66         Commands usually return None.
67         '''
68         print 'I am a Hooke command. I do nothing.'
69         
70     def do_printargs(self,args):
71         '''
72         This command prints the args you give to it.
73         args is always a string, that contains everything you write after the command.
74         So if you issue "mycommand blah blah 12345" args is "blah blah 12345".
75         
76         Again, args is needed in the definition even if your command does not use it.
77         '''
78         print 'You gave me those args: '+args
79         
80     def help_tutorial(self):
81         '''
82         This is a help function. 
83         If you want a help function for something that is not a command, you can write a help
84         function like this. Calling "help tutorial" will execute this function.
85         '''
86         print 'You called help_tutorial()'
87         
88     def do_environment(self,args):
89         '''
90         This plugin contains a panoramic of the Hooke command line environment variables,
91         and prints their current value.
92         '''
93         
94         '''self.current_list
95         TYPE: [ libhookecurve.HookeCurve ], len=variable
96         contains the actual playlist of Hooke curve objects.
97         Each HookeCurve object represents a reference to a data file.
98         We will see later in detail how do they work.
99         '''
100         print 'current_list length:',len(self.current_list)
101         print 'current_list 0th:',self.current_list[0]
102         
103         '''self.pointer
104         TYPE: int
105         contains the index of
106         the current curve in the playlist
107         '''
108         print 'pointer: ',self.pointer
109         
110         '''self.current
111         TYPE: libhookecurve.HookeCurve
112         contains the current curve displayed.
113         We will see later how it works.
114         '''
115         print 'current:',self.current
116         
117         '''self.plots
118         TYPE: [ libhookecurve.PlotObject ], len=1,2
119         contains the current default plots.
120         Each PlotObject contains all info needed to display 
121         the plot: apart from the data vectors, the title, destination
122         etc.
123         Usually self.plots[0] is the default topmost plot, self.plots[1] is the
124         accessory bottom plot.
125         '''
126         print 'plots:',self.plots
127         
128         '''self.config
129         TYPE: { string:anything }
130         contains the current Hooke configuration variables, in form of a dictionary.
131         '''
132         print 'config:',self.config
133         
134         '''self.plotmanip
135         TYPE: [ function ]
136         Contains the ordered plot manipulation functions.
137         These functions are called to modify the default plot by default before it is plotted.
138         self.plots contains the plot passed through the plot manipulators.
139         We will see it better later.
140         *YOU SHOULD NEVER MODIFY THAT*
141         '''
142         print 'plotmanip: ',self.plotmanip
143         
144         '''self.drivers
145         TYPE: [ class ]
146         Contains the plot reading drivers.
147         *YOU SHOULD NEVER MODIFY THAT*
148         '''
149         print 'drivers: ',self.drivers
150         
151         '''self.frame
152         TYPE: wx.Frame
153         Contains the wx Frame of the GUI.
154         ***NEVER, EVER TOUCH THAT.***
155         '''
156         print 'frame: ',self.frame
157         
158         '''self.list_of_events
159         TYPE: { string:wx.Event }
160         Contains the wx.Events to communicate with the GUI.
161         Usually not necessary to use it, unless you want
162         to create a GUI plugin.
163         '''
164         print 'list of events:',self.list_of_events
165         
166         '''self.events_from_gui
167         TYPE: Queue.Queue
168         Contains the Queue where data from the GUI is put.
169         Usually not necessary to use it, unless you want
170         to create a GUI plugin.
171         '''
172         print 'events from gui:',self.events_from_gui
173         
174         '''self.playlist_saved
175         TYPE: Int (0/1) ; Boolean
176         Flag that tells if the playlist has been saved or not.
177         '''
178         print 'playlist saved:',self.playlist_saved
179         
180         '''self.playlist_name
181         TYPE: string
182         Name of current playlist
183         '''
184         print 'playlist name:',self.playlist_name
185         
186         '''self.notes_saved
187         TYPE: Int (0/1) ; Boolean
188         Flag that tells if the playlist has been saved or not.
189         '''
190         print 'notes saved:',self.notes_saved
191         
192
193     def do_myfirstplot(self,args):
194         '''
195         In this function, we see how to create a PlotObject and send it to the screen.
196         ***Read the code of PlotObject in libhookecurve.py before!***.
197         '''
198         
199         #We generate some interesting data to plot for this example.
200         xdata1=np.arange(-5,5,0.1)
201         xdata2=np.arange(-5,5,0.1)
202         ydata1=[item**2 for item in xdata1]
203         ydata2=[item**3 for item in xdata2]
204         
205         #Create the object.
206         #The PlotObject class lives in the libhookecurve library.
207         myplot=lhc.PlotObject()
208         '''
209         The *data* of the plot live in the .vectors list. 
210         
211         plot.vectors is a multidimensional array:
212         plot.vectors[0]=set1
213         plot.vectors[1]=set2
214         plot.vectors[2]=sett3
215         etc.
216         
217         2 curves in a x,y plot are:
218         [[[x1],[y1]],[[x2],[y2]]]
219         for example:
220             x1          y1              x2         y2
221         [[[1,2,3,4],[10,20,30,40]],[[3,6,9,12],[30,60,90,120]]]
222         x1 = self.vectors[0][0]
223         y1 = self.vectors[0][1]
224         x2 = self.vectors[1][0]
225         y2 = self.vectors[1][1]
226         '''
227         #Pour 0-th dataset into myplot: 
228         myplot.add_set(xdata1,ydata1)
229         
230         #Pour 1-st dataset into myplot: 
231         myplot.add_set(xdata2,ydata2)
232         
233         #Add units to x and y axes
234         #units=[string, string]
235         myplot.units=['x axis','y axis']
236         
237         #Where do we want the plot? 0=top, 1=bottom
238         myplot.destination=1
239         
240         '''Send it to the GUI.
241         Note that you *have* to encapsulate it into a list, so you
242         have to send [myplot], not simply myplot.
243         
244         You can also send more two plots at once
245         self.send_plot([plot1,plot2])
246         '''
247         self._send_plot([myplot])
248         
249
250     def do_myfirstscatter(self,args):
251         '''
252         How to draw a scatter plot.
253         '''
254         #We generate some interesting data to plot for this example.
255         xdata1=np.arange(-5,5,1)
256         xdata2=np.arange(-5,5,1)
257         ydata1=[item**2 for item in xdata1]
258         ydata2=[item**3 for item in xdata2]
259         
260         myplot=lhc.PlotObject()
261         myplot.add_set(xdata1,ydata1)
262         myplot.add_set(xdata2,ydata2)
263         
264         
265         #Add units to x and y axes
266         myplot.units=['x axis','y axis']
267         
268         #Where do we want the plot? 0=top, 1=bottom
269         myplot.destination=1
270         
271         '''None=standard line plot
272         'scatter'=scatter plot
273         By default, the styles attribute is an empty list. If you
274         want to define a scatter plot, you must define all other
275         plots as None or 'scatter', depending on what you want.
276         
277         Here we define the second set to be plotted as scatter,
278         and the first to be plotted as line.
279         
280         Here we define also the colors to be the default Matplotlib colors
281         '''
282         myplot.styles=[None,'scatter']
283         myplot.colors=[None,None]
284         self._send_plot([myplot])
285         
286
287     def do_clickaround(self,args):
288         '''
289         Here we click two points on the curve and take some parameters from the points
290         we have clicked.
291         '''
292         
293         '''
294         points = self._measure_N_points(N=Int, whatset=Int)
295         *N = number of points to measure(1...n)
296         *whatset = data set to measure (0,1...n)
297         *points = a list of ClickedPoint objects, one for each point requested
298         '''
299         points=self._measure_N_points(N=2,whatset=1)
300         print 'You clicked the following points.'
301         
302         '''
303         These are the absolute coordinates of the
304         point clicked. 
305         [float, float] = x,y
306         '''
307         print 'Absolute coordinates:'
308         print points[0].absolute_coords
309         print points[1].absolute_coords
310         print
311         
312         '''
313         These are the coordinates of the points
314         clicked, remapped on the graph.
315         Hooke looks at the graph point which X
316         coordinate is next to the X coordinate of
317         the point measured, and uses that point
318         as the actual clicked point.
319         [float, float] = x,y
320         '''
321         print 'Coordinates on the graph:'
322         print points[0].graph_coords
323         print points[1].graph_coords
324         print
325         
326         '''
327         These are the indexes of the clicked points
328         on the dataset vector.
329         '''
330         print 'Index of points on the graph:'
331         print points[0].index
332         print points[1].index
333         
334         
335     def help_thedifferentplots(self):
336         '''
337         The *three* different default plots you should be familiar with
338         in Hooke.
339         
340         Each plot contains of course the respective data in their
341         vectors attribute, so here you learn also which data access for
342         each situation.
343         '''
344         print '''
345         1. THE RAW, CURRENT PLOTS
346         
347         self.current
348         ---
349         Contains the current libhookecurve.HookeCurve container object.
350         A HookeCurve object defines only two default attributes:
351         
352         * self.current.path = string
353         The path of the current displayed curve
354         
355         * self.current.curve = libhookecurve.Driver
356         The curve object. This is not only generated by the driver,
357         this IS a driver instance in itself.
358         This means that in self.current.curve you can access the
359         specific driver APIs, if you know them.
360         
361         And defines only one method:
362         * self.current.identify()
363         Fills in the self.current.curve object.
364         See in the cycling tutorial.
365         
366         *****
367         The REAL curve data actually lives in:
368         ---
369         * self.current.curve.default_plots() = [ libhooke.PlotObject ]
370         Contains the raw PlotObject-s, as "spitted out" by the driver, without any
371         intervention.
372         This is as close to the raw data as Hooke gets.
373         
374         One or two plots can be spit out; they are always enclosed in a list.
375         *****
376         
377         Methods of self.current.curve are:
378         ---
379         
380         * self.current.curve.is_me()
381         (Used by identify() only.)
382         
383         * self.current.curve.close_all()
384         Closes all driver open files; see the cycling tutorial.
385         '''
386         
387         print '''
388         2. THE PROCESSED, DEFAULT PLOT
389         
390         The plot that is spitted out by the driver is *not* the usual default plot
391         that is displayed by calling "plot" at the Hooke prompt.
392         
393         This is because the raw, driver-generated plot is usually *processed* by so called
394         *plot processing* functions. We will see in the tutorial how to define
395         them. 
396         
397         For example, in force spectroscopy force curves, raw data are automatically corrected
398         for deflection. Other data can be, say, filtered by default.
399                 
400         The default plots are accessible in 
401         self.plots = [ libhooke.PlotObject ]
402         
403         self.plots[0] is usually the topmost plot
404         self.plots[1] is usually the bottom plot (if present)
405         '''
406         
407         print '''
408         3. THE PLOT DISPLAYED RIGHT NOW.
409         
410         Sometimes the plots you are displaying *right now* is different from the previous
411         two. You may have a fit trace, you may have issued some command that spits out
412         a custom plot and you want to rework that, whatever. 
413         
414         You can obtain in any moment the plot currently displayed by Hooke by issuing
415         
416         PlotObject = self._get_displayed_plot(dest)
417         * dest = Int (0/1)
418         dest=0 : top plot
419         dest=1 : bottom plot
420         '''
421     
422     
423     def do_cycling(self,args):
424         '''
425         Here we cycle through our playlist and print some info on the curves we find.
426         Cycling through the playlist needs a bit of care to avoid memory leaks and dangling
427         open files...
428         
429         Look at the source code for more information.
430         '''
431         
432         def things_when_cycling(item):
433             '''
434             We encapsulate here everything has to open the actual curve file.
435             By doing it all here, we avoid to do acrobacies when deleting objects etc.
436             in the main loop: we do the dirty stuff here.
437             '''
438             
439             '''
440             identify()
441         
442             This method looks for the correct driver in self.drivers to use;
443             and puts the curve content in the .curve attribute.
444             Basically, until identify() is called, the HookeCurve object
445             is just an empty shell. When identify() is called (usually by
446             the Hooke plot routine), the HookeCurve object is "filled" with
447             the actual curve.
448             '''
449           
450             item.identify(self.drivers)
451             
452             '''
453             After the identify(), item.curve contains the curve, and item.curve.default_plots() behaves exactly like
454             self.current.curve.default_plots() -but for the given item.
455             '''
456             itplot=item.curve.default_plots()
457             
458             print 'length of X1 vector:',len(itplot[0].vectors[0][0]) #just to show something
459             
460             '''
461             The following three lines are a magic spell you HAVE to do
462             before closing the function.
463             (Otherwise you will be plagued by unpredicatable, system-dependent bugs.)
464             '''
465             item.curve.close_all() #Avoid open files dangling
466             del item.curve #Avoid memory leaks
467             del item #Just be paranoid. Don't ask.
468             
469             return
470         
471         
472         c=0
473         for item in self.current_list:
474             print 'Looking at curve ',c,'of',len(self.current_list)
475             things_when_cycling(item)
476             c+=1
477         
478         return
479         
480             
481         
482     def plotmanip_absvalue(self, plot, current, customvalue=None):
483         '''
484         This function defines a PLOT MANIPULATOR.
485         A plot manipulator is a function that takes a plot in input, does something to the plot
486         and returns the modified plot in output.
487         The function, once plugged, gets automatically called everytime self.plots is updated
488         
489         For example, in force spectroscopy force curves, raw data are automatically corrected
490         for deflection. Other data can be, say, filtered by default.
491         
492         To create and activate a plot manipulator you have to:
493             * Write a function (like this) which name starts with "plotmanip_" (just like commands
494               start with "do_")
495             * The function must support four arguments:
496               self : (as usual)
497               plot : a plot object
498               current : (usually not used, deprecated)
499               customvalue=None : a variable containing custom value(s) you need for your plot manipulators.
500             * The function must return a plot object.
501             * Add an entry in hooke.conf: if your function is "plotmanip_something" you will have
502               to add <something/> in the plotmanips section: example
503             
504             <plotmanips>
505                 <detriggerize/>
506                 <correct/>
507                 <median/>
508                 <something/>        
509             </plotmanips>
510             
511             Important: Plot manipulators are *in pipe*: each plot manipulator output becomes the input of the next one.
512             The order in hooke.conf *is the order* in which plot manipulators are connected, so in the example above
513             we have:
514             self.current.curve.default_plots() --> detriggerize --> correct --> median --> something --> self.plots
515         '''
516         
517         '''
518         Here we see what is in a configuration variable to enable/disable the plot manipulator as user will using
519         the Hooke "set" command.
520         Typing "set tutorial_absvalue 0" disables the plot manipulator; typing "set tutorial_absvalue 1" will enable it.
521         '''
522         if not self.config['tutorial_absvalue']:
523             return plot
524         
525         #We do something to the plot, for demonstration's sake
526         #If we needed variables, we would have used customvalue.
527         plot.vectors[0][1]=[abs(i) for i in plot.vectors[0][1]]
528         plot.vectors[1][1]=[abs(i) for i in plot.vectors[1][1]]
529         
530         #Return the plot object.
531         return plot
532             
533         
534 #TODO IN TUTORIAL:
535 #how to add lines to an existing plot!!
536 #peaks
537 #configuration files
538 #gui plugins