4 HOOKE - A force spectroscopy review & analysis tool
6 (C) 2008 Massimo Sandal
8 Copyright (C) 2008 Massimo Sandal (University of Bologna, Italy).
10 This program is released under the GNU General Public License version 2.
13 from libhooke import HOOKE_VERSION
14 from libhooke import WX_GOOD
19 wxversion.select(WX_GOOD)
22 from wx.lib.newevent import NewEvent
24 import matplotlib.numerix as nx
27 from threading import *
30 from hooke_cli import HookeCli
31 from libhooke import *
32 import libhookecurve as lhc
34 #import file versions, just to know with what we're working...
35 from hooke_cli import __version__ as hookecli_version
38 global events_from_gui
43 global PLOTMANIP_PLUGINS
46 __version__=HOOKE_VERSION[0]
47 __release_name__=HOOKE_VERSION[1]
49 events_from_gui=Queue.Queue() #GUI ---> CLI COMMUNICATION
51 print 'Starting Hooke.'
52 #CONFIGURATION FILE PARSING
53 config_obj=HookeConfig()
54 config=config_obj.load_config('hooke.conf')
63 plugin_commands_namespaces=[]
64 plugin_gui_namespaces=[]
65 for plugin_name in config['plugins']:
67 plugin=__import__(plugin_name)
69 eval('CLI_PLUGINS.append(plugin.'+plugin_name+'Commands)') #take Command plugin classes
70 plugin_commands_namespaces.append(dir(eval('plugin.'+plugin_name+'Commands')))
74 eval('GUI_PLUGINS.append(plugin.'+plugin_name+'Gui)') #take Gui plugin classes
75 plugin_gui_namespaces.append(dir(eval('plugin.'+plugin_name+'Gui')))
79 print 'Cannot find plugin ',plugin_name
81 LOADED_PLUGINS.append(plugin_name)
82 print 'Imported plugin ',plugin_name
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=[]
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.'
102 plugin_commands_names.append(item)
103 whatplugin_defines.append(plugin_name)
106 config['loaded_plugins']=LOADED_PLUGINS #FIXME: kludge -this should be global but not in config!
108 #FIXME: code duplication
111 for driver_name in config['drivers']:
113 driver=__import__(driver_name)
115 eval('FILE_DRIVERS.append(driver.'+driver_name+'Driver)')
119 print 'Cannot find driver ',driver_name
121 LOADED_DRIVERS.append(driver_name)
122 print 'Imported driver ',driver_name
123 config['loaded_drivers']=LOADED_DRIVERS
125 #LIST OF CUSTOM WX EVENTS FOR CLI ---> GUI COMMUNICATION
126 #FIXME: do they need to be here?
129 plot_graph, EVT_PLOT = NewEvent()
130 list_of_events['plot_graph']=plot_graph
132 plot_contact, EVT_PLOT_CONTACT = NewEvent()
133 list_of_events['plot_contact']=plot_contact
135 measure_points, EVT_MEASURE_POINTS = NewEvent()
136 list_of_events['measure_points']=measure_points
138 export_image, EVT_EXPORT_IMAGE = NewEvent()
139 list_of_events['export_image']=export_image
141 close_plot, EVT_CLOSE_PLOT = NewEvent()
142 list_of_events['close_plot'] = close_plot
144 show_plots, EVT_SHOW_PLOTS = NewEvent()
145 list_of_events['show_plots'] = show_plots
147 get_displayed_plot, EVT_GET_DISPLAYED_PLOT = NewEvent()
148 list_of_events['get_displayed_plot'] = get_displayed_plot
151 class CliThread(Thread):
153 def __init__(self,frame,list_of_events):
154 Thread.__init__(self)
156 #here we have to put temporary references to pass to the cli object.
158 self.list_of_events=list_of_events
160 self.debug=0 #to be used in the future
163 print '\n\nThis is Hooke, version',__version__ , __release_name__
165 print '(c) Massimo Sandal & others, 2006-2008. Released under the GNU Lesser General Public License Version 3'
166 print 'Hooke is Free software.'
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)
179 FIXME: put it in a separate module in the future?
181 class MainMenuBar(wx.MenuBar):
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.
193 See create_menus() to see how it works
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 :)
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')]}
204 def create_menus(self):
206 Smartish routine to create the menu from the self.menu_desc dictionary
207 Hope it's a workable solution for the future.
209 self.menus=[] #the menu objects to append to the menubar
210 self.menu_items={} #the single menu items dictionary, to bind to events
212 names=self.menu_desc.keys() #we gotta sort, because iterating keys goes in odd order
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])
220 for menu,name in zip(self.menus,names):
221 self.Append(menu,name[2:])
223 class MainPanel(wx.Panel):
224 def __init__(self,parent,id):
226 wx.Panel.__init__(self,parent,id)
227 self.splitter = wx.SplitterWindow(self)
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):
234 #-----------------------------
235 #WX WIDGETS INITIALIZATION
237 wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
239 self.mainpanel=MainPanel(self,-1)
242 self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))
243 self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))
245 self.statusbar=wx.StatusBar(self,-1)
246 self.SetStatusBar(self.statusbar)
248 self.mainmenubar=MainMenuBar()
249 self.SetMenuBar(self.mainmenubar)
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
260 self.figures=[control.get_figure() for control in self.controls]
261 self.axes=[figure.gca() for figure in self.figures]
263 self.cpanels[1].Hide()
264 self.mainpanel.splitter.Initialize(self.cpanels[0])
266 self.sizer_dance() #place/size the widgets
268 self.controls[0].SetSize(self.cpanels[0].GetSize())
269 self.controls[1].SetSize(self.cpanels[1].GetSize())
271 #-------------------------------------------
272 #NON-WX WIDGETS INITIALIZATION
277 #FIXME: These could become a single flag with different (string?) values
278 self.on_measure_distance=False
279 self.on_measure_force=False
283 #Number of points to be clicked
284 self.num_of_points = 2
287 self.current_x_ext=[[],[]]
288 self.current_y_ext=[[],[]]
289 self.current_x_ret=[[],[]]
290 self.current_y_ret=[[],[]]
292 self.current_x_unit=[None,None]
293 self.current_y_unit=[None,None]
295 #Initialize xaxes, yaxes
296 #FIXME: should come from config
305 self.clicked_points=[]
307 self.measure_set=None
309 self.events_from_gui = events_from_gui
312 This dictionary keeps all the flags and the relative functon names that
313 have to be called when a point is clicked.
315 - if point is clicked AND foo_flag=True
318 Conversely, foo_flag is True if a corresponding event is launched by the CLI.
320 self.ClickedPoints() takes care of handling this
323 self.click_flags_functions={'measure_points':[False, 'MeasurePoints']}
325 #Custom events from CLI --> GUI functions!
326 #FIXME: Should use the self.Bind() syntax
327 EVT_PLOT(self, self.PlotCurve)
328 EVT_PLOT_CONTACT(self, self.PlotContact)
329 EVT_GET_DISPLAYED_PLOT(self, self.OnGetDisplayedPlot)
330 EVT_MEASURE_POINTS(self, self.OnMeasurePoints)
331 EVT_EXPORT_IMAGE(self,self.ExportImage)
332 EVT_CLOSE_PLOT(self, self.OnClosePlot)
333 EVT_SHOW_PLOTS(self, self.OnShowPlots)
335 #This event and control decide what happens when I click on the plot 0.
336 wxmpl.EVT_POINT(self, self.controls[0].GetId(), self.ClickPoint0)
337 wxmpl.EVT_POINT(self, self.controls[1].GetId(), self.ClickPoint1)
339 #RUN PLUGIN-SPECIFIC INITIALIZATION
340 #make sure we execute _plug_init() for every command line plugin we import
341 for plugin_name in config['plugins']:
343 plugin=__import__(plugin_name)
345 eval('plugin.'+plugin_name+'Gui._plug_init(self)')
347 except AttributeError:
354 #WX-SPECIFIC FUNCTIONS
355 def sizer_dance(self):
357 adjust size and placement of wxpython widgets.
359 self.splittersizer = wx.BoxSizer(wx.VERTICAL)
360 self.splittersizer.Add(self.mainpanel.splitter, 1, wx.EXPAND)
362 self.plot1sizer = wx.BoxSizer()
363 self.plot1sizer.Add(self.controls[0], 1, wx.EXPAND)
365 self.plot2sizer = wx.BoxSizer()
366 self.plot2sizer.Add(self.controls[1], 1, wx.EXPAND)
368 self.panelsizer=wx.BoxSizer()
369 self.panelsizer.Add(self.mainpanel, -1, wx.EXPAND)
371 self.cpanels[0].SetSizer(self.plot1sizer)
372 self.cpanels[1].SetSizer(self.plot2sizer)
374 self.mainpanel.SetSizer(self.splittersizer)
375 self.SetSizer(self.panelsizer)
377 def binding_dance(self):
378 self.Bind(wx.EVT_MENU, self.OnOpenPlayMenu, self.menubar.menu_items['openplaymenu'])
379 self.Bind(wx.EVT_MENU, self.OnExitMenu, self.menubar.menu_items['exitmenu'])
380 self.Bind(wx.EVT_MENU, self.OnExportText, self.menubar.menu_items['exporttextmenu'])
381 self.Bind(wx.EVT_MENU, self.OnExportImage, self.menubar.menu_items['exportimagemenu'])
382 self.Bind(wx.EVT_MENU, self.OnAboutMenu, self.menubar.menu_items['aboutmenu'])
384 # DOUBLE PLOT MANAGEMENT
385 #----------------------
390 self.mainpanel.splitter.SplitHorizontally(self.cpanels[0],self.cpanels[1])
391 self.mainpanel.splitter.SetSashGravity(0.5)
392 self.mainpanel.splitter.SetSashPosition(300) #FIXME: we should get it and restore it
393 self.mainpanel.splitter.UpdateSize()
395 def close_plot(self,plot):
397 Closes one plot - only if it's open
399 if not self.cpanels[plot].IsShown():
402 self.current_plot_dest = 0
404 self.current_plot_dest = 1
405 self.cpanels[plot].Hide()
406 self.mainpanel.splitter.Unsplit(self.cpanels[plot])
407 self.mainpanel.splitter.UpdateSize()
410 def OnClosePlot(self,event):
411 self.close_plot(event.to_close)
413 def OnShowPlots(self,event):
418 #--------------------
419 def OnOpenPlayMenu(self, event):
422 def OnExitMenu(self,event):
425 def OnExportText(self,event):
428 def OnExportImage(self,event):
431 def OnAboutMenu(self,event):
436 def PlotCurve(self,event):
438 plots the current ext,ret curve.
442 #FIXME: BAD kludge following. There should be a well made plot queue mechanism, with replacements etc.
444 #If we have only one plot in the event, we already have one in self.plots and this is a secondary plot,
445 #do not erase self.plots but append the new plot to it.
446 if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) == 1:
447 self.plots.append(event.plots[0])
448 #if we already have two plots and a new secondary plot comes, we substitute the previous
449 if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) > 1:
450 self.plots[1] = event.plots[0]
452 self.plots = event.plots
454 #FIXME. Should be in PlotObject, somehow
456 for plot in self.plots:
457 if self.plots[c].styles==[]:
458 self.plots[c].styles=[None for item in plot.vectors]
460 for plot in self.plots:
462 MAIN LOOP FOR ALL PLOTS (now only 2 are allowed but...)
464 if 'destination' in dir(plot):
465 dest=plot.destination
467 #if the requested panel is not shown, show it
468 if not ( self.cpanels[dest].IsShown() ):
471 self.axes[dest].hold(False)
472 self.current_vectors=plot.vectors
473 self.current_title=plot.title
474 self.current_plot_dest=dest #let's try this way to take into account the destination plot...
477 for vectors_to_plot in self.current_vectors:
478 if len(vectors_to_plot)==2: #3d plots are to come...
479 if len(plot.styles) > 0 and plot.styles[c] == 'scatter':
480 self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1])
482 self.axes[dest].plot(vectors_to_plot[0],vectors_to_plot[1])
484 self.axes[dest].hold(True)
489 #FIXME: tackles only 2d plots
490 self.axes[dest].set_xlabel(plot.units[0])
491 self.axes[dest].set_ylabel(plot.units[1])
493 #FIXME: set smaller fonts
494 self.axes[dest].set_title(plot.title)
498 xlim=self.axes[dest].get_xlim()
499 self.axes[dest].set_xlim((xlim[1],xlim[0]))
502 ylim=self.axes[dest].get_ylim()
503 self.axes[dest].set_ylim((ylim[1],ylim[0]))
505 self.controls[dest].draw()
508 def PlotContact(self,event):
510 plots the contact point
512 self.axes[0].hold(True)
513 self.current_contact_index=event.contact_index
515 #now we fake a clicked point
516 self.clicked_points.append(ClickedPoint())
517 self.clicked_points[-1].absolute_coords=self.current_x_ret[dest][self.current_contact_index], self.current_y_ret[dest][self.current_contact_index]
518 self.clicked_points[-1].is_marker=True
521 self.clicked_points=[]
524 def ClickPoint0(self,event):
525 self.current_plot_dest=0
526 self.ClickPoint(event)
527 def ClickPoint1(self,event):
528 self.current_plot_dest=1
529 self.ClickPoint(event)
531 def ClickPoint(self,event):
533 this function decides what to do when we receive a left click on the axes.
534 We trigger other functions:
535 - the action chosen by the CLI sends an event
536 - the event raises a flag : self.click_flags_functions['foo'][0]
537 - the raised flag wants the function in self.click_flags_functions[1] to be called after a click
539 for key, value in self.click_flags_functions.items():
541 eval('self.'+value[1]+'(event)')
543 def OnMeasurePoints(self,event):
545 trigger flags to measure N points
547 self.click_flags_functions['measure_points'][0]=True
548 if 'num_of_points' in dir(event):
549 self.num_of_points=event.num_of_points
550 if 'set' in dir(event):
551 self.measure_set=event.set
553 def MeasurePoints(self,event,current_set=1):
554 dest=self.current_plot_dest
556 current_set=self.measure_set
557 except AttributeError:
560 #find the current plot matching the clicked destination
561 plot=self._plot_of_dest()
562 if len(plot.vectors)-1 < current_set: #what happens if current_set is 1 and we have only 1 vector?
563 current_set=current_set-len(plot.vectors)
565 xvector=plot.vectors[current_set][0]
566 yvector=plot.vectors[current_set][1]
568 self.clicked_points.append(ClickedPoint())
569 self.clicked_points[-1].absolute_coords=event.xdata, event.ydata
570 self.clicked_points[-1].find_graph_coords(xvector,yvector)
571 self.clicked_points[-1].is_marker=True
572 self.clicked_points[-1].is_line_edge=True
573 self.clicked_points[-1].dest=dest
577 if len(self.clicked_points)==self.num_of_points:
578 self.events_from_gui.put(self.clicked_points)
579 #restore to default state:
580 self.clicked_points=[]
581 self.click_flags_functions['measure_points'][0]=False
584 def OnGetDisplayedPlot(self,event):
585 if 'dest' in dir(event):
586 self.GetDisplayedPlot(event.dest)
588 self.GetDisplayedPlot(self.current_plot_dest)
590 def GetDisplayedPlot(self,dest):
592 returns to the CLI the currently displayed plot for the given destination
594 displayed_plot=self._plot_of_dest(dest)
595 events_from_gui.put(displayed_plot)
597 def ExportImage(self,event):
599 exports an image as a file.
600 Current supported file formats: png, eps
601 (matplotlib docs say that jpeg should be supported too, but with .jpg it doesn't work for me!)
603 #dest=self.current_plot_dest
606 self.figures[dest].savefig(filename)
608 def _find_nearest_point(self, mypoint, dataset=1):
610 Given a clicked point on the plot, finds the nearest point in the dataset (in X) that
611 corresponds to the clicked point.
613 dest=self.current_plot_dest
615 xvector=plot.vectors[dataset][0]
616 yvector=plot.vectors[dataset][1]
618 #Ye Olde sorting algorithm...
619 #FIXME: is there a better solution?
622 best_diff=10^9 #hope we never go over this magic number :(
623 for point in xvector:
624 diff=abs(point-mypoint)
630 return best_index,xvector[best_index],yvector[best_index]
633 def _plot_of_dest(self,dest=None):
635 returns the plot that has the current destination
638 dest=self.current_plot_dest
641 for aplot in self.plots:
642 if aplot.destination == dest:
648 this routine is needed for a fresh clean-and-replot of interface
649 otherwise, refreshing works very badly :(
651 thanks to Ken McIvor, wxmpl author!
653 dest=self.current_plot_dest
654 #we get current zoom limits
655 xlim=self.axes[dest].get_xlim()
656 ylim=self.axes[dest].get_ylim()
658 self.axes[dest].cla()
661 #find the current plot matching the clicked destination
662 plot=self._plot_of_dest()
663 #plot all superimposed plots
665 for plotset in plot.vectors:
666 if len(plot.styles) > 0 and plot.styles[c]=='scatter':
667 self.axes[dest].scatter(plotset[0], plotset[1])
669 self.axes[dest].plot(plotset[0], plotset[1])
671 #plot points we have clicked
672 for item in self.clicked_points:
674 if item.graph_coords==(None,None): #if we have no graph coords, we display absolute coords
675 self.axes[dest].scatter([item.absolute_coords[0]],[item.absolute_coords[1]])
677 self.axes[dest].scatter([item.graph_coords[0]],[item.graph_coords[1]])
680 print 'DEBUGGING WARNING: use of self.plot_fit is deprecated!'
681 self.axes[dest].plot(self.plot_fit[0],self.plot_fit[1])
683 self.axes[dest].hold(True)
685 self.axes[dest].set_xlim(xlim)
686 self.axes[dest].set_ylim(ylim)
687 #set title and names again...
688 self.axes[dest].set_title(self.current_title)
689 self.axes[dest].set_xlabel(plot.units[0])
690 self.axes[dest].set_ylabel(plot.units[1])
692 self.controls[dest].draw()
695 class MySplashScreen(wx.SplashScreen):
697 Create a splash screen widget.
698 That's just a fancy addition... every serious application has a splash screen!
700 def __init__(self, frame):
701 # This is a recipe to a the screen.
702 # Modify the following variables as necessary.
703 #aBitmap = wx.Image(name = "wxPyWiki.jpg").ConvertToBitmap()
704 aBitmap=wx.Image(name='hooke.jpg').ConvertToBitmap()
705 splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
706 splashDuration = 2000 # milliseconds
707 splashCallback = None
708 # Call the constructor with the above arguments in exactly the
710 wx.SplashScreen.__init__(self, aBitmap, splashStyle,
711 splashDuration, None, -1)
712 wx.EVT_CLOSE(self, self.OnExit)
716 def OnExit(self, evt):
720 # The program will freeze without this line.
721 evt.Skip() # Make sure the default handler runs too...
724 #------------------------------------------------------------------------------
728 #save the directory where Hooke is located
729 config['hookedir']=os.getcwd()
731 #now change to the working directory.
733 os.chdir(config['workdir'])
735 print "Warning: Invalid work directory."
739 def make_gui_class(*bases):
740 return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {})
742 main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__))
744 #FIXME. The frame.Show() is called by the splashscreen here! Ugly as hell.
746 mysplash=MySplashScreen(main_frame)
749 my_cmdline=CliThread(main_frame, list_of_events)