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

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 7c8d3093 was 7d45a56, checked in by Jae Cho <jhjcho@…>, 13 years ago

move calculatorview perspective under sans folder

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