The code.ill.fr has been recreated and upgraded with the latest version this weekend, If you encounter any problem please inform the Helpdesk.

MainFrame.py 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

''' 
Created on Apr 14, 2015

:author: Bachir Aoun, Gael Goret and Eric C. Pellegrini
'''

import collections
import os
import sys
import webbrowser

38

39
40
import wx
import wx.aui as aui
eric pellegrini's avatar
test    
eric pellegrini committed
41
 
42
from MDANSE import LOGGER, PLATFORM, REGISTRY
eric pellegrini's avatar
eric pellegrini committed
43
from MDANSE.__pkginfo__ import __author__, __commit__, __version__, __beta__
44
from MDANSE.Framework.Jobs.Converter import Converter
45
from MDANSE.GUI.ControllerPanel import ControllerPanel
46
from MDANSE.GUI.DataController import DATA_CONTROLLER
47
48
49
50
51
52
53
54
55
from MDANSE.GUI.DataTreePanel import DataTreePanel
from MDANSE.GUI.Icons import ICONS
from MDANSE.GUI.PluginsTreePanel import PluginsTreePanel
from MDANSE.GUI.WorkingPanel import WorkingPanel

def excepthook(error, message, tback):
    '''
    Called when an exception is raised and uncaught.
    
eric pellegrini's avatar
eric pellegrini committed
56
    Redirect the exception information to the MDANSE logger at the ERROR level.
57
        
eric pellegrini's avatar
test    
eric pellegrini committed
58
59
    :param typ: the exception class.
    :type typ: exception
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    
    @param value: the exception instance.
    @type value: exception
    
    @param tback: the traceback.
    @type tback: traceback instance  
    '''
    
    import traceback
    
    from MDANSE.Core.Error import Error

    tback = traceback.extract_tb(tback)

    trace = []                        

    if not issubclass(error, Error):
        for tb in tback:
            trace.append(' -- '.join([str(t) for t in tb]))
    
    trace.append("\n%s: %s" % (error.__name__,message))

    trace = '\n'.join(trace)
                
84
    LOGGER(trace,'error',['console','dialog'])
85
86
87
88
89
90
91
92
93
94
        
class MainFrame(wx.Frame):

    def __init__(self, parent, title="MDANSE: Molecular Dynamics Analysis for Neutron Scattering Experiments"):
        
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = (1200,800))
    
        self.build_dialog()
        
        # Add some handlers to the loggers
95
96
        consoleHandler = REGISTRY['handler']['console'](self._panels["controller"].pages["logger"])
        LOGGER.add_handler("console", consoleHandler, level="info")
97
98
99
        LOGGER.add_handler("dialog", REGISTRY['handler']['dialog'](), level="error")
        LOGGER.start()
        
100
101
102
103
        # Redirect all output to the console logger
        sys.stdout = consoleHandler
        sys.stderr = consoleHandler
                
104
        sys.excepthook = excepthook
105
                 
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    def build_dialog(self):
        
        self.build_menu()
        
        self.build_toolbar()

        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(ICONS["mdanse",32,32])
        self.SetIcon(icon) 
        
        # The main aui manager.
        self._mgr = aui.AuiManager(self)

        self._panels = {}
        self._panels["data"] = DataTreePanel(self)
        self._panels["plugins"] = PluginsTreePanel(self)
        self._panels["working"] = WorkingPanel(self)
        self._panels["controller"] = ControllerPanel(self)
        
        # Add the panes corresponding to the tree control and the notebook.
126
127
128
129
130
131
132
133
        paneInfo1=aui.AuiPaneInfo()
        self._mgr.AddPane(self._panels["data"], paneInfo1.Caption("Data").Name("data").Left().CloseButton(True).DestroyOnClose(False).MinSize((250,-1)))
        paneInfo2=aui.AuiPaneInfo()
        self._mgr.AddPane(self._panels["plugins"], paneInfo2.Caption("Plugins").Name("plugins").Left().CloseButton(True).DestroyOnClose(False).MinSize((250,-1)))
        paneInfo3=aui.AuiPaneInfo()
        self._mgr.AddPane(self._panels["working"], paneInfo3.Caption("Working panel").Name("working").Center().CloseButton(False))
        paneInfo4=aui.AuiPaneInfo()
        self._mgr.AddPane(self._panels["controller"], paneInfo4.Name("controller").Name("controller").Floatable().Right().Bottom().CloseButton(True).DestroyOnClose(False).MinSize((-1,120)))
134
135
136
137
138
139
140
141
142
143
144
145
146

        self._mgr.Update()

    def build_menu(self):
        
        self._mainMenu = wx.MenuBar()

        fileMenu = wx.Menu()
        loadDataItem = fileMenu.Append(wx.ID_ANY, 'Load data')
        fileMenu.AppendSeparator()
        converterMenu = wx.Menu()
        self._converters = {}

147
148
149
        converters = [job for job in REGISTRY["job"].items() if issubclass(job[1],Converter)]
        converters = sorted(converters)
        for name,job in converters:
150
            item = converterMenu.Append(wx.ID_ANY,job.label)
151
            self._converters[job.label] = name
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
            self.Bind(wx.EVT_MENU, self.on_open_converter, item)

        fileMenu.AppendMenu(wx.ID_ANY,'Trajectory converters',converterMenu)
        fileMenu.AppendSeparator()
        quitItem = fileMenu.Append(wx.ID_ANY, 'Quit')

        self._mainMenu.Append(fileMenu, 'File')

        viewMenu = wx.Menu()
        showDataTreeItem = viewMenu.Append(wx.ID_ANY, "Toggle data tree")
        showPluginsTreeItem = viewMenu.Append(wx.ID_ANY, "Toggle plugins tree")
        showControllerItem = viewMenu.Append(wx.ID_ANY, "Toggle controller")
        viewMenu.AppendSeparator()
        showToolbarItem = viewMenu.Append(wx.ID_ANY, "Toggle toolbar")

        self._mainMenu.Append(viewMenu, 'View')

        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ANY, 'About')
        helpMenu.AppendSeparator()
        simpleHelpItem = helpMenu.Append(wx.ID_ANY, 'Simple help')
        theoryHelpItem = helpMenu.Append(wx.ID_ANY, 'Theoretical background')
        helpMenu.AppendSeparator()
        bugReportItem = helpMenu.Append(wx.ID_ANY, 'Bug report')
        self._mainMenu.Append(helpMenu, 'Help')

        self.SetMenuBar(self._mainMenu)

        self.Bind(wx.EVT_CLOSE, self.on_quit)
        
        self.Bind(wx.EVT_MENU, self.on_load_data, loadDataItem)
        self.Bind(wx.EVT_MENU, self.on_quit, quitItem)
        self.Bind(wx.EVT_MENU, self.on_about, aboutItem)
        self.Bind(wx.EVT_MENU, self.on_toggle_data_tree, showDataTreeItem)
        self.Bind(wx.EVT_MENU, self.on_toggle_plugins_tree, showPluginsTreeItem)
        self.Bind(wx.EVT_MENU, self.on_toggle_controller, showControllerItem)
        self.Bind(wx.EVT_MENU, self.on_toggle_toolbar, showToolbarItem)
        self.Bind(wx.EVT_MENU, self.on_bug_report, bugReportItem)
        self.Bind(wx.EVT_MENU, self.on_simple_help, simpleHelpItem)
        self.Bind(wx.EVT_MENU, self.on_theory_help, theoryHelpItem)

    def build_toolbar(self):
        
        self._toolbar = self.CreateToolBar()
                
        loadDataButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["load",32,32], 'Load a trajectory')
198
        periodicTableButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["periodic_table",32,32], 'Launch the periodic table viewer')
eric pellegrini's avatar
eric pellegrini committed
199
        elementsDatabaseButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["atom",32,32], 'Launch the elements database editor')
200
201
202
        plotButton = self._toolbar.AddSimpleTool(wx.ID_ANY,ICONS["plot",32,32], 'Launch the NetCDF plotter')
        udButton = self._toolbar.AddSimpleTool(wx.ID_ANY,ICONS["user",32,32], 'Launch the user definitions editor')
        registryButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["registry",32,32], 'Inspect MDANSE classes framework')
203
        templateButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["template",32,32], 'Save a template for a new analysis')
204
205
206
207
208
209
210
211
212
213
214
215
        apiButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["api",32,32], 'Open MDANSE API')
        websiteButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["web",32,32], 'Open MDANSE website')
        aboutButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["about",32,32], 'About MDANSE')
        bugButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["bug",32,32], 'Bug report')
        quitButton = self._toolbar.AddSimpleTool(wx.ID_ANY, ICONS["quit",32,32], 'Quit MDANSE')
        
        self._toolbar.Realize()
        
        self.SetToolBar(self._toolbar)

        # The toolbar-related events handlers.
        self.Bind(wx.EVT_MENU, self.on_load_data, loadDataButton)
216
217
        self.Bind(wx.EVT_MENU, self.on_open_periodic_table, periodicTableButton)
        self.Bind(wx.EVT_MENU, self.on_open_elements_database, elementsDatabaseButton)
218
219
220
        self.Bind(wx.EVT_MENU, self.on_start_plotter, plotButton)
        self.Bind(wx.EVT_MENU, self.on_open_user_definitions, udButton)
        self.Bind(wx.EVT_MENU, self.on_open_classes_registry, registryButton)
221
        self.Bind(wx.EVT_MENU, self.on_save_job_template, templateButton)
222
223
224
225
226
227
228
        self.Bind(wx.EVT_MENU, self.on_about, aboutButton)
        self.Bind(wx.EVT_MENU, self.on_quit, quitButton)
        self.Bind(wx.EVT_MENU, self.on_open_api, apiButton)
        self.Bind(wx.EVT_MENU, self.on_open_mdanse_url, websiteButton)
        self.Bind(wx.EVT_MENU, self.on_bug_report, bugButton)
                                                                    
    def load_data(self,typ,filename):
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        if typ == "automatic":
            # if type is set on automatic, find data type
            if filename[-4:] == ".mvi":
                # File is mvi
                typ = "molecular_viewer"
                data = REGISTRY["input_data"]["molecular_viewer"](filename)
            else:
                # File is either netcdf or mmtk
                try:
                    data = REGISTRY["input_data"]["mmtk_trajectory"](filename)
                except KeyError:
                    data = REGISTRY["input_data"]["netcdf_data"](filename)
        else:
            data = REGISTRY["input_data"][typ](filename)
243
244
245
246

        DATA_CONTROLLER[data.filename] = data

    def on_about(self, event=None):
247
        if __beta__:
eric pellegrini's avatar
eric pellegrini committed
248
            beta_string = " (%s)" % __beta__
249
        else:
250
            beta_string = ""
251
        about_str = \
252
"""MDANSE version %s (commit %s).
253
254
255
256

An interactive program for analyzing Molecular Dynamics simulations.

Authors:
257
""" % (__version__ + beta_string,__commit__)
eric pellegrini's avatar
eric pellegrini committed
258
259
260

        for author in __author__.split(","):
            about_str += "\t- %s\n" % author.strip()
261
262
263
264
265
266
267
        
        d = wx.MessageDialog(self, about_str, 'About', style=wx.OK|wx.ICON_INFORMATION)
        d.ShowModal()
        d.Destroy()

    def on_bug_report(self, event=None):

268
        webbrowser.open("mailto:mdanse@ill.fr?subject=MDANSE query")        
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

    def on_simple_help(self,event):

        path = os.path.join(PLATFORM.doc_path(),'simple_help.txt')
                
        with open(path,'r') as f:
            info = f.read()
            frame = wx.Frame(self, style=wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER)
            panel = wx.Panel(frame,wx.ID_ANY)
            sizer = wx.BoxSizer(wx.VERTICAL)
            text = wx.TextCtrl(panel,wx.ID_ANY,style=wx.TE_MULTILINE|wx.TE_WORDWRAP|wx.TE_READONLY)
            text.SetValue(info)
            sizer.Add(text,1,wx.ALL|wx.EXPAND,5)
            panel.SetSizer(sizer)
            frame.Show()

    def on_theory_help(self,event):

287
        webbrowser.open("file://%s" % os.path.join(PLATFORM.doc_path(),'theory_help.pdf'))
288
289
290
                
    def on_open_classes_registry(self,event):
        
291
        from MDANSE.GUI.RegistryViewer import RegistryViewer
292
        
293
        f = RegistryViewer(self)
294
        
295
296
297
        f.ShowModal()
        
        f.Destroy()
298
299
300
301
302
303
304
305
306
307
        
    def on_save_job_template(self,event):
        
        from MDANSE.GUI.JobTemplateEditor import JobTemplateEditor
        
        f = JobTemplateEditor(self)
        
        f.ShowModal()
        
        f.Destroy()
308
309
310
311

    def on_open_api(self, event):
        
        mainHTML = os.path.join(PLATFORM.api_path(),'MDANSE.html')
312
        
313
        if os.path.exists(mainHTML):
314
            webbrowser.open("file://%s" % mainHTML)
315
316
317
318
319
        else:
            LOGGER("Can not open MDANSE API. Maybe the documentation was not properly installed.", "error",['dialog'])
            
    def on_load_data(self, event=None):

320
        wildcards = collections.OrderedDict([kls._type, "%s (*.%s)|*.%s" % (kls._type,kls.extension,kls.extension)] for kls in REGISTRY["input_data"].values() if kls.extension is not None)
321
322

        dialog = wx.FileDialog ( None, message='Open data ...', wildcard="automatic (*.mvi,*.nc)|*.mvi;*.nc|" + "|".join(wildcards.values()), style=wx.OPEN)
323
324
325
326
327
        
        if dialog.ShowModal() == wx.ID_CANCEL:
            return ""
                
        idx = dialog.GetFilterIndex()
328
329
330
331
332
        # Check if automatic has been chosen
        if idx <= 0:
            dataType = "automatic"
        else:
            dataType = wildcards.keys()[idx-1]
333
334
335
336
337
338
339
340
                        
        filename = dialog.GetPath()
        
        if not filename:
            return
        
        self.load_data(dataType,filename)
                
341
        LOGGER("Data %r successfully loaded." % filename, "info", ["console"])
342
343
344
                                                            
    def on_open_user_definitions(self,event):
        
345
        from MDANSE.GUI.UserDefinitionViewer import UserDefinitionViewer
346
        
347
        f = UserDefinitionViewer(self)
348
349
        f.ShowModal()
        f.Destroy()
350
351
352

    def on_open_converter(self,event):

353
        from MDANSE.GUI.Plugins.JobPlugin import JobFrame
354

355
        item = self.GetMenuBar().FindItemById(event.GetId())
356
        converter = item.GetText()
357
                        
358
        f = JobFrame(self,self._converters[converter],os.path.join(PLATFORM.home_directory(),"trajectory_conversion.nc"))
359
360
        f.Show()

361
    def on_open_periodic_table(self, event):
362

363
        from MDANSE.GUI.PeriodicTableViewer import PeriodicTableViewer
364
                
365
        f = PeriodicTableViewer(self)
366
367
368
        
        f.Show()

369
370
371
372
373
374
375
376
    def on_open_elements_database(self, event):

        from MDANSE.GUI.ElementsDatabaseEditor import ElementsDatabaseEditor
                
        f = ElementsDatabaseEditor(self)
        
        f.Show()

377
378
    def on_open_mdanse_url(self, event):

379
        webbrowser.open('http://mdanse.org')
380
381
382
383
384
385
386
387
388

    def on_quit(self, event=None):
        
        d = wx.MessageDialog(None, 'Do you really want to quit ?', 'Question', wx.YES_NO|wx.YES_DEFAULT|wx.ICON_QUESTION)
        if d.ShowModal() == wx.ID_YES:
            self.Destroy()
                                                                         
    def on_start_plotter(self, event = None):

389
        from MDANSE.GUI.Plugins.PlotterPlugin import PlotterFrame
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        
        f = PlotterFrame(self)
        
        f.Show()                                               
                
    def on_toggle_controller(self, event=None):

        pane = self._mgr.GetPane("controller")        
        
        self.toggle_window(pane)

    def on_toggle_data_tree(self, event=None):

        pane = self._mgr.GetPane("data")        
        
        self.toggle_window(pane)
        
    def on_toggle_plugins_tree(self, event = None):
        
        pane = self._mgr.GetPane("plugins")
        
        self.toggle_window(pane)    

    def on_toggle_toolbar(self, event=None):

415
416
        self._prevSize = self.GetSize()

417
        if self.GetToolBar():
418
            sizeH = self._prevSize[1] - self._toolbar.GetSize()[1]
419
            self._toolbar.Hide()
420
421
            self.SetToolBar(None)
        else:
422
            sizeH = self._prevSize[1] + self._toolbar.GetSize()[1]
423
            self.SetToolBar(self._toolbar)
424
425
426
427
            self._toolbar.Show()
            
        self.SetSize((-1,sizeH))
            
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
    @property
    def panels(self):
        return self._panels
        
    def toggle_window(self, window):
        
        if window.IsShown():
            window.Hide()
        else:
            window.Show()

        self._mgr.Update()
        
if __name__ == "__main__":
    
443
444
445
    from MDANSE.GUI.Apps import MainApplication
    
    app = MainApplication(None)
446
    app.MainLoop()