source: sasview/calculatorview/perspectives/calculator/sld_panel.py @ 66bfacf

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 66bfacf was 66bfacf, checked in by Gervaise Alina <gervyh@…>, 14 years ago

add a unitest for gui sld calculator

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