source: sasview/calculatorview/src/sans/perspectives/calculator/sld_panel.py @ d0923a3

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d0923a3 was d0923a3, checked in by Jae Cho <jhjcho@…>, 11 years ago

Instead of mdi, use wxframe on linux

  • Property mode set to 100644
File size: 19.5 KB
Line 
1"""
2This module provide GUI for the neutron scattering length density calculator
3
4"""
5
6import wx
7import math
8import sys
9
10from sans.guiframe.panel_base import PanelBase
11
12from sans.guiframe.utils import format_number
13from sans.guiframe.utils import check_float
14from sans.guiframe.events import StatusEvent 
15
16# the calculator default value for wavelength is 6
17#import periodictable
18from periodictable import formula
19from periodictable.xsf import xray_energy
20from periodictable.xsf import xray_sld_from_atoms
21from periodictable.nsf import neutron_scattering
22from sans.perspectives.calculator import calculator_widgets as widget   
23       
24WAVELENGTH = 6.0
25_BOX_WIDTH = 76
26_STATICBOX_WIDTH = 350
27_SCALE = 1e-6
28
29#SLD panel size
30if sys.platform.count("win32") > 0:
31    _STATICBOX_WIDTH = 350
32    PANEL_SIZE = 400
33    FONT_VARIANT = 0
34else:
35    _STATICBOX_WIDTH = 380
36    PANEL_SIZE = 410
37    FONT_VARIANT = 1
38   
39class SldPanel(wx.Panel, PanelBase):
40    """
41    Provides the SLD calculator GUI.
42    """
43    ## Internal nickname for the window, used by the AUI manager
44    window_name = "SLD Calculator"
45    ## Name to appear on the window title bar
46    window_caption = "SLD Calculator"
47    ## Flag to tell the AUI manager to put this panel in the center pane
48    CENTER_PANE = True
49   
50    def __init__(self, parent, base=None, *args, **kwds):
51        """
52        """
53        wx.Panel.__init__(self, parent, *args, **kwds)
54        PanelBase.__init__(self)
55        #Font size
56        self.SetWindowVariant(variant=FONT_VARIANT)
57        # Object that receive status event
58        self.base = base
59        self.wavelength = WAVELENGTH
60        #layout attribute
61        self.compound_ctl = None
62        self.density_ctl = None
63        self.compound = ""
64        self.density = ""
65        self.wavelength_ctl = None
66        self.neutron_sld_real_ctl = None
67        self.neutron_sld_im_ctl = None
68        self.mo_ka_sld_real_ctl = None
69        self.mo_ka_sld_im_ctl = None
70        self.cu_ka_sld_real_ctl = None
71        self.cu_ka_sld_im_ctl = None
72        self.neutron_abs_ctl = None
73        self.neutron_inc_ctl = None
74        self.neutron_length_ctl = None
75        self.button_calculate = None
76        #Draw the panel
77        self._do_layout()
78        self.SetAutoLayout(True)
79        self.Layout()
80       
81    def _do_layout(self):
82        """
83        Draw window content
84        """
85        unit_a = '[A]'
86        unit_density = '[g/cm^(3)]'
87        unit_sld = '[1/A^(2)]'
88        unit_cm1 = '[1/cm]'
89        unit_cm = '[cm]'
90        sizer_input = wx.GridBagSizer(5, 5)
91        sizer_output = wx.GridBagSizer(5, 5)
92        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
93        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
94        sizer2 = wx.BoxSizer(wx.HORIZONTAL)
95        sizer3 = wx.BoxSizer(wx.HORIZONTAL)
96        #---------inputs----------------
97        inputbox = wx.StaticBox(self, -1, "Input")
98        boxsizer1 = wx.StaticBoxSizer(inputbox, wx.VERTICAL)
99        boxsizer1.SetMinSize((_STATICBOX_WIDTH, -1))
100       
101        compound_txt = wx.StaticText(self, -1, 'Compound ')
102        self.compound_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH*2, -1))
103        density_txt = wx.StaticText(self, -1, 'Density ')
104        self.density_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))
105        unit_density_txt = wx.StaticText(self, -1, unit_density)
106        wavelength_txt = wx.StaticText(self, -1, 'Wavelength ')
107        self.wavelength_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))
108        self.wavelength_ctl.SetValue(str(self.wavelength))
109        unit_a_txt = wx.StaticText(self, -1, unit_a)
110        iy = 0
111        ix = 0
112        sizer_input.Add(compound_txt, (iy, ix), (1, 1),
113                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
114        ix += 1
115        sizer_input.Add(self.compound_ctl, (iy, ix), (1, 1),
116                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
117        iy += 1
118        ix = 0
119        sizer_input.Add(density_txt, (iy, ix), (1, 1),
120                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
121        ix += 1
122        sizer_input.Add(self.density_ctl, (iy, ix), (1, 1),
123                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
124        ix +=1
125        sizer_input.Add(unit_density_txt,(iy, ix), (1, 1),
126                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
127        iy += 1
128        ix = 0
129        sizer_input.Add(wavelength_txt, (iy, ix), (1, 1),
130                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
131        ix += 1
132        sizer_input.Add(self.wavelength_ctl, (iy, ix), (1, 1),
133                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
134        ix += 1
135        sizer_input.Add(unit_a_txt, (iy, ix), (1, 1),
136                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
137        boxsizer1.Add(sizer_input)
138        sizer1.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)
139        #---------Outputs sizer--------
140        outputbox = wx.StaticBox(self, -1, "Output")
141        boxsizer2 = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
142        boxsizer2.SetMinSize((_STATICBOX_WIDTH, -1))
143       
144        i_complex = '- i'
145        neutron_sld_txt = wx.StaticText(self, -1, 'Neutron SLD')
146        self.neutron_sld_real_ctl = wx.TextCtrl(self, -1,
147                                                 size=(_BOX_WIDTH, -1))
148        self.neutron_sld_real_ctl.SetEditable(False)
149        self.neutron_sld_real_ctl.SetToolTipString("Neutron SLD real.")
150        self.neutron_sld_im_ctl = wx.TextCtrl(self, -1, 
151                                              size=(_BOX_WIDTH, -1))
152        self.neutron_sld_im_ctl.SetEditable(False)
153        self.neutron_sld_im_ctl.SetToolTipString("Neutron SLD imaginary.")
154        neutron_sld_units_txt = wx.StaticText(self, -1, unit_sld)
155       
156        cu_ka_sld_txt = wx.StaticText(self, -1, 'Cu Ka SLD')
157        self.cu_ka_sld_real_ctl = wx.TextCtrl(self, -1,
158                                               size=(_BOX_WIDTH, -1))
159        self.cu_ka_sld_real_ctl.SetEditable(False)
160        self.cu_ka_sld_real_ctl.SetToolTipString("Cu Ka SLD real.")
161        self.cu_ka_sld_im_ctl = wx.TextCtrl(self, -1, 
162                                            size=(_BOX_WIDTH, -1))
163        self.cu_ka_sld_im_ctl.SetEditable(False)
164        self.cu_ka_sld_im_ctl.SetToolTipString("Cu Ka SLD imaginary.")
165        cu_ka_sld_units_txt = wx.StaticText(self, -1, unit_sld)
166       
167        mo_ka_sld_txt = wx.StaticText(self, -1, 'Mo Ka SLD')
168        self.mo_ka_sld_real_ctl = wx.TextCtrl(self, -1,
169                                               size=(_BOX_WIDTH, -1))
170        self.mo_ka_sld_real_ctl.SetEditable(False)
171        self.mo_ka_sld_real_ctl.SetToolTipString("Mo Ka SLD real.")
172        self.mo_ka_sld_im_ctl = wx.TextCtrl(self, -1,
173                                             size=(_BOX_WIDTH, -1))
174        self.mo_ka_sld_im_ctl.SetEditable(False)
175        self.mo_ka_sld_im_ctl.SetToolTipString("Mo Ka SLD imaginary.")
176        mo_ka_sld_units_txt = wx.StaticText(self, -1, unit_sld)
177       
178        neutron_inc_txt = wx.StaticText(self, -1, 'Neutron Inc. Xs')
179        self.neutron_inc_ctl = wx.TextCtrl(self, -1,
180                                            size=(_BOX_WIDTH, -1))
181        self.neutron_inc_ctl.SetEditable(False)
182        self.neutron_inc_ctl.SetToolTipString("Neutron Inc. Xs")
183        neutron_inc_units_txt = wx.StaticText(self, -1,  unit_cm1)
184       
185        neutron_abs_txt = wx.StaticText(self, -1, 'Neutron Abs. Xs')     
186        self.neutron_abs_ctl = wx.TextCtrl(self, -1, 
187                                           size=(_BOX_WIDTH, -1))
188        self.neutron_abs_ctl.SetEditable(False)
189        self.neutron_abs_ctl.SetToolTipString("Neutron Abs. Xs")
190        neutron_abs_units_txt = wx.StaticText(self, -1,  unit_cm1)
191     
192        neutron_length_txt = wx.StaticText(self, -1, 'Neutron 1/e length')
193        self.neutron_length_ctl = wx.TextCtrl(self, -1,
194                                               size=(_BOX_WIDTH, -1))
195        self.neutron_length_ctl.SetEditable(False)
196        self.neutron_length_ctl.SetToolTipString("Neutron 1/e length")
197        neutron_length_units_txt = wx.StaticText(self, -1,  unit_cm)
198     
199        iy = 0
200        ix = 0
201        sizer_output.Add(neutron_sld_txt, (iy, ix), (1, 1),
202                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
203        ix += 1
204        sizer_output.Add(self.neutron_sld_real_ctl, (iy, ix), (1, 1),
205                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
206        ix += 1
207        sizer_output.Add(wx.StaticText(self, -1, i_complex),
208                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
209        ix += 1
210        sizer_output.Add(self.neutron_sld_im_ctl,
211                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
212        ix += 1
213        sizer_output.Add(neutron_sld_units_txt,
214                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
215        iy += 1
216        ix = 0
217        sizer_output.Add(cu_ka_sld_txt, (iy, ix), (1, 1),
218                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
219        ix += 1
220        sizer_output.Add(self.cu_ka_sld_real_ctl, (iy, ix), (1, 1),
221                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
222        ix += 1
223        sizer_output.Add(wx.StaticText(self, -1, i_complex),
224                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
225        ix += 1
226        sizer_output.Add(self.cu_ka_sld_im_ctl,
227                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
228        ix += 1
229        sizer_output.Add(cu_ka_sld_units_txt,
230                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
231        iy += 1
232        ix = 0
233        sizer_output.Add(mo_ka_sld_txt,(iy, ix), (1, 1),
234                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
235        ix += 1
236        sizer_output.Add(self.mo_ka_sld_real_ctl,(iy, ix), (1, 1),
237                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
238        ix += 1
239        sizer_output.Add(wx.StaticText(self, -1, i_complex),
240                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
241        ix += 1
242        sizer_output.Add(self.mo_ka_sld_im_ctl,
243                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
244        ix += 1
245        sizer_output.Add(mo_ka_sld_units_txt,
246                         (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
247        iy += 1
248        ix = 0
249        sizer_output.Add(neutron_inc_txt, (iy, ix), (1, 1),
250                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
251        ix += 1
252        sizer_output.Add(self.neutron_inc_ctl, (iy, ix), (1, 1),
253                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
254        ix += 2
255        sizer_output.Add(neutron_inc_units_txt,(iy, ix), (1, 1),
256                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
257        iy += 1
258        ix = 0
259        sizer_output.Add(neutron_abs_txt, (iy, ix), (1, 1),
260                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
261        ix += 1
262        sizer_output.Add(self.neutron_abs_ctl, (iy, ix), (1, 1),
263                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
264        ix += 2
265        sizer_output.Add(neutron_abs_units_txt, (iy, ix), (1, 1),
266                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
267        iy += 1
268        ix = 0
269        sizer_output.Add(neutron_length_txt, (iy, ix), (1, 1),
270                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
271        ix += 1
272        sizer_output.Add(self.neutron_length_ctl, (iy, ix), (1, 1),
273                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
274        ix += 2
275        sizer_output.Add(neutron_length_units_txt, (iy, ix), (1, 1),
276                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
277        boxsizer2.Add(sizer_output)
278        sizer2.Add(boxsizer2, 0, wx.EXPAND|wx.ALL, 10)
279        #-----Button  sizer------------
280   
281        id = wx.NewId()
282        self.button_calculate = wx.Button(self, id, "Calculate")
283        self.button_calculate.SetToolTipString("Calculate SLD.")
284        self.Bind(wx.EVT_BUTTON, self.calculateSld, id=id)   
285       
286        sizer_button.Add((250, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
287        sizer_button.Add(self.button_calculate, 0, wx.RIGHT|wx.ADJUST_MINSIZE, 20)
288        sizer3.Add(sizer_button)
289        #---------layout----------------
290        vbox  = wx.BoxSizer(wx.VERTICAL)
291        vbox.Add(sizer1)
292        vbox.Add(sizer2)
293        vbox.Add(sizer3)
294        vbox.Fit(self) 
295        self.SetSizer(vbox)
296       
297    def calculate_xray_sld(self, element):
298        """
299        Get an element and compute the corresponding SLD for a given formula
300       
301        :param element:  elements a string of existing atom
302       
303        """
304        myformula = formula(str(element))
305        if len(myformula.atoms) != 1:
306            return 
307        element = myformula.atoms.keys()[0] 
308        energy = xray_energy(element.K_alpha)
309       
310        self.sld_formula = formula(str(self.compound), density=self.density)
311        atom = self.sld_formula.atoms
312        return xray_sld_from_atoms(atom, density=self.density, energy= energy)
313   
314    def check_inputs(self):
315        """Check validity user inputs"""
316        flag = True
317        msg = ""
318        if check_float(self.density_ctl):
319            self.density = float(self.density_ctl.GetValue())
320        else:
321            flag = False
322            msg += "Error for Density value :expect float"
323   
324        self.wavelength = self.wavelength_ctl.GetValue()
325        if str(self.wavelength).lstrip().rstrip() == "":
326            self.wavelength = WAVELENGTH
327            self.wavelength_ctl.SetValue(str(WAVELENGTH))
328            self.wavelength_ctl.SetBackgroundColour(wx.WHITE)
329            self.wavelength_ctl.Refresh()
330            msg += "Default value for wavelength is 6.0"
331        else:
332            if check_float(self.wavelength_ctl):
333                self.wavelength = float(self.wavelength)
334            else:
335                flag = False
336                msg += "Error for wavelength value :expect float"
337               
338        self.compound = self.compound_ctl.GetValue().lstrip().rstrip()
339        if self.compound != "":
340            try :
341                formula(self.compound)
342                self.compound_ctl.SetBackgroundColour(wx.WHITE)
343                self.compound_ctl.Refresh()
344            except:
345                self.compound_ctl.SetBackgroundColour("pink")
346                self.compound_ctl.Refresh()
347                flag = False
348                msg += "Enter correct formula"
349        else:
350            self.compound_ctl.SetBackgroundColour("pink")
351            self.compound_ctl.Refresh()
352            flag = False
353            msg += "Enter a formula"
354        return flag, msg
355       
356    def calculate_sld_helper(self, element, density, molecule_formula):
357        """
358        Get an element and compute the corresponding SLD for a given formula
359       
360        :param element:  elements a string of existing atom
361       
362        """
363        element_formula = formula(str(element))
364        if len(element_formula.atoms) != 1:
365            return 
366        element = element_formula.atoms.keys()[0] 
367        energy = xray_energy(element.K_alpha)
368        atom = molecule_formula.atoms
369        return xray_sld_from_atoms(atom, density=density, energy=energy)
370
371
372    def calculateSld(self, event):
373        """
374            Calculate the neutron scattering density length of a molecule
375        """
376        self.clear_outputs()
377        try:
378            #Check validity user inputs
379            flag, msg = self.check_inputs()
380            if self.base is not None and msg.lstrip().rstrip() != "":
381                msg = "SLD Calculator: %s" % str(msg)
382                wx.PostEvent(self.base, StatusEvent(status=msg))
383            if not flag:
384               return 
385            #get ready to compute
386            self.sld_formula = formula(self.compound,
387                                            density=self.density)
388            (sld_real, sld_im, _), (_, absorp, incoh), \
389                        length = neutron_scattering(compound=self.compound,
390                                   density=self.density, 
391                                   wavelength=self.wavelength) 
392            cu_real, cu_im = self.calculate_sld_helper(element="Cu",
393                                                 density=self.density,
394                                        molecule_formula=self.sld_formula)
395            mo_real, mo_im = self.calculate_sld_helper(element="Mo", 
396                                                       density=self.density,
397                                     molecule_formula=self.sld_formula)
398            # set neutron sld values
399            val = format_number(sld_real * _SCALE)
400            self.neutron_sld_real_ctl.SetValue(val)
401            val = format_number(math.fabs(sld_im) * _SCALE)
402            self.neutron_sld_im_ctl.SetValue(val)
403            # Compute the Cu SLD
404            self.cu_ka_sld_real_ctl.SetValue(format_number(cu_real *_SCALE))
405            val = format_number(math.fabs(cu_im )* _SCALE)
406            self.cu_ka_sld_im_ctl.SetValue(val)
407            # Compute the Mo SLD
408            self.mo_ka_sld_real_ctl.SetValue(format_number(mo_real *_SCALE))
409            val = format_number(math.fabs(mo_im)* _SCALE)
410            self.mo_ka_sld_im_ctl.SetValue(val)
411            # set incoherence and absorption
412            self.neutron_inc_ctl.SetValue(format_number(incoh))
413            self.neutron_abs_ctl.SetValue(format_number(absorp))
414            # Neutron length
415            self.neutron_length_ctl.SetValue(format_number(length))
416            # display wavelength
417            self.wavelength_ctl.SetValue(str(self.wavelength))
418        except:
419            if self.base is not None:
420                msg = "SLD Calculator: %s"%(sys.exc_value)
421                wx.PostEvent(self.base, StatusEvent(status=msg))
422        if event is not None:
423            event.Skip()
424           
425    def clear_outputs(self):
426        """
427        Clear the outputs textctrl
428        """
429        self.neutron_sld_real_ctl.SetValue("")
430        self.neutron_sld_im_ctl.SetValue("")
431        self.mo_ka_sld_real_ctl.SetValue("")
432        self.mo_ka_sld_im_ctl.SetValue("")
433        self.cu_ka_sld_real_ctl.SetValue("")
434        self.cu_ka_sld_im_ctl.SetValue("")
435        self.neutron_abs_ctl.SetValue("")
436        self.neutron_inc_ctl.SetValue("")
437        self.neutron_length_ctl.SetValue("")
438       
439       
440class SldWindow(widget.CHILD_FRAME):
441    """
442    """
443    def __init__(self, parent=None, title="SLD Calculator",
444                  base=None, manager=None, 
445                  size=(PANEL_SIZE, PANEL_SIZE), *args, **kwds):
446        """
447        """
448        kwds['title'] = title
449        kwds['size'] = size
450        widget.CHILD_FRAME.__init__(self, parent, *args, **kwds)
451        """
452        """
453        self.parent = parent
454        self.base = base
455        self.manager = manager
456        self.panel = SldPanel(self, base=base)
457        self.Bind(wx.EVT_CLOSE, self.on_close)
458        self.SetPosition((25, 100))
459        self.Show(True)
460   
461    def on_close(self, event):
462        """
463        On close event
464        """
465        if self.manager != None:
466            self.manager.sld_frame = None
467        self.Destroy()
468       
469       
470class ViewApp(wx.App):
471    """
472    """
473    def OnInit(self):
474        """
475        """
476        frame = SldWindow(None, title='SLD Calculator')   
477        frame.Show(True)
478        self.SetTopWindow(frame)
479        return True
480       
481
482if __name__ == "__main__": 
483    app = ViewApp(0)
484    app.MainLoop()     
Note: See TracBrowser for help on using the repository browser.