QVectorsWidget.py 11.1 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#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 Mar 30, 2015

:author: Eric C. Pellegrini
'''

import os

import wx
import wx.aui as wxaui
import wx.grid as wxgrid
from wx.lib.delayedresult import startWorker

from MDANSE import LOGGER, REGISTRY
from MDANSE.Framework.Widgets.UserDefinitionWidget import UserDefinitionsDialog,UserDefinitionWidget
from MDANSE.GUI.ComboWidgets.ConfigurationPanel import ConfigurationPanel
from MDANSE.GUI.ComboWidgets.ProgressBar import ProgressBar

class QVectorsData(wxgrid.PyGridTableBase):
    
    def __init__(self, data=None):
        
        wxgrid.PyGridTableBase.__init__(self)

        self._colLabels = ["Qx","Qy","Qz","|Q|","h","k","l"]
        
        self._data=data
           
        self._grid = []                     
        if self._data is not None:
            
            for v in self._data.values():

                if not v:
                    continue

                for i in range(v["n_q_vectors"]):
                    temp = []
                    temp.extend(["%8.3f" % val for val in v["q_vectors"][:,i]])
                    temp.extend(["%8.3f" % v["q"]])
                    if v["hkls"] is not None:
                        temp.extend(["%d" % val for val in v["hkls"][:,i]])
                    else:
                        temp.extend(['-']*3)
                
                    self._grid.append(temp)
                    
    @property
    def data(self):
        return self._data

    def GetAttr(self, row, col, kind):
        
        attr = wxgrid.GridCellAttr()
        attr.SetBackgroundColour(wx.NamedColour("LIGHT BLUE"))
        if col == 3:
            attr.SetTextColour(wx.RED)
        attr.SetReadOnly(True)
        attr.SetAlignment(wx.ALIGN_RIGHT,wx.ALIGN_CENTRE)
        
        return attr        
                            
    def GetNumberRows(self):
        
        return len(self._grid)
                
    def GetNumberCols(self):

        return 7

    def GetColLabelValue(self, col):
        
        return self._colLabels[col]
                    
    def GetRowLabelValue(self, row):
        return row+1
        
    def GetValue(self, row, col):
        
        if self._grid is None:
            return "-"
        else:
            return self._grid[row][col]
                    
    def SetValue(self, row, col, value):
        pass
                            
class QVectorsPanel(wx.Panel):
    
    def __init__(self, generator,parameters,*args, **kwargs):
                                        
        wx.Panel.__init__(self, *args, **kwargs)
                
        self._generator = generator
        self._parameters = parameters
                
        self._grid = wxgrid.Grid(self)
        self._grid.DisableCellEditControl()
        
        self._progress = ProgressBar(self)
                
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self._grid, 1, wx.ALL|wx.EXPAND, 5)
        sizer.Add(self._progress, 0, wx.ALL|wx.EXPAND, 5)
                
        self.SetSizer(sizer)

    @property
    def grid(self):
        
        return self._grid

    @property
    def generator(self):
        
        return self._generator

    @property
    def parameters(self):
        
        return self._parameters

    @property
    def progress(self):
        
        return self._progress
                            
class QVectorsDialog(UserDefinitionsDialog):
    
    type = 'q_vectors'
            
    def __init__(self, parent, trajectory):

        self._currentGenerator = None

        self._value = None
                
        self._trajectory = trajectory
        
        target = os.path.basename(self._trajectory.filename)

        UserDefinitionsDialog.__init__(self, parent, target, wx.ID_ANY, title="Q vectors generator dialog",style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX)
        
        self.SetSize((800,700))
                                                                  
    def build_dialog(self):   

        sizer = wx.BoxSizer(wx.VERTICAL)
                 
        # Widgets and sizers related to generator section        
        self._panel = wx.ScrolledWindow(self, wx.ID_ANY, size=self.GetSize())
        self._panel.SetScrollbars(20,20,50,50)
        sb1 = wx.StaticBox(self._panel, wx.ID_ANY, label="generator")
        sbSizer1 = wx.StaticBoxSizer(sb1, wx.VERTICAL)
        self._availableGenerators = wx.Choice(self._panel, wx.ID_ANY)
        if self._trajectory.universe.is_periodic:
            choices = REGISTRY["q_vectors"].keys()
        else:
            choices = [k for k,v in REGISTRY["q_vectors"].items() if not v.is_lattice]        
        self._availableGenerators.SetItems(choices)
        self._availableGenerators.SetSelection(0)
        generateButton  = wx.Button(self._panel, wx.ID_ANY, label="Generate")
        sbSizer1.Add(self._availableGenerators, 1, wx.ALL|wx.EXPAND, 5)        
        sbSizer1.Add(generateButton, 1, wx.ALL|wx.EXPAND, 5)        
        sizer.Add(sbSizer1, 0, wx.ALL|wx.EXPAND, 5)
    
        # Widgets and sizers related to parameters section        
        sb2 = wx.StaticBox(self._panel, wx.ID_ANY, label="parameters")
        self._parametersSizer = wx.StaticBoxSizer(sb2, wx.VERTICAL)
        sizer.Add(self._parametersSizer, 0, wx.ALL|wx.EXPAND, 5)

        self._notebook = wxaui.AuiNotebook(self._panel, wx.ID_ANY, style=wxaui.AUI_NB_DEFAULT_STYLE^wxaui.AUI_NB_TAB_MOVE)

        sizer.Add(self._notebook, 3, wx.ALL|wx.EXPAND, 5)
                 
        self._panel.SetSizer(sizer)

        self._mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 5)

        self.select_generator(self._availableGenerators.GetStringSelection())
                                 
        self.Bind(wxaui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_tab, self._notebook)
        self.Bind(wx.EVT_BUTTON, self.on_generate_q_vectors, generateButton)
        self.Bind(wx.EVT_CHOICE, self.on_select_generator, self._availableGenerators)

    def set_user_definition(self):

        if self._notebook.GetPageCount() == 0:
            LOGGER("No Q vectors generated.", "error")
            return

        qPanel = self._notebook.GetPage(self._notebook.GetSelection())

        if qPanel._grid.GetTable().data is None:
            LOGGER("No data is the selected Q vectors tab", "error")
            return
        
        self._ud['parameters'] = (qPanel.generator.type,qPanel.parameters)
eric pellegrini's avatar
eric pellegrini committed
225
        self._ud['generator'] = qPanel.generator.type
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
        self._ud['q_vectors'] = qPanel.grid.GetTable().data
        self._ud['is_lattice'] = qPanel.generator.is_lattice
                
    def on_close(self, event):
        
        self.Destroy()
        
    def on_close_tab(self, event):
        
        if event.GetSelection() == 0:
            event.Veto()
        else:
            qPanel = event.GetEventObject().GetPage(event.GetSelection())
            if qPanel.progress.is_running():
                d = wx.MessageDialog(None, 'The background task is still running. You must cancel it before closing this tab.', 'Warning', wx.OK|wx.ICON_WARNING)
                d.ShowModal()
                event.Veto()
                return            
                    
    def generate_q_vectors(self,generator):
                                
        generator.generate()
                         
        return generator['q_vectors']
    
    def generate_q_vectors_done(self,result,qPanel):
                
        data = result.get()
        if data:
            table = QVectorsData(data)
            qPanel.grid.SetTable(table)
            qPanel.grid.Refresh()
        
    def on_generate_q_vectors(self, event):

        generator = self._availableGenerators.GetStringSelection()
        generator = REGISTRY["q_vectors"][generator](self._trajectory.universe)
        parameters = self._configurationPanel.get_value()
        generator.setup(parameters)
        
        qPanel = QVectorsPanel(generator,parameters,self._panel,wx.ID_ANY)
        self._notebook.AddPage(qPanel, "Q Vectors")
        
        generator.setStatus(qPanel.progress)
                
        startWorker(self.generate_q_vectors_done, self.generate_q_vectors, cargs=(qPanel,),wargs=(generator,))                                          
                
    def on_select_generator(self, event):
                                
        self.select_generator(event.GetString())
            
    def validate(self):

        self.set_user_definition()
        
        if not self._ud['q_vectors']:
            LOGGER("No Q vectors generated.", "error", ["dialog"])
            return None
        
        return self._ud
                
    def select_generator(self, generatorName):
                         
        if generatorName == self._currentGenerator:
            return
                               
        self._currentGenerator = REGISTRY["q_vectors"][generatorName](self._trajectory.universe)
         
        self._parametersSizer.Clear(deleteWindows=True)
 
        self.Freeze()
                 
        self._configurationPanel = ConfigurationPanel(self._panel, self._currentGenerator)
 
        self._parametersSizer.Add(self._configurationPanel, 1, wx.ALL|wx.EXPAND, 5)
                                 
        self.Thaw()
                         
        self._parametersSizer.Layout()
        
class QVectorsWidget(UserDefinitionWidget):
        
    type = "q_vectors"

    def on_new_user_definition(self,event):
        
        qVectorsDlg = QVectorsDialog(self,self._trajectory)
        
        qVectorsDlg.ShowModal()

        qVectorsDlg.Destroy()
        
if __name__ == "__main__":
    
    from MMTK.Trajectory import Trajectory
    
    t = Trajectory(None,"../../../../../Data/Trajectories/MMTK/protein_in_periodic_universe.nc","r")
    
    app = wx.App(False)
            
    p = QVectorsDialog(None,t)
        
    p.ShowModal()
    
    p.Destroy()
    
    app.MainLoop()