pcluster improved with density estimation and second PCA. next step will be to clean...
[hooke.git] / hooke.py
1 #!/usr/bin/env python
2
3 '''
4 HOOKE - A force spectroscopy review & analysis tool
5
6 (C) 2008 Massimo Sandal
7
8 Copyright (C) 2008 Massimo Sandal (University of Bologna, Italy).
9
10 This program is released under the GNU General Public License version 2.
11 '''
12
13 from libhooke import HOOKE_VERSION
14 from libhooke import WX_GOOD
15
16 import os
17
18 import wxversion
19 wxversion.select(WX_GOOD)
20 import wx
21 import wxmpl
22 from wx.lib.newevent import NewEvent
23
24 import matplotlib.numerix as nx
25 import scipy as sp
26
27 from threading import *
28 import Queue
29
30 from hooke_cli import HookeCli
31 from libhooke import *
32 import libhookecurve as lhc
33
34 #import file versions, just to know with what we're working...
35 from hooke_cli import __version__ as hookecli_version
36
37 global __version__
38 global events_from_gui
39 global config
40 global CLI_PLUGINS
41 global GUI_PLUGINS
42 global LOADED_PLUGINS
43 global PLOTMANIP_PLUGINS
44 global FILE_DRIVERS
45
46 __version__=HOOKE_VERSION[0]
47 __release_name__=HOOKE_VERSION[1]
48
49 events_from_gui=Queue.Queue() #GUI ---> CLI COMMUNICATION
50
51 print 'Starting Hooke.'
52 #CONFIGURATION FILE PARSING
53 config_obj=HookeConfig()
54 config=config_obj.load_config('hooke.conf')
55
56 #IMPORTING PLUGINS
57
58 CLI_PLUGINS=[]
59 GUI_PLUGINS=[]
60 PLOTMANIP_PLUGINS=[]
61 LOADED_PLUGINS=[]
62
63 plugin_commands_namespaces=[]
64 plugin_gui_namespaces=[]
65 for plugin_name in config['plugins']:
66     try:
67         plugin=__import__(plugin_name)
68         try:
69             eval('CLI_PLUGINS.append(plugin.'+plugin_name+'Commands)') #take Command plugin classes
70             plugin_commands_namespaces.append(dir(eval('plugin.'+plugin_name+'Commands')))
71         except:
72             pass
73         try:
74             eval('GUI_PLUGINS.append(plugin.'+plugin_name+'Gui)') #take Gui plugin classes
75             plugin_gui_namespaces.append(dir(eval('plugin.'+plugin_name+'Gui')))
76         except:
77             pass
78     except ImportError:
79         print 'Cannot find plugin ',plugin_name
80     else:
81         LOADED_PLUGINS.append(plugin_name)
82         print 'Imported plugin ',plugin_name
83       
84 #eliminate names common to all namespaces
85 for i in range(len(plugin_commands_namespaces)):
86     plugin_commands_namespaces[i]=[item for item in plugin_commands_namespaces[i] if (item != '__doc__' and item != '__module__' and item != '_plug_init')]
87 #check for conflicts in namespaces between plugins
88 #FIXME: only in commands now, because I don't have Gui plugins to check
89 #FIXME: how to check for plugin-defined variables (self.stuff) ??
90 plugin_commands_names=[]
91 whatplugin_defines=[]
92 plugin_gui_names=[]
93 for namespace,plugin_name in zip(plugin_commands_namespaces, config['plugins']):
94     for item in namespace:
95         if item in plugin_commands_names:
96             i=plugin_commands_names.index(item) #we exploit the fact index gives the *first* occurrence of a name...
97             print 'Error. Plugin ',plugin_name,' defines a function already defined by ',whatplugin_defines[i],'!'
98             print 'This should not happen. Please disable one or both plugins and contact the plugin authors to solve the conflict.'
99             print 'Hooke cannot continue.'
100             exit()
101         else:
102             plugin_commands_names.append(item)
103             whatplugin_defines.append(plugin_name)
104     
105
106 config['loaded_plugins']=LOADED_PLUGINS #FIXME: kludge -this should be global but not in config!
107 #IMPORTING DRIVERS
108 #FIXME: code duplication
109 FILE_DRIVERS=[]
110 LOADED_DRIVERS=[]
111 for driver_name in config['drivers']:
112     try:
113         driver=__import__(driver_name)
114         try:
115             eval('FILE_DRIVERS.append(driver.'+driver_name+'Driver)')
116         except:
117             pass
118     except ImportError:
119         print 'Cannot find driver ',driver_name
120     else:
121         LOADED_DRIVERS.append(driver_name)
122         print 'Imported driver ',driver_name
123 config['loaded_drivers']=LOADED_DRIVERS
124
125 #LIST OF CUSTOM WX EVENTS FOR CLI ---> GUI COMMUNICATION
126 #FIXME: do they need to be here?
127 list_of_events={}
128
129 plot_graph, EVT_PLOT = NewEvent()
130 list_of_events['plot_graph']=plot_graph
131
132 plot_contact, EVT_PLOT_CONTACT = NewEvent()
133 list_of_events['plot_contact']=plot_contact
134
135 measure_points, EVT_MEASURE_POINTS = NewEvent()
136 list_of_events['measure_points']=measure_points
137
138 export_image, EVT_EXPORT_IMAGE = NewEvent()
139 list_of_events['export_image']=export_image
140
141 close_plot, EVT_CLOSE_PLOT = NewEvent()
142 list_of_events['close_plot'] = close_plot
143
144 show_plots, EVT_SHOW_PLOTS = NewEvent()
145 list_of_events['show_plots'] = show_plots
146
147 get_displayed_plot, EVT_GET_DISPLAYED_PLOT = NewEvent()
148 list_of_events['get_displayed_plot'] = get_displayed_plot
149 #------------
150
151 class CliThread(Thread):
152     
153     def __init__(self,frame,list_of_events):
154         Thread.__init__(self)
155         
156         #here we have to put temporary references to pass to the cli object.
157         self.frame=frame
158         self.list_of_events=list_of_events
159         
160         self.debug=0 #to be used in the future
161         
162     def run(self):
163         print '\n\nThis is Hooke, version',__version__ , __release_name__
164         print
165         print '(c) Massimo Sandal & others, 2006-2008. Released under the GNU Lesser General Public License Version 3'
166         print 'Hooke is Free software.'
167         print '----'
168         print ''
169
170         def make_command_class(*bases):
171             #FIXME: perhaps redundant
172             return type(HookeCli)("HookeCliPlugged", bases + (HookeCli,), {})
173         cli = make_command_class(*CLI_PLUGINS)(self.frame,self.list_of_events,events_from_gui,config,FILE_DRIVERS)
174         cli.cmdloop()
175         
176 '''
177 GUI CODE
178
179 FIXME: put it in a separate module in the future?
180 '''
181 class MainMenuBar(wx.MenuBar):
182     '''
183     Creates the menu bar
184     '''
185     def __init__(self):
186         wx.MenuBar.__init__(self)
187         '''the menu description. the key of the menu is XX&Menu, where XX is a number telling
188         the order of the menus on the menubar.
189         &Menu is the Menu text
190         the corresponding argument is ('&Item', 'itemname'), where &Item is the item text and itemname
191         the inner reference to use in the self.menu_items dictionary.
192         
193         See create_menus() to see how it works
194         
195         Note: the mechanism on page 124 of "wxPython in Action" is less awkward, maybe, but I want
196         binding to be performed later. Perhaps I'm wrong :)
197         ''' 
198         
199         self.menu_desc={'00&File':[('&Open playlist','openplaymenu'),('&Exit','exitmenu')], 
200         '01&Edit':[('&Export text...','exporttextmenu'),('&Export image...','exportimagemenu')],
201         '02&Help':[('&About Hooke','aboutmenu')]}
202         self.create_menus()
203         
204     def create_menus(self):
205         '''
206         Smartish routine to create the menu from the self.menu_desc dictionary
207         Hope it's a workable solution for the future.
208         '''
209         self.menus=[] #the menu objects to append to the menubar
210         self.menu_items={} #the single menu items dictionary, to bind to events
211         
212         names=self.menu_desc.keys() #we gotta sort, because iterating keys goes in odd order
213         names.sort()
214         
215         for name in names:
216             self.menus.append(wx.Menu())
217             for menu_item in self.menu_desc[name]:
218                 self.menu_items[menu_item[1]]=self.menus[-1].Append(-1, menu_item[0])
219         
220         for menu,name in zip(self.menus,names):
221             self.Append(menu,name[2:])
222
223 class MainPanel(wx.Panel):
224     def __init__(self,parent,id):  
225        
226        wx.Panel.__init__(self,parent,id)
227        self.splitter = wx.SplitterWindow(self)
228        
229 ID_FRAME=100        
230 class MainWindow(wx.Frame):
231         '''we make a frame inheriting wx.Frame and setting up things on the init'''
232         def __init__(self,parent,id,title):
233             
234             #-----------------------------
235             #WX WIDGETS INITIALIZATION
236             
237             wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
238             
239             self.mainpanel=MainPanel(self,-1)
240             self.cpanels=[]
241             
242             self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))
243             self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))
244                        
245             self.statusbar=wx.StatusBar(self,-1)
246             self.SetStatusBar(self.statusbar)
247             
248             self.mainmenubar=MainMenuBar()
249             self.SetMenuBar(self.mainmenubar)
250             
251             self.controls=[]
252             self.figures=[]
253             self.axes=[]
254             
255             #This is our matplotlib plot
256             self.controls.append(wxmpl.PlotPanel(self.cpanels[0],-1))
257             self.controls.append(wxmpl.PlotPanel(self.cpanels[1],-1))
258             #These are our figure and axes, so to have easy references
259             #Also, we initialize
260             self.figures=[control.get_figure() for control in self.controls]
261             self.axes=[figure.gca() for figure in self.figures]
262             
263             self.cpanels[1].Hide()
264             self.mainpanel.splitter.Initialize(self.cpanels[0])
265                                    
266             self.sizer_dance() #place/size the widgets
267             
268             self.controls[0].SetSize(self.cpanels[0].GetSize())
269             self.controls[1].SetSize(self.cpanels[1].GetSize())
270             
271             #-------------------------------------------
272             #NON-WX WIDGETS INITIALIZATION
273             
274             #Flags.
275             self.click_plot=0
276                         
277             #FIXME: These could become a single flag with different (string?) values
278             #self.on_measure_distance=False
279             #self.on_measure_force=False
280             
281             self.plot_fit=False
282             
283             #Number of points to be clicked
284             self.num_of_points = 2
285             
286             #Data.
287             '''
288             self.current_x_ext=[[],[]]
289             self.current_y_ext=[[],[]]
290             self.current_x_ret=[[],[]]
291             self.current_y_ret=[[],[]]
292             
293             
294             self.current_x_unit=[None,None]
295             self.current_y_unit=[None,None]
296             '''
297                         
298             #Initialize xaxes, yaxes
299             #FIXME: should come from config
300             self.current_xaxes=0
301             self.current_yaxes=0
302             
303             #Other
304             
305             
306             self.index_buffer=[]
307                         
308             self.clicked_points=[]
309             
310             self.measure_set=None
311             
312             self.events_from_gui = events_from_gui
313             
314             '''
315             This dictionary keeps all the flags and the relative functon names that
316             have to be called when a point is clicked.
317             That is:
318             - if point is clicked AND foo_flag=True
319             - foo()
320             
321             Conversely, foo_flag is True if a corresponding event is launched by the CLI.
322             
323             self.ClickedPoints() takes care of handling this
324             '''
325             
326             self.click_flags_functions={'measure_points':[False, 'MeasurePoints']}
327             
328             #Binding of custom events from CLI --> GUI functions!                       
329             #FIXME: Should use the self.Bind() syntax
330             EVT_PLOT(self, self.PlotCurve)
331             EVT_PLOT_CONTACT(self, self.PlotContact)
332             EVT_GET_DISPLAYED_PLOT(self, self.OnGetDisplayedPlot)
333             EVT_MEASURE_POINTS(self, self.OnMeasurePoints)
334             EVT_EXPORT_IMAGE(self,self.ExportImage)
335             EVT_CLOSE_PLOT(self, self.OnClosePlot)
336             EVT_SHOW_PLOTS(self, self.OnShowPlots)
337                                                 
338             #This event and control decide what happens when I click on the plot 0.
339             wxmpl.EVT_POINT(self, self.controls[0].GetId(), self.ClickPoint0)
340             wxmpl.EVT_POINT(self, self.controls[1].GetId(), self.ClickPoint1)
341             
342             #RUN PLUGIN-SPECIFIC INITIALIZATION
343             #make sure we execute _plug_init() for every command line plugin we import
344             for plugin_name in config['plugins']:
345                 try:
346                     plugin=__import__(plugin_name)
347                     try:
348                         eval('plugin.'+plugin_name+'Gui._plug_init(self)')
349                         pass
350                     except AttributeError:
351                         pass
352                 except ImportError:
353                     pass
354             
355             
356         
357         #WX-SPECIFIC FUNCTIONS
358         def sizer_dance(self):
359             '''
360             adjust size and placement of wxpython widgets.
361             '''
362             self.splittersizer = wx.BoxSizer(wx.VERTICAL)
363             self.splittersizer.Add(self.mainpanel.splitter, 1, wx.EXPAND)
364             
365             self.plot1sizer = wx.BoxSizer()
366             self.plot1sizer.Add(self.controls[0], 1, wx.EXPAND)
367                         
368             self.plot2sizer = wx.BoxSizer()
369             self.plot2sizer.Add(self.controls[1], 1, wx.EXPAND)
370             
371             self.panelsizer=wx.BoxSizer()
372             self.panelsizer.Add(self.mainpanel, -1, wx.EXPAND)
373                        
374             self.cpanels[0].SetSizer(self.plot1sizer)
375             self.cpanels[1].SetSizer(self.plot2sizer)
376             
377             self.mainpanel.SetSizer(self.splittersizer)
378             self.SetSizer(self.panelsizer)
379             
380         def binding_dance(self):
381             self.Bind(wx.EVT_MENU, self.OnOpenPlayMenu, self.menubar.menu_items['openplaymenu'])
382             self.Bind(wx.EVT_MENU, self.OnExitMenu, self.menubar.menu_items['exitmenu'])
383             self.Bind(wx.EVT_MENU, self.OnExportText, self.menubar.menu_items['exporttextmenu'])
384             self.Bind(wx.EVT_MENU, self.OnExportImage, self.menubar.menu_items['exportimagemenu'])
385             self.Bind(wx.EVT_MENU, self.OnAboutMenu, self.menubar.menu_items['aboutmenu'])
386         
387         # DOUBLE PLOT MANAGEMENT
388         #----------------------
389         def show_both(self):
390             '''
391             Shows both plots.
392             '''
393             self.mainpanel.splitter.SplitHorizontally(self.cpanels[0],self.cpanels[1])
394             self.mainpanel.splitter.SetSashGravity(0.5)
395             self.mainpanel.splitter.SetSashPosition(300) #FIXME: we should get it and restore it
396             self.mainpanel.splitter.UpdateSize()
397             
398         def close_plot(self,plot):
399             '''
400             Closes one plot - only if it's open
401             '''
402             if not self.cpanels[plot].IsShown():
403                 return
404             if plot != 0:
405                 self.current_plot_dest = 0
406             else:
407                 self.current_plot_dest = 1
408             self.cpanels[plot].Hide()
409             self.mainpanel.splitter.Unsplit(self.cpanels[plot])
410             self.mainpanel.splitter.UpdateSize()
411             
412                     
413         def OnClosePlot(self,event):
414             self.close_plot(event.to_close)       
415             
416         def OnShowPlots(self,event):
417             self.show_both()
418             
419             
420         #FILE MENU FUNCTIONS
421         #--------------------
422         def OnOpenPlayMenu(self, event):
423             pass 
424            
425         def OnExitMenu(self,event):
426             pass
427         
428         def OnExportText(self,event):
429             pass
430         
431         def OnExportImage(self,event):
432             pass
433         
434         def OnAboutMenu(self,event):
435             pass
436             
437         #PLOT INTERACTION    
438         #----------------                        
439         def PlotCurve(self,event):
440             '''
441             plots the current ext,ret curve.
442             '''
443             dest=0
444             
445             #FIXME: BAD kludge following. There should be a well made plot queue mechanism, with replacements etc.
446             #---
447             #If we have only one plot in the event, we already have one in self.plots and this is a secondary plot,
448             #do not erase self.plots but append the new plot to it.
449             if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) == 1:
450                 self.plots.append(event.plots[0])
451             #if we already have two plots and a new secondary plot comes, we substitute the previous
452             if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) > 1:
453                 self.plots[1] = event.plots[0]
454             else:
455                 self.plots = event.plots
456             
457             #FIXME. Should be in PlotObject, somehow
458             c=0
459             for plot in self.plots:
460                 if self.plots[c].styles==[]:
461                     self.plots[c].styles=[None for item in plot.vectors] 
462                 if self.plots[c].colors==[]:
463                     self.plots[c].colors=[None for item in plot.vectors] 
464             
465             for plot in self.plots:
466                 '''
467                 MAIN LOOP FOR ALL PLOTS (now only 2 are allowed but...)
468                 '''
469                 if 'destination' in dir(plot):
470                     dest=plot.destination
471                 
472                 #if the requested panel is not shown, show it
473                 if not ( self.cpanels[dest].IsShown() ):
474                     self.show_both()
475             
476                 self.axes[dest].hold(False)
477                 self.current_vectors=plot.vectors
478                 self.current_title=plot.title
479                 self.current_plot_dest=dest #let's try this way to take into account the destination plot...
480                 
481                 c=0
482                             
483                 if len(plot.colors)==0:
484                     plot.colors=[None] * len(plot.vectors)
485                 if len(plot.styles)==0:
486                     plot.styles=[None] * len(plot.vectors)     
487                 
488                 for vectors_to_plot in self.current_vectors: 
489                     if plot.styles[c]=='scatter':
490                         if plot.colors[c]==None:
491                             self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1])
492                         else:
493                             self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1],color=plot.colors[c])
494                     else:
495                         if plot.colors[c]==None:
496                             self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1])
497                         else:
498                             self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1], color=plot.colors[c])
499                     self.axes[dest].hold(True)
500                     c+=1
501                     
502                 '''
503                 for vectors_to_plot in self.current_vectors:
504                     if len(vectors_to_plot)==2: #3d plots are to come...
505                         if len(plot.styles) > 0 and plot.styles[c] == 'scatter':
506                             self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1])
507                         elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':
508                             self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1],color='red')
509                         else:
510                             self.axes[dest].plot(vectors_to_plot[0],vectors_to_plot[1])
511                             
512                         self.axes[dest].hold(True)
513                         c+=1
514                     else:
515                         pass
516                 '''               
517                 #FIXME: tackles only 2d plots
518                 self.axes[dest].set_xlabel(plot.units[0])
519                 self.axes[dest].set_ylabel(plot.units[1])
520                                 
521                 #FIXME: set smaller fonts
522                 self.axes[dest].set_title(plot.title)
523                            
524                 if plot.xaxes: 
525                     #swap X axis
526                     xlim=self.axes[dest].get_xlim()
527                     self.axes[dest].set_xlim((xlim[1],xlim[0])) 
528                 if plot.yaxes:
529                     #swap Y axis
530                     ylim=self.axes[dest].get_ylim()        
531                     self.axes[dest].set_ylim((ylim[1],ylim[0])) 
532                 
533                 self.controls[dest].draw()
534             
535             
536         def PlotContact(self,event):
537             '''
538             plots the contact point
539             DEPRECATED!
540             '''
541             self.axes[0].hold(True)
542             self.current_contact_index=event.contact_index
543             
544             #now we fake a clicked point 
545             self.clicked_points.append(ClickedPoint())
546             self.clicked_points[-1].absolute_coords=self.current_x_ret[dest][self.current_contact_index], self.current_y_ret[dest][self.current_contact_index]
547             self.clicked_points[-1].is_marker=True    
548             
549             self._replot()
550             self.clicked_points=[]
551             
552         def OnMeasurePoints(self,event):
553             '''
554             trigger flags to measure N points
555             '''
556             self.click_flags_functions['measure_points'][0]=True
557             if 'num_of_points' in dir(event):
558                 self.num_of_points=event.num_of_points
559             if 'set' in dir(event):    
560                 self.measure_set=event.set            
561         
562         def ClickPoint0(self,event):
563             self.current_plot_dest=0
564             self.ClickPoint(event)
565         def ClickPoint1(self,event):
566             self.current_plot_dest=1
567             self.ClickPoint(event)
568             
569         def ClickPoint(self,event):
570             '''
571             this function decides what to do when we receive a left click on the axes.
572             We trigger other functions:
573             - the action chosen by the CLI sends an event
574             - the event raises a flag : self.click_flags_functions['foo'][0]
575             - the raised flag wants the function in self.click_flags_functions[1] to be called after a click
576             '''
577             for key, value in self.click_flags_functions.items():
578                 if value[0]:
579                     eval('self.'+value[1]+'(event)')
580                                       
581
582      
583         def MeasurePoints(self,event,current_set=1):
584             dest=self.current_plot_dest
585             try:
586                 current_set=self.measure_set
587             except AttributeError:
588                 pass
589             
590             #find the current plot matching the clicked destination
591             plot=self._plot_of_dest()
592             if len(plot.vectors)-1 < current_set: #what happens if current_set is 1 and we have only 1 vector?
593                 current_set=current_set-len(plot.vectors)
594                 
595             xvector=plot.vectors[current_set][0]
596             yvector=plot.vectors[current_set][1]
597             
598             self.clicked_points.append(ClickedPoint())            
599             self.clicked_points[-1].absolute_coords=event.xdata, event.ydata
600             self.clicked_points[-1].find_graph_coords(xvector,yvector)
601             self.clicked_points[-1].is_marker=True    
602             self.clicked_points[-1].is_line_edge=True
603             self.clicked_points[-1].dest=dest                
604             
605             self._replot()
606             
607             if len(self.clicked_points)==self.num_of_points:
608                 self.events_from_gui.put(self.clicked_points)
609                 #restore to default state:
610                 self.clicked_points=[]
611                 self.click_flags_functions['measure_points'][0]=False    
612                 
613         
614         def OnGetDisplayedPlot(self,event):
615             if 'dest' in dir(event):
616                 self.GetDisplayedPlot(event.dest)
617             else:
618                 self.GetDisplayedPlot(self.current_plot_dest)
619             
620         def GetDisplayedPlot(self,dest):
621             '''
622             returns to the CLI the currently displayed plot for the given destination
623             '''
624             displayed_plot=self._plot_of_dest(dest)
625             events_from_gui.put(displayed_plot)
626                 
627         def ExportImage(self,event):
628             '''
629             exports an image as a file.
630             Current supported file formats: png, eps
631             (matplotlib docs say that jpeg should be supported too, but with .jpg it doesn't work for me!)
632             '''
633             #dest=self.current_plot_dest
634             dest=event.dest
635             filename=event.name
636             self.figures[dest].savefig(filename)
637                
638         '''
639         def _find_nearest_point(self, mypoint, dataset=1):
640             
641             #Given a clicked point on the plot, finds the nearest point in the dataset (in X) that
642             #corresponds to the clicked point.
643             
644             dest=self.current_plot_dest
645             
646             xvector=plot.vectors[dataset][0]
647             yvector=plot.vectors[dataset][1]
648             
649             #Ye Olde sorting algorithm...
650             #FIXME: is there a better solution?
651             index=0
652             best_index=0
653             best_diff=10^9 #hope we never go over this magic number :(
654             for point in xvector:
655                 diff=abs(point-mypoint)
656                 if diff<best_diff:
657                     best_index=index
658                     best_diff=diff
659                 index+=1
660             
661             return best_index,xvector[best_index],yvector[best_index]
662          '''   
663         
664         def _plot_of_dest(self,dest=None):
665             '''
666             returns the plot that has the current destination
667             '''
668             if dest==None:
669                 dest=self.current_plot_dest
670                 
671             plot=None
672             for aplot in self.plots:
673                 if aplot.destination == dest:
674                     plot=aplot
675             return plot
676             
677         def _replot(self):
678             '''
679             this routine is needed for a fresh clean-and-replot of interface
680             otherwise, refreshing works very badly :(
681             
682             thanks to Ken McIvor, wxmpl author!
683             '''
684             dest=self.current_plot_dest
685             #we get current zoom limits
686             xlim=self.axes[dest].get_xlim()
687             ylim=self.axes[dest].get_ylim()           
688             #clear axes
689             self.axes[dest].cla()
690    
691             #Plot curve:         
692             #find the current plot matching the clicked destination
693             plot=self._plot_of_dest()
694             #plot all superimposed plots 
695             c=0 
696             if len(plot.colors)==0:
697                     plot.colors=[None] * len(plot.vectors)
698             if len(plot.styles)==0:
699                     plot.styles=[None] * len(plot.vectors)     
700             for plotset in plot.vectors: 
701                 if plot.styles[c]=='scatter':
702                     if plot.colors[c]==None:
703                         self.axes[dest].scatter(plotset[0], plotset[1])
704                     else:
705                         self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])
706                 else:
707                     if plot.colors[c]==None:
708                         self.axes[dest].plot(plotset[0], plotset[1])
709                     else:
710                         self.axes[dest].plot(plotset[0], plotset[1], color=plot.colors[c])
711                 '''    
712                 if len(plot.styles) > 0 and plot.styles[c]=='scatter':
713                     self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])
714                 elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':
715                     self.axes[dest].scatter(plotset[0],plotset[1],color='red')
716                 else:
717                     self.axes[dest].plot(plotset[0], plotset[1])
718                 '''
719                 c+=1
720             #plot points we have clicked
721             for item in self.clicked_points:
722                 if item.is_marker:
723                     if item.graph_coords==(None,None): #if we have no graph coords, we display absolute coords
724                         self.axes[dest].scatter([item.absolute_coords[0]],[item.absolute_coords[1]])
725                     else:
726                         self.axes[dest].scatter([item.graph_coords[0]],[item.graph_coords[1]])               
727                     
728             if self.plot_fit:
729                 print 'DEBUGGING WARNING: use of self.plot_fit is deprecated!'
730                 self.axes[dest].plot(self.plot_fit[0],self.plot_fit[1])
731                     
732             self.axes[dest].hold(True)      
733             #set old axes again
734             self.axes[dest].set_xlim(xlim)
735             self.axes[dest].set_ylim(ylim)
736             #set title and names again...
737             self.axes[dest].set_title(self.current_title)           
738             self.axes[dest].set_xlabel(plot.units[0])
739             self.axes[dest].set_ylabel(plot.units[1])
740             #and redraw!
741             self.controls[dest].draw()
742             
743
744 class MySplashScreen(wx.SplashScreen):
745     """
746     Create a splash screen widget.
747     That's just a fancy addition... every serious application has a splash screen!
748     """
749     def __init__(self, frame):
750         # This is a recipe to a the screen.
751         # Modify the following variables as necessary.
752         #aBitmap = wx.Image(name = "wxPyWiki.jpg").ConvertToBitmap()
753         aBitmap=wx.Image(name='hooke.jpg').ConvertToBitmap()
754         splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
755         splashDuration = 2000 # milliseconds
756         splashCallback = None
757         # Call the constructor with the above arguments in exactly the
758         # following order.
759         wx.SplashScreen.__init__(self, aBitmap, splashStyle,
760                                  splashDuration, None, -1)
761         wx.EVT_CLOSE(self, self.OnExit)
762         self.frame=frame
763         wx.Yield()
764
765     def OnExit(self, evt):
766         self.Hide()
767         
768         self.frame.Show()
769         # The program will freeze without this line.
770         evt.Skip()  # Make sure the default handler runs too...
771
772         
773 #------------------------------------------------------------------------------
774                 
775 def main():
776     
777     #save the directory where Hooke is located
778     config['hookedir']=os.getcwd()
779     
780     #now change to the working directory.
781     try:
782         os.chdir(config['workdir'])
783     except OSError:
784         print "Warning: Invalid work directory."
785     
786     app=wx.PySimpleApp()
787        
788     def make_gui_class(*bases):
789             return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {})
790             
791     main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__))
792        
793     #FIXME. The frame.Show() is called by the splashscreen here! Ugly as hell.
794     
795     mysplash=MySplashScreen(main_frame)
796     mysplash.Show()
797     
798     my_cmdline=CliThread(main_frame, list_of_events)
799     my_cmdline.start()
800         
801     
802     app.MainLoop()
803     
804 main()