4 Hooke - A force spectroscopy review & analysis tool.
10 import multiprocessing
12 from . import config as config_mod
13 from . import plugin as plugin_mod
14 from . import driver as driver_mod
24 #import libhooke as lh
29 #import hookepropertyeditor
34 def __init__(self, config=None, debug=0):
36 config_mod.DEFAULTS.extend(plugin_mod.default_settings())
37 config_mod.DEFAULTS.extend(driver_mod.default_settings())
39 config = config_mod.HookeConfigParser(
40 paths=config_mod.DEFAULT_PATHS,
41 default_settings=config_mod.DEFAULT_SETTINGS)
47 def driver_default_settings(self):
49 for driver in driver_mod.drivers:
50 settings.extend(driver_mod.default_settings(driver))
53 def load_plugins(self):
54 for plugin,value in self.config[plugins].items():
56 def load_drivers(self)
60 if self.config.changed:
61 self.config.write() # Does not preserve original comments
63 class HookeFrame(wx.Frame):
65 def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN):
66 #call parent constructor
67 wx.Frame.__init__(self, parent, id, title, pos, size, style)
69 self.CreateApplicationIcon()
70 #self.configs contains: {the name of the Commands file: corresponding ConfigObj}
72 ##self.playlists contains: {the name of the playlist: [playlist, tabIndex, plotID]}
74 #self.plugins contains: {the name of the plugin: [caption, function]}
76 #self.plotmanipulators list contains: [the name of the plotmanip, function, name of the module]
77 self.plotmanipulators = []
79 #tell FrameManager to manage this frame
80 self._mgr = aui.AuiManager()
81 self._mgr.SetManagedWindow(self)
82 #set the gradient style
83 self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)
85 self._mgr.SetFlags(self._mgr.GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)
87 # set up default notebook style
88 self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER
89 self._notebook_theme = 0
91 #holds the perspectives: {name, [index, perspectiveStr]}
92 self._perspectives = {}
94 # min size for the frame itself isn't completely done.
95 # see the end up FrameManager::Update() for the test
96 # code. For now, just hard code a frame minimum size
97 self.SetMinSize(wx.Size(400, 300))
99 self.panelAssistant = self.CreatePanelAssistant()
100 self.panelCommands = self.CreatePanelCommands()
101 self.panelFolders = self.CreatePanelFolders()
102 self.panelPlaylists = self.CreatePanelPlaylists()
103 self.panelProperties = self.CreatePanelProperties()
104 self.panelOutput = self.CreatePanelOutput()
105 self.panelResults = self.CreatePanelResults()
106 self.plotNotebook = self.CreateNotebook()
107 #self.textCtrlCommandLine=self.CreateCommandLine()
110 self._mgr.AddPane(self.panelFolders, aui.AuiPaneInfo().Name('Folders').Caption('Folders').Left().CloseButton(True).MaximizeButton(False))
111 self._mgr.AddPane(self.panelPlaylists, aui.AuiPaneInfo().Name('Playlists').Caption('Playlists').Left().CloseButton(True).MaximizeButton(False))
112 self._mgr.AddPane(self.plotNotebook, aui.AuiPaneInfo().Name('Plots').CenterPane().PaneBorder(False))
113 self._mgr.AddPane(self.panelCommands, aui.AuiPaneInfo().Name('Commands').Caption('Settings and commands').Right().CloseButton(True).MaximizeButton(False))
114 self._mgr.AddPane(self.panelProperties, aui.AuiPaneInfo().Name('Properties').Caption('Properties').Right().CloseButton(True).MaximizeButton(False))
115 self._mgr.AddPane(self.panelAssistant, aui.AuiPaneInfo().Name('Assistant').Caption('Assistant').Right().CloseButton(True).MaximizeButton(False))
116 self._mgr.AddPane(self.panelOutput, aui.AuiPaneInfo().Name('Output').Caption('Output').Bottom().CloseButton(True).MaximizeButton(False))
117 self._mgr.AddPane(self.panelResults, aui.AuiPaneInfo().Name('Results').Caption('Results').Bottom().CloseButton(True).MaximizeButton(False))
118 #self._mgr.AddPane(self.textCtrlCommandLine, aui.AuiPaneInfo().Name('CommandLine').CaptionVisible(False).Fixed().Bottom().Layer(2).CloseButton(False).MaximizeButton(False))
119 #self._mgr.AddPane(panelBottom, aui.AuiPaneInfo().Name("panelCommandLine").Bottom().Position(1).CloseButton(False).MaximizeButton(False))
121 # add the toolbars to the manager
122 self.toolbar=self.CreateToolBar()
123 self.toolbarNavigation=self.CreateToolBarNavigation()
124 self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Name('toolbar').Caption('Toolbar').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
125 self._mgr.AddPane(self.toolbarNavigation, aui.AuiPaneInfo().Name('toolbarNavigation').Caption('Navigation').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
126 # "commit" all changes made to FrameManager
128 #create the menubar after the panes so that the default perspective
129 #is created with all panes open
131 self.statusbar = self.CreateStatusBar()
133 #TODO: select item on startup (whatever item)
134 #self.listCtrlCommands.Select(0)
135 #self.OnListboxSelect(None)
136 name = self.config['perspectives']['active']
137 menu_item = self.GetPerspectiveMenuItem(name)
138 self.OnRestorePerspective(menu_item)
139 self.playlists = self.panelPlaylists.Playlists
140 #define the list of active drivers
142 for driver in self.config['drivers']:
143 if self.config['drivers'][driver]:
144 #get the corresponding filename and path
145 filename = ''.join([driver, '.py'])
146 path = lh.get_file_path(filename, ['drivers'])
147 #the driver is active for driver[1] == 1
148 if os.path.isfile(path):
149 #driver files are located in the 'drivers' subfolder
150 driver_name = ''.join(['drivers.', driver])
151 module = __import__(driver_name)
152 class_file = getattr(drivers, driver)
153 for command in dir(class_file):
154 if command.endswith('Driver'):
155 self.drivers.append(getattr(class_file, command))
156 #import all active plugins and plotmanips
157 #the plotmanip_functions contains: {the name of the plotmanip: [method, class_object]}
158 plotmanip_functions = {}
159 #add 'general.ini' to self.configs (this is not a plugin and thus must be imported seperately)
160 ini_path = lh.get_file_path('general.ini', ['plugins'])
161 plugin_config = ConfigObj(ini_path)
162 #self.config.merge(plugin_config)
163 self.configs['general'] = plugin_config
164 #make sure we execute _plug_init() for every command line plugin we import
165 for plugin in self.config['plugins']:
166 if self.config['plugins'][plugin]:
167 filename = ''.join([plugin, '.py'])
168 path = lh.get_file_path(filename, ['plugins'])
169 if os.path.isfile(path):
170 #get the corresponding filename and path
171 plugin_name = ''.join(['plugins.', plugin])
174 module = __import__(plugin_name)
175 #prepare the ini file for inclusion
176 ini_path = path.replace('.py', '.ini')
178 plugin_config = ConfigObj(ini_path)
179 #self.config.merge(plugin_config)
180 self.configs[plugin] = plugin_config
182 commands = eval('dir(module.' + plugin+ '.' + plugin + 'Commands)')
183 #keep only commands (ie names that start with 'do_')
184 commands = [command for command in commands if command.startswith('do_')]
186 self.plugins[plugin] = commands
188 #initialize the plugin
189 eval('module.' + plugin+ '.' + plugin + 'Commands._plug_init(self)')
190 except AttributeError:
194 #initialize the commands tree
195 commands = dir(HookeFrame)
196 commands = [command for command in commands if command.startswith('do_')]
198 self.plugins['general'] = commands
199 self.panelCommands.Initialize(self.plugins)
200 for command in dir(self):
201 if command.startswith('plotmanip_'):
202 plotmanip_functions[command] = [command, getattr(self, command)]
203 for name in self.config['plotmanipulators']['names']:
204 if self.config['plotmanipulators'].as_bool(name):
205 command_name = ''.join(['plotmanip_', name])
206 if command_name in plotmanip_functions:
207 self.plotmanipulators.append(plotmanip_functions[command_name])
208 #load default list, if possible
209 self.do_loadlist(self.config['general']['list'])
211 def _BindEvents(self):
212 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
213 self.Bind(wx.EVT_SIZE, self.OnSize)
214 self.Bind(wx.EVT_CLOSE, self.OnClose)
215 # Show How To Use The Closing Panes Event
216 self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
217 self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnNotebookPageClose)
219 self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)
220 self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
222 self.Bind(wx.EVT_MENU_RANGE, self.OnView, id=ID_ViewAssistant, id2=ID_ViewResults)
224 self.Bind(wx.EVT_MENU, self.OnDeletePerspective, id=ID_DeletePerspective)
225 self.Bind(wx.EVT_MENU, self.OnSavePerspective, id=ID_SavePerspective)
226 self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, id2=ID_FirstPerspective+1000)
228 self.Bind(wx.EVT_TOOL, self.OnExportImage, id=ID_ExportImage)
229 self.Bind(wx.EVT_TOOL, self.OnNext, id=ID_Next)
230 self.Bind(wx.EVT_TOOL, self.OnPrevious, id=ID_Previous)
231 #self.Bind(.EVT_AUITOOLBAR_TOOL_DROPDOWN, self.OnDropDownToolbarItem, id=ID_DropDownToolbarItem)
233 treeCtrl = self.panelFolders.GetTreeCtrl()
234 #tree.Bind(wx.EVT_LEFT_UP, self.OnDirCtrl1LeftUp)
235 #tree.Bind(wx.EVT_LEFT_DOWN, self.OnGenericDirCtrl1LeftDown)
236 treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self.OnDirCtrlLeftDclick)
238 self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DOWN, self.OnPlaylistsLeftDown)
239 self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DCLICK, self.OnPlaylistsLeftDclick)
241 self.panelCommands.ExecuteButton.Bind(wx.EVT_BUTTON, self.OnExecute)
242 self.panelCommands.CommandsTree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeCtrlCommandsLeftDown)
244 self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)
245 self.panelProperties.pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)
247 self.panelResults.results_list.OnCheckItem = self.OnResultsCheck
249 def _GetActiveCurveIndex(self):
250 playlist = self.GetActivePlaylist()
251 #get the selected item from the tree
252 selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
253 #test if a playlist or a curve was double-clicked
254 if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
258 selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
259 while selected_item.IsOk():
261 selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
264 def _GetActivePlaylistName(self):
265 #get the selected item from the tree
266 selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
267 #test if a playlist or a curve was double-clicked
268 if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
269 playlist_item = selected_item
271 #get the name of the playlist
272 playlist_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
273 #now we have a playlist
274 return self.panelPlaylists.PlaylistsTree.GetItemText(playlist_item)
276 def _GetPlaylistTab(self, name):
277 for index, page in enumerate(self.plotNotebook._tabs._pages):
278 if page.caption == name:
282 def _GetUniquePlaylistName(self, name):
285 while playlist_name in self.playlists:
286 playlist_name = ''.join([name, str(count)])
290 def _SavePerspectiveToFile(self, name, perspective):
291 filename = ''.join([name, '.txt'])
292 filename = lh.get_file_path(filename, ['perspectives'])
293 perspectivesFile = open(filename, 'w')
294 perspectivesFile.write(perspective)
295 perspectivesFile.close()
297 def AddPlaylist(self, playlist=None, name='Untitled'):
298 #TODO: change cursor or progressbar (maybe in statusbar)
299 #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
300 if playlist and playlist.count > 0:
301 playlist.name = self._GetUniquePlaylistName(name)
303 self.AddToPlaylists(playlist)
305 def AddPlaylistFromFiles(self, files=[], name='Untitled'):
306 #TODO: change cursor or progressbar (maybe in statusbar)
307 #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
309 playlist = Playlist.Playlist(self.drivers)
311 playlist.add_curve(item)
312 if playlist.count > 0:
313 playlist.name = self._GetUniquePlaylistName(name)
315 self.AddToPlaylists(playlist)
317 def AddToPlaylists(self, playlist):
318 if playlist.has_curves:
319 #setup the playlist in the Playlist tree
320 tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
321 playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
322 #add all curves to the Playlist tree
324 for index, curve in enumerate(playlist.curves):
325 ##remove the extension from the name of the curve
327 #item_text, extension = os.path.splitext(curve.name)
328 #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
329 curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
330 if index == playlist.index:
331 self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
333 #create the plot tab and add playlist to the dictionary
334 plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
335 notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
336 tab_index = self.plotNotebook.GetSelection()
337 figure = plotPanel.get_figure()
338 self.playlists[playlist.name] = [playlist, figure]
339 self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
340 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
343 def AppendToOutput(self, text):
344 self.panelOutput.AppendText(''.join([text, '\n']))
346 def CreateApplicationIcon(self):
347 iconFile = 'resources' + os.sep + 'microscope.ico'
348 icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
351 def CreateCommandLine(self):
352 return wx.TextCtrl(self, -1, '', style=wx.NO_BORDER|wx.EXPAND)
354 def CreatePanelAssistant(self):
355 panel = wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
356 panel.SetEditable(False)
359 def CreatePanelCommands(self):
360 return hookecommands.Commands(self)
362 def CreatePanelFolders(self):
364 filters = self.config['folders']['filters']
365 index = self.config['folders'].as_int('filterindex')
366 #set initial directory
367 folder = self.config['general']['workdir']
368 return wx.GenericDirCtrl(self, -1, dir=folder, size=(200, 250), style=wx.DIRCTRL_SHOW_FILTERS, filter=filters, defaultFilter=index)
370 def CreatePanelOutput(self):
371 return wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
373 def CreatePanelPlaylists(self):
374 return hookeplaylist.Playlists(self)
376 def CreatePanelProperties(self):
377 return hookepropertyeditor.PropertyEditor(self)
379 def CreatePanelResults(self):
380 return hookeresults.Results(self)
382 def CreatePanelWelcome(self):
383 ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))
384 introStr = '<h1>Welcome to Hooke</h1>' + \
385 '<h3>Features</h3>' + \
387 '<li>View, annotate, measure force curves</li>' + \
388 '<li>Worm-like chain fit of force peaks</li>' + \
389 '<li>Automatic convolution-based filtering of empty curves</li>' + \
390 '<li>Automatic fit and measurement of multiple force peaks</li>' + \
391 '<li>Handles force-clamp force experiments (experimental)</li>' + \
392 '<li>It is extensible by users by means of plugins and drivers</li>' + \
394 '<p>See the <a href="/p/hooke/wiki/DocumentationIndex">DocumentationIndex</a> for more information</p>'
395 ctrl.SetPage(introStr)
398 def CreateMenuBar(self):
399 menu_bar = wx.MenuBar()
401 file_menu = wx.Menu()
402 file_menu.Append(wx.ID_OPEN, '&Open playlist\tCtrl-O')
403 file_menu.Append(wx.ID_SAVE, 'Save playlist\tCtrl-S')
404 file_menu.AppendSeparator()
405 file_menu.Append(wx.ID_EXIT, 'Exit\tCtrl-Q')
407 edit_menu = wx.Menu()
408 edit_menu.Append(ID_ExportText, 'Export text...')
409 edit_menu.Append(ID_ExportImage, 'Export image...')
410 edit_menu.AppendSeparator();
411 edit_menu.Append(ID_Config, 'Preferences')
413 view_menu = wx.Menu()
414 view_menu.AppendCheckItem(ID_ViewFolders, 'Folders\tF5')
415 view_menu.AppendCheckItem(ID_ViewPlaylists, 'Playlists\tF6')
416 view_menu.AppendCheckItem(ID_ViewCommands, 'Commands\tF7')
417 view_menu.AppendCheckItem(ID_ViewProperties, 'Properties\tF8')
418 view_menu.AppendCheckItem(ID_ViewAssistant, 'Assistant\tF9')
419 view_menu.AppendCheckItem(ID_ViewResults, 'Results\tF10')
420 view_menu.AppendCheckItem(ID_ViewOutput, 'Output\tF11')
422 self._perspectives_menu = self.CreatePerspectivesMenu()
424 help_menu = wx.Menu()
425 help_menu.Append(wx.ID_ABOUT, 'About Hooke')
427 menu_bar.Append(file_menu, 'File')
428 menu_bar.Append(edit_menu, 'Edit')
429 menu_bar.Append(view_menu, 'View')
430 menu_bar.Append(self._perspectives_menu, "Perspectives")
431 menu_bar.Append(help_menu, 'Help')
433 self.SetMenuBar(menu_bar)
435 def CreateNotebook(self):
436 # create the notebook off-window to avoid flicker
437 client_size = self.GetClientSize()
438 ctrl = aui.AuiNotebook(self, -1, wx.Point(client_size.x, client_size.y), wx.Size(430, 200), self._notebook_style)
439 arts = [aui.AuiDefaultTabArt, aui.AuiSimpleTabArt, aui.VC71TabArt, aui.FF2TabArt, aui.VC8TabArt, aui.ChromeTabArt]
440 art = arts[self._notebook_theme]()
441 ctrl.SetArtProvider(art)
442 #uncomment if we find a nice icon
443 #page_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
444 ctrl.AddPage(self.CreatePanelWelcome(), "Welcome", False)
447 def CreatePerspectivesMenu(self):
449 menu.Append(ID_SavePerspective, "Save Perspective")
450 menu.Append(ID_DeletePerspective, "Delete Perspective")
451 menu.AppendSeparator()
452 #add perspectives to menubar and _perspectives
453 perspectivesDirectory = os.path.join(lh.hookeDir, 'perspectives')
454 if os.path.isdir(perspectivesDirectory):
455 perspectiveFileNames = os.listdir(perspectivesDirectory)
456 for perspectiveFilename in perspectiveFileNames:
457 filename = lh.get_file_path(perspectiveFilename, ['perspectives'])
458 if os.path.isfile(filename):
459 perspectiveFile = open(filename, 'rU')
460 perspective = perspectiveFile.readline()
461 perspectiveFile.close()
462 if perspective != '':
463 name, extension = os.path.splitext(perspectiveFilename)
464 if extension == '.txt':
465 menuItem = menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
466 self._perspectives[name] = [len(self._perspectives), perspective]
467 if self.config['perspectives']['active'] == name:
469 #in case there are no perspectives
470 if not self._perspectives:
471 perspective = self._mgr.SavePerspective()
472 self.config['perspectives']['default'] = 'Default'
473 self._perspectives['Default'] = [0, perspective]
474 menuItem = menu.AppendRadioItem(ID_FirstPerspective, 'Default')
476 self._SavePerspectiveToFile('Default', perspective)
479 def CreateStatusbar(self):
480 statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
481 statusbar.SetStatusWidths([-2, -3])
482 statusbar.SetStatusText('Ready', 0)
483 welcomeString=u'Welcome to Hooke (version '+__version__+', '+__release_name__+')!'
484 statusbar.SetStatusText(welcomeString, 1)
487 def CreateToolBar(self):
488 toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
489 toolbar.SetToolBitmapSize(wx.Size(16,16))
490 toolbar_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))
491 toolbar_bmpOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 16))
492 toolbar_bmpSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 16))
493 toolbar_bmpExportText = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
494 toolbar_bmpExportImage = wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_OTHER, wx.Size(16, 16))
495 toolbar.AddLabelTool(101, 'Open', toolbar_bmpOpen)
496 toolbar.AddLabelTool(102, 'Save', toolbar_bmpSave)
497 toolbar.AddSeparator()
498 toolbar.AddLabelTool(ID_ExportText, 'Export text...', toolbar_bmpExportText)
499 toolbar.AddLabelTool(ID_ExportImage, 'Export image...', toolbar_bmpExportImage)
503 def CreateToolBarNavigation(self):
504 toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
505 toolbar.SetToolBitmapSize(wx.Size(16,16))
506 toolbar_bmpBack = wx.ArtProvider_GetBitmap(wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16))
507 toolbar_bmpForward = wx.ArtProvider_GetBitmap(wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16))
508 toolbar.AddLabelTool(ID_Previous, 'Previous', toolbar_bmpBack, shortHelp='Previous curve')
509 toolbar.AddLabelTool(ID_Next, 'Next', toolbar_bmpForward, shortHelp='Next curve')
513 def DeleteFromPlaylists(self, name):
514 if name in self.playlists:
515 del self.playlists[name]
516 tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
517 item, cookie = self.panelPlaylists.PlaylistsTree.GetFirstChild(tree_root)
519 playlist_name = self.panelPlaylists.PlaylistsTree.GetItemText(item)
520 if playlist_name == name:
522 self.panelPlaylists.PlaylistsTree.Delete(item)
525 item = self.panelPlaylists.PlaylistsTree.GetNextSibling(item)
526 self.OnPlaylistsLeftDclick(None)
528 def DeletePlotPage(self, name):
529 index = self._GetPlaylistTab(name)
530 plot = self.playlists[name][1]
532 self.plotNotebook.RemovePage(index)
533 self.DeleteFromPlaylists(name)
535 def GetActiveCurve(self):
536 playlist = self.GetActivePlaylist()
537 if playlist is not None:
538 return playlist.get_active_curve()
541 def GetActivePlaylist(self):
542 playlist_name = self._GetActivePlaylistName()
543 if playlist_name in self.playlists:
544 return self.playlists[playlist_name][0]
547 def GetActivePlot(self):
548 curve = self.GetActiveCurve()
549 if curve is not None:
550 return curve.plots[0]
553 def GetDockArt(self):
554 return self._mgr.GetArtProvider()
556 def GetBoolFromConfig(self, *args):
565 if self.configs.has_key(plugin):
566 config = self.configs[plugin]
567 return config[section][key].as_bool('value')
570 def GetFloatFromConfig(self, *args):
579 if self.configs.has_key(plugin):
580 config = self.configs[plugin]
581 return config[section][key].as_float('value')
584 def GetIntFromConfig(self, *args):
593 if self.configs.has_key(plugin):
594 config = self.configs[plugin]
595 return config[section][key].as_int('value')
598 def GetStringFromConfig(self, *args):
607 if self.configs.has_key(plugin):
608 config = self.configs[plugin]
609 return config[section][key]['value']
612 def GetPerspectiveMenuItem(self, name):
613 index = self._perspectives[name][0]
614 perspective_Id = ID_FirstPerspective + index
615 menu_item = self.MenuBar.FindItemById(perspective_Id)
618 def HasPlotmanipulator(self, name):
620 returns True if the plotmanipulator 'name' is loaded, False otherwise
622 for plotmanipulator in self.plotmanipulators:
623 if plotmanipulator[0] == name:
627 def OnAbout(self, event):
629 'A free, open source data analysis platform\n'+\
630 '(c) 2006-2008 Massimo Sandal\n\n'+\
631 '(c) 2009 Dr. Rolf Schmidt\n\n'+\
632 'Released under the GNU GPL v2'
633 dialog = wx.MessageDialog(self, msg, "About Hooke", wx.OK | wx.ICON_INFORMATION)
637 def OnClose(self, event):
639 self.config['main']['height'] = str(self.GetSize().GetHeight())
640 self.config['main']['left'] = str(self.GetPosition()[0])
641 self.config['main']['top'] = str(self.GetPosition()[1])
642 self.config['main']['width'] = str(self.GetSize().GetWidth())
643 # Writing the configuration file to 'hooke.ini'
649 def OnDeletePerspective(self, event):
652 def OnDirCtrlLeftDclick(self, event):
653 file_path = self.panelFolders.GetPath()
654 if os.path.isfile(file_path):
655 if file_path.endswith('.hkp'):
656 self.do_loadlist(file_path)
661 def OnEraseBackground(self, event):
664 def OnExecute(self, event):
665 item = self.panelCommands.CommandsTree.GetSelection()
667 if self.panelCommands.CommandsTree.ItemHasChildren(item):
671 parent = self.panelCommands.CommandsTree.GetItemParent(item)
672 if not self.panelCommands.CommandsTree.ItemHasChildren(item):
673 parent_text = self.panelCommands.CommandsTree.GetItemText(parent)
674 item_text = self.panelCommands.CommandsTree.GetItemText(item)
675 if item_text in ['genlist', 'loadlist', 'savelist']:
676 property_values = self.panelProperties.GetPropertyValues()
678 for item in property_values:
679 arg_str = ''.join([arg_str, item, '=r"', str(property_values[item]), '", '])
680 command = ''.join(['self.do_', item_text, '(', arg_str, ')'])
682 command = ''.join(['self.do_', item_text, '()'])
686 def OnExit(self, event):
689 def OnExportImage(self, event):
692 def OnNext(self, event):
695 Go to the next curve in the playlist.
696 If we are at the last curve, we come back to the first.
700 selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
701 if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
702 #GetFirstChild returns a tuple
703 #we only need the first element
704 next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(selected_item)[0]
706 next_item = self.panelPlaylists.PlaylistsTree.GetNextSibling(selected_item)
707 if not next_item.IsOk():
708 parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
709 #GetFirstChild returns a tuple
710 #we only need the first element
711 next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(parent_item)[0]
712 self.panelPlaylists.PlaylistsTree.SelectItem(next_item, True)
713 playlist = self.playlists[self._GetActivePlaylistName()][0]
714 if playlist.count > 1:
716 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
719 def OnNotebookPageClose(self, event):
720 ctrl = event.GetEventObject()
721 playlist_name = ctrl.GetPageText(ctrl._curpage)
722 self.DeleteFromPlaylists(playlist_name)
724 def OnPaneClose(self, event):
727 def OnPlaylistsLeftDclick(self, event):
728 playlist_name = self._GetActivePlaylistName()
729 #if that playlist already exists
730 #we check if it is the active playlist (ie selected in panelPlaylists)
731 #and switch to it if necessary
732 if playlist_name in self.playlists:
733 index = self.plotNotebook.GetSelection()
734 current_playlist = self.plotNotebook.GetPageText(index)
735 #new_playlist = self.playlists[playlist_name][0]
736 #if current_playlist != new_playlist:
737 if current_playlist != playlist_name:
738 index = self._GetPlaylistTab(playlist_name)
739 self.plotNotebook.SetSelection(index)
740 #if a curve was double-clicked
741 item = self.panelPlaylists.PlaylistsTree.GetSelection()
742 #TODO: fix with get_active_curve
743 if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
744 index = self._GetActiveCurveIndex()
748 playlist = self.playlists[playlist_name][0]
749 playlist.index = index
750 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
752 #if you uncomment the following line, the tree will collapse/expand as well
755 def OnPlaylistsLeftDown(self, event):
756 hit_item, hit_flags = self.panelPlaylists.PlaylistsTree.HitTest(event.GetPosition())
757 if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
759 self.panelPlaylists.PlaylistsTree.SelectItem(hit_item)
760 playlist_name = self._GetActivePlaylistName()
761 playlist = self.playlists[playlist_name][0]
762 #if a curve was clicked
763 item = self.panelPlaylists.PlaylistsTree.GetSelection()
764 if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
765 #TODO: fix with get_active_curve
766 index = self._GetActiveCurveIndex()
768 #playlist = self.playlists[playlist_name][0]
769 playlist.index = index
770 #self.playlists[playlist_name][0].index = index
772 ##self.playlists[playlist_name][0].index = 0
773 #playlist.index = index
774 self.playlists[playlist_name][0] = playlist
777 def OnPrevious(self, event):
780 Go to the previous curve in the playlist.
781 If we are at the first curve, we jump to the last.
785 #playlist = self.playlists[self._GetActivePlaylistName()][0]
786 #select the previous curve and tell the user if we wrapped around
787 #self.AppendToOutput(playlist.previous())
788 selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
789 if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
790 previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(selected_item)
792 previous_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
793 if not previous_item.IsOk():
794 parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
795 previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(parent_item)
796 self.panelPlaylists.PlaylistsTree.SelectItem(previous_item, True)
797 playlist = self.playlists[self._GetActivePlaylistName()][0]
798 if playlist.count > 1:
800 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
803 def OnPropGridChanged (self, event):
804 prop = event.GetProperty()
806 item_section = self.panelProperties.SelectedTreeItem
807 item_plugin = self.panelCommands.CommandsTree.GetItemParent(item_section)
808 plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
809 config = self.configs[plugin]
810 property_section = self.panelCommands.CommandsTree.GetItemText(item_section)
811 property_key = prop.GetName()
812 property_value = prop.GetValue()
813 config[property_section][property_key]['value'] = property_value
815 def OnPropGridSelect(self, event):
818 def OnRestorePerspective(self, event):
819 name = self.MenuBar.FindItemById(event.GetId()).GetLabel()
820 self._mgr.LoadPerspective(self._perspectives[name][1])
821 self.config['perspectives']['active'] = name
823 all_panes = self._mgr.GetAllPanes()
824 for pane in all_panes:
825 if not pane.name.startswith('toolbar'):
826 if pane.name == 'Assistant':
827 self.MenuBar.FindItemById(ID_ViewAssistant).Check(pane.window.IsShown())
828 if pane.name == 'Folders':
829 self.MenuBar.FindItemById(ID_ViewFolders).Check(pane.window.IsShown())
830 if pane.name == 'Playlists':
831 self.MenuBar.FindItemById(ID_ViewPlaylists).Check(pane.window.IsShown())
832 if pane.name == 'Commands':
833 self.MenuBar.FindItemById(ID_ViewCommands).Check(pane.window.IsShown())
834 if pane.name == 'Properties':
835 self.MenuBar.FindItemById(ID_ViewProperties).Check(pane.window.IsShown())
836 if pane.name == 'Output':
837 self.MenuBar.FindItemById(ID_ViewOutput).Check(pane.window.IsShown())
838 if pane.name == 'Results':
839 self.MenuBar.FindItemById(ID_ViewResults).Check(pane.window.IsShown())
841 def OnResultsCheck(self, index, flag):
842 curve = self.GetActiveCurve()
843 result = curve.data['results'][index]['visible'] = flag
846 def OnSavePerspective(self, event):
847 def nameExists(name):
848 for item in self._perspectives_menu.GetMenuItems():
849 if item.GetText() == name:
855 dialog = wx.TextEntryDialog(self, 'Enter a name for the new perspective:', 'Save perspective')
856 dialog.SetValue('New perspective')
857 if dialog.ShowModal() != wx.ID_OK:
860 name = dialog.GetValue()
863 dialogConfirm = wx.MessageDialog(self, 'A file with this name already exists.\n\nDo you want to replace it?', 'Confirm', wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)
864 if dialogConfirm.ShowModal() == wx.ID_YES:
869 perspective = self._mgr.SavePerspective()
872 #check the corresponding menu item
873 menuItem = self.GetPerspectiveMenuItem(name)
874 #replace the perspectiveStr in _pespectives
875 index = self._perspectives[name][0]
876 self._perspectives[name] = [index, perspective]
878 #simply add the new perspective to _perspectives
879 index = len(self._perspectives)
880 self._perspectives[name] = [len(self._perspectives), perspective]
881 menuItem = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
884 self._SavePerspectiveToFile(name, perspective)
885 #uncheck all perspective menu items
886 #as these are radio items, one item has to be checked at all times
887 #the line 'menuItem.Check()' above actually checks a second item
889 #so we need to uncheck all other items afterwards
890 #weirdly enough, menuitem.Toggle() doesn't do this properly either
891 for item in self._perspectives_menu.GetMenuItems():
892 if item.IsCheckable():
893 if item.GetLabel() != name:
896 def OnView(self, event):
897 menu_id = event.GetId()
898 menu_item = self.MenuBar.FindItemById(menu_id)
899 menu_label = menu_item.GetLabel()
901 pane = self._mgr.GetPane(menu_label)
902 pane.Show(not pane.IsShown())
903 #if we don't do the following, the Folders pane does not resize properly on hide/show
904 if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():
905 #folders_size = pane.GetSize()
906 self.panelFolders.Fit()
909 def OnSize(self, event):
912 def OnTreeCtrlCommandsLeftDown(self, event):
913 hit_item, hit_flags = self.panelCommands.CommandsTree.HitTest(event.GetPosition())
914 if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
915 self.panelCommands.CommandsTree.SelectItem(hit_item)
916 self.panelProperties.SelectedTreeItem = hit_item
917 #if a command was clicked
919 if not self.panelCommands.CommandsTree.ItemHasChildren(hit_item):
920 item_plugin = self.panelCommands.CommandsTree.GetItemParent(hit_item)
921 plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
922 if self.configs.has_key(plugin):
923 #config = self.panelCommands.CommandsTree.GetPyData(item_plugin)
924 config = self.configs[plugin]
925 section = self.panelCommands.CommandsTree.GetItemText(hit_item)
926 #display docstring in help window
927 doc_string = eval('self.do_' + section + '.__doc__')
928 if section in config:
929 for option in config[section]:
930 properties.append([option, config[section][option]])
932 module = self.panelCommands.CommandsTree.GetItemText(hit_item)
933 if module != 'general':
934 doc_string = eval('plugins.' + module + '.' + module + 'Commands.__doc__')
936 doc_string = 'The module "general" contains Hooke core functionality'
937 if doc_string is not None:
938 self.panelAssistant.ChangeValue(doc_string)
939 hookepropertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)
942 def UpdatePlaylists(self):
943 #setup the playlist in the Playlist tree
944 tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
945 playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
946 #add all curves to the Playlist tree
948 for index, curve in enumerate(playlist.curves):
949 ##remove the extension from the name of the curve
951 #item_text, extension = os.path.splitext(curve.name)
952 #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
953 curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
954 if index == playlist.index:
955 self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
956 #create the plot tab and add playlist to the dictionary
957 plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
958 notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
959 #tab_index = self.plotNotebook.GetSelection()
960 figure = plotPanel.get_figure()
961 #self.playlists[playlist.name] = [playlist, tab_index, figure]
962 self.playlists[playlist.name] = [playlist, figure]
963 self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
964 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
968 #Everything sending an event should be here
969 def _measure_N_points(self, N, whatset=1):
971 general helper function for N-points measures
973 wx.PostEvent(self.frame,self.list_of_events['measure_points'](num_of_points=N, set=whatset))
976 points=self.frame.events_from_gui.get()
982 def _clickize(self, xvector, yvector, index):
984 returns a ClickedPoint() object from an index and vectors of x, y coordinates
986 point = lh.ClickedPoint()
988 point.absolute_coords = xvector[index], yvector[index]
989 point.find_graph_coords(xvector, yvector)
992 #PLAYLIST INTERACTION COMMANDS
993 #-------------------------------
994 def do_genlist(self, folder=lh.hookeDir, filemask='*.*'):
997 Generates a file playlist.
998 Note it doesn't *save* it: see savelist for this.
1000 If [input files] is a directory, it will use all files in the directory for playlist.
1006 are all equivalent syntax.
1008 Syntax: genlist [input files]
1010 #args list is: input folder, file mask
1011 if os.path.isdir(folder):
1012 path = os.path.join(folder, filemask)
1013 #expanding correctly the input list with the glob module :)
1014 files = glob.glob(path)
1016 #TODO: change cursor or progressbar (maybe in statusbar)
1017 #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1018 playlist = playlist.Playlist(self.drivers)
1020 curve = playlist.add_curve(item)
1021 plot = copy.deepcopy(curve.plots[0])
1023 curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1024 curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1025 #apply all active plotmanipulators and add the 'manipulated' data
1026 for plotmanipulator in self.plotmanipulators:
1027 plot = plotmanipulator[1](plot, curve)
1028 curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1029 curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1030 if playlist.count > 0:
1031 playlist.name = self._GetUniquePlaylistName(os.path.basename(folder))
1033 self.AddToPlaylists(playlist)
1034 self.AppendToOutput(playlist.get_status_string())
1036 self.AppendToOutput(''.join(['Cannot find folder ', folder]))
1038 def do_loadlist(self, filename):
1041 Loads a file playlist
1043 Syntax: loadlist [playlist file]
1045 #TODO: check for duplicate playlists, ask the user for a unique name
1046 #if self.playlist_name in self.playlists:
1048 #add hkp extension if necessary
1049 if not filename.endswith('.hkp'):
1050 filename = ''.join([filename, '.hkp'])
1051 #prefix with 'hookeDir' if just a filename or a relative path
1052 filename = lh.get_file_path(filename)
1053 if os.path.isfile(filename):
1054 #TODO: change cursor
1055 #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1056 playlist_new = playlist.Playlist(self.drivers)
1057 playlist_new.load(filename)
1058 if playlist_new.count > 0:
1059 for curve in playlist_new.curves:
1060 plot = copy.deepcopy(curve.plots[0])
1061 for plotmanip in self.plotmanipulators:
1062 #to_plot = plotmanip[1](to_plot, curve)
1063 plot = plotmanip[1](plot, curve)
1064 curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1065 curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1066 self.AddToPlaylists(playlist_new)
1068 ##TODO: display dialog
1069 self.AppendToOutput(playlist_new.get_status_string())
1070 #TODO: change cursor
1071 #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1073 #TODO: display dialog
1074 self.AppendToOutput(''.join['File ', filename, ' not found.\n'])
1077 def do_savelist(self, filename):
1080 Saves the current file playlist on disk.
1082 Syntax: savelist [filename]
1085 #self.playlist_generics['pointer'] = self._GetActiveCurveIndex
1086 pointer = self._GetActiveCurveIndex()
1087 #autocomplete filename if not specified
1088 if not filename.endswith('.hkp'):
1089 filename = filename.join(['.hkp'])
1091 playlist = self.GetActivePlaylist()
1093 playlist.save(filename)
1095 #PLOT INTERACTION COMMANDS
1096 #-------------------------------
1097 def UpdatePlot(self):
1099 if plot['visible'] and plot['x'] and plot['y']:
1100 color = plot['color']
1101 style = plot['style']
1103 axes.plot(plot['x'], plot['y'], color=color, zorder=1)
1104 if style == 'scatter':
1105 axes.scatter(plot['x'], plot['y'], color=color, s=0.5, zorder=2)
1107 def add_plot2(plot):
1108 if plot.visible and plot.x and plot.y:
1109 if plot.style == 'plot':
1110 axes.plot(plot.x, plot.y, color=plot.color, zorder=1)
1111 if plot.style == 'scatter':
1112 axes.scatter(plot.x, plot.y, color=plot.color, s=0.5, zorder=2)
1114 playlist_name = self._GetActivePlaylistName()
1115 index = self._GetActiveCurveIndex()
1116 playlist = self.playlists[playlist_name][0]
1117 curve = playlist.get_active_curve()
1118 plot = playlist.get_active_plot()
1119 figure = self.playlists[playlist_name][1]
1123 if curve.data.has_key('manipulated'):
1125 elif curve.data.has_key('raw'):
1126 exclude = 'manipulated'
1128 if exclude is not None:
1129 #TODO: what is this good for?
1130 if not hasattr(self, 'subplot'):
1131 axes = figure.add_subplot(111)
1133 axes.set_title(plot.title)
1134 axes.set_xlabel(plot.units[0])
1135 axes.set_ylabel(plot.units[1])
1137 for set_of_plots in curve.data:
1138 if set_of_plots != exclude:
1139 plots = curve.data[set_of_plots]
1140 for each_plot in plots:
1143 #TODO: add multiple results support
1144 #for fit in curve.fits:
1145 if curve.fits.has_key('wlc'):
1146 for plot in curve.fits['wlc'].results:
1148 self.panelResults.DisplayResults(curve.fits['wlc'])
1150 self.panelResults.ClearResults()
1152 axes.figure.canvas.draw()
1154 self.AppendToOutput('Not able to plot.')
1157 if __name__ == '__main__':
1158 app = Hooke(debug=__debug__)