source: sasview/calculatorview/perspectives/calculator/sld_panel.py @ 53ddcdb

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

make sure there is args for neutron_scattering method

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