source: sasview/calculatorview/src/sans/perspectives/calculator/gen_scatter_panel.py @ 9624cda

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 9624cda was 9624cda, checked in by Jae Cho <jhjcho@…>, 11 years ago

fixed debye averging in gensans

  • Property mode set to 100644
File size: 75.6 KB
Line 
1"""
2Generic Scattering panel.
3This module relies on guiframe manager.
4"""
5
6import wx
7import sys
8import os
9import numpy
10#import math
11import wx.aui as aui
12#import wx.lib.agw.aui as aui
13import logging
14import time
15
16import matplotlib
17matplotlib.interactive(False)
18#Use the WxAgg back end. The Wx one takes too long to render
19matplotlib.use('WXAgg')
20
21from data_util.calcthread import CalcThread
22from sans.guiframe.local_perspectives.plotting.SimplePlot import PlotFrame
23from sans.guiframe.dataFitting import Data2D
24from sans.guiframe.dataFitting import Data1D
25from sans.dataloader.data_info import Detector
26from sans.dataloader.data_info import Source
27from sans.guiframe.panel_base import PanelBase
28from sans.guiframe.utils import format_number
29from sans.guiframe.events import StatusEvent 
30from sans.calculator import sans_gen
31from sans.perspectives.calculator.calculator_widgets import OutputTextCtrl
32from sans.perspectives.calculator.calculator_widgets import InputTextCtrl
33from wx.lib.scrolledpanel import ScrolledPanel
34from sans.perspectives.calculator.load_thread import GenReader
35from danse.common.plottools.arrow3d import Arrow3D
36
37_BOX_WIDTH = 76
38#Slit length panel size
39if sys.platform.count("win32") > 0:
40    PANEL_WIDTH = 570
41    PANEL_HEIGHT = 370
42    FONT_VARIANT = 0
43else:
44    PANEL_WIDTH = 620
45    PANEL_HEIGHT = 370
46    FONT_VARIANT = 1
47_QMAX_DEFAULT = 0.3
48_NPTS_DEFAULT = 50 
49_Q1D_MIN = 0.001
50
51def add_icon(parent, frame):
52    """
53    Add icon in the frame
54    """
55    if parent != None:
56        if hasattr(frame, "IsIconized"):
57            if not frame.IsIconized():
58                try:
59                    icon = parent.GetIcon()
60                    frame.SetIcon(icon)
61                except:
62                    pass 
63
64def _set_error(panel, item, show_msg=False):
65    """
66    Set_error dialog
67    """
68    if item != None:
69        item.SetBackgroundColour("pink")
70        item.Refresh()
71    if show_msg:
72        msg = "Error: wrong (or out of range) value entered."
73        if panel.parent.parent != None:
74            wx.PostEvent(panel.parent.parent, 
75                     StatusEvent(status=msg, info='Error' )) 
76            panel.SetFocus()
77    return False
78
79class CalcGen(CalcThread):
80    """
81    Computation
82    """
83    def __init__(self,
84                 id=-1,
85                 input = None,
86                 completefn = None,
87                 updatefn   = None,
88                 #elapsed = 0,
89                 yieldtime  = 0.01,
90                 worktime   = 0.01):
91        """
92        """
93        CalcThread.__init__(self, completefn,
94                 updatefn,
95                 yieldtime,
96                 worktime)
97        self.starttime = 0
98        self.id = id 
99        self.input = input 
100        self.update_fn = updatefn
101       
102    def compute(self):
103        """
104        excuting computation
105        """
106        #elapsed = time.time() - self.starttime
107        self.starttime = time.time()
108        self.complete(input=self.input, update=self.update_fn)
109           
110class SasGenPanel(ScrolledPanel, PanelBase):
111    """
112        Provides the sas gen calculator GUI.
113    """
114    ## Internal nickname for the window, used by the AUI manager
115    window_name = "Generic SANS Calculator"
116    ## Name to appear on the window title bar
117    window_caption = "Generic SANS "
118    ## Flag to tell the AUI manager to put this panel in the center pane
119    CENTER_PANE = True
120   
121    def __init__(self, parent, *args, **kwds):
122        ScrolledPanel.__init__(self, parent, style=wx.RAISED_BORDER, 
123                               *args, **kwds)
124        #kwds['style'] = wx.SUNKEN_BORDER
125        PanelBase.__init__(self)
126        #Font size
127        self.SetWindowVariant(variant=FONT_VARIANT)
128        self.SetupScrolling()
129        #thread to read data
130        self.reader = None
131        self.ext = None
132        self.id = 'Generic Scattering'
133        self.file_name = ''
134        self.time_text = None
135        self.orient_combo = None
136        self.omfreader = sans_gen.OMFReader()
137        self.sldreader = sans_gen.SLDReader()
138        self.pdbreader = sans_gen.PDBReader()
139        self.model = sans_gen.GenSAS()
140        self.param_dic = self.model.params
141        self.parameters = []
142        self.data = None
143        self.scale2d = None
144        self.is_avg = False
145        self.plot_frame = None
146        self.qmax_x = _QMAX_DEFAULT
147        self.npts_x = _NPTS_DEFAULT
148        self.sld_data = None
149        self.graph_num = 1
150        self.default_shape = 'rectangular'
151        # Object that receive status event
152        self.parent = parent
153        self._do_layout()
154        self._create_default_sld_data()
155        self._create_default_2d_data()
156        wx.CallAfter(self._set_sld_data_helper)
157       
158    def _define_structure(self):
159        """
160            Define the main sizers building to build this application.
161        """
162        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
163        self.box_source = wx.StaticBox(self, -1, str("SLD Data File"))
164        self.box_parameters = wx.StaticBox(self, -1, str("Input Parameters"))
165        self.box_qrange = wx.StaticBox(self, -1, str("Q Range"))
166        self.boxsizer_source = wx.StaticBoxSizer(self.box_source,
167                                                    wx.VERTICAL)
168        self.boxsizer_parameters = wx.StaticBoxSizer(self.box_parameters,
169                                                    wx.VERTICAL)
170        self.boxsizer_qrange = wx.StaticBoxSizer(self.box_qrange,
171                                                    wx.VERTICAL)
172        self.data_name_sizer = wx.BoxSizer(wx.HORIZONTAL)
173        self.param_sizer = wx.BoxSizer(wx.HORIZONTAL)
174        self.shape_sizer = wx.BoxSizer(wx.HORIZONTAL)
175        self.hint_sizer = wx.BoxSizer(wx.HORIZONTAL)
176        self.qrange_sizer = wx.BoxSizer(wx.HORIZONTAL)
177        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
178       
179    def _layout_data_name(self):
180        """
181            Fill the sizer containing data's name
182        """
183        data_name_txt = wx.StaticText(self, -1, 'Data: ')
184        self.data_name_tcl = OutputTextCtrl(self, -1, 
185                                            size=(_BOX_WIDTH * 4, -1))
186        data_hint = "Loaded data"
187        self.data_name_tcl.SetToolTipString(data_hint)
188        #control that triggers importing data
189        id = wx.NewId()
190        self.browse_button = wx.Button(self, id, "Load")
191        hint_on_browse = "Click on this button to load a data in this panel."
192        #self.browse_button.SetToolTipString(hint_on_browse)
193        self.Bind(wx.EVT_BUTTON, self.on_load_data, id=id)
194        self.data_name_sizer.AddMany([(data_name_txt, 0, wx.LEFT, 15),
195                                      (self.data_name_tcl, 0, wx.LEFT, 10),
196                                      (self.browse_button, 0, wx.LEFT, 10)])
197    def _layout_param_size(self):
198        """
199            Fill the sizer containing slit size information
200        """
201        self.parameters = []
202        sizer = wx.GridBagSizer(3, 6)
203        model = self.model
204        details = self.model.details
205        params = self.model.params
206        ix = 0
207        iy = 0
208        param_title = wx.StaticText(self, -1, 'Parameter')
209        sizer.Add(param_title, (iy, ix), (1, 1), \
210                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
211        ix += 1
212        value_title = wx.StaticText(self, -1, 'Value')
213        sizer.Add(value_title, (iy, ix), (1, 1), \
214                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
215        ix += 1
216        unit_title = wx.StaticText(self, -1, 'Unit')
217        sizer.Add(unit_title, (iy, ix), (1, 1), \
218                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
219        key_list = params.keys()
220        key_list.sort()
221        for param in key_list:
222            iy += 1
223            ix = 0
224            p_name = wx.StaticText(self, -1, param)
225            sizer.Add(p_name, (iy, ix), (1, 1), \
226                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
227            ## add parameter value
228            ix += 1
229            value = model.getParam(param)
230            ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH * 2, 20),
231                                style=wx.TE_PROCESS_ENTER)
232            #ctl.SetToolTipString(\
233            #            "Hit 'Enter' after typing to update the plot.")
234            ctl.SetValue(format_number(value, True))
235            sizer.Add(ctl, (iy, ix), (1, 1), wx.EXPAND)
236            ## add unit
237            ix += 1
238            unit = wx.StaticText(self, -1, details[param][0])
239            sizer.Add(unit, (iy, ix), (1, 1), \
240                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
241            self.parameters.append([p_name, ctl, unit])
242                                 
243        self.param_sizer.Add(sizer, 0, wx.LEFT, 10)
244   
245    def _layout_hint(self):
246        """
247            Fill the sizer containing hint
248        """
249        hint_msg = "We support omf, sld or pdb data files only."
250        hint_msg +=  "         "
251        if FONT_VARIANT < 1:
252            hint_msg +=  "Very "
253        hint_msg += "SLOW drawing -->"
254        hint_txt = wx.StaticText(self, -1, hint_msg)
255       
256        id = wx.NewId()
257        self.draw_button = wx.Button(self, id, "Arrow Draw")
258        hint_on_draw = "Draw with arrows. Caution: it is a very slow drawing."
259        self.draw_button.SetToolTipString(hint_on_draw)
260        self.draw_button.Bind(wx.EVT_BUTTON, self.sld_draw, id=id)
261       
262        self.draw_button.Enable(False)
263        self.hint_sizer.AddMany([(hint_txt, 0, wx.LEFT, 15),
264                                 (self.draw_button, 0, wx.LEFT, 7)])
265   
266    def _layout_shape(self):
267        """
268        Fill the shape sizer
269        """
270        label_txt = wx.StaticText(self, -1, "Shape:")
271        self.shape_combo = self._fill_shape_combo()
272        self.shape_sizer.AddMany([(label_txt, 0, wx.LEFT, 15),
273                                (self.shape_combo, 0, wx.LEFT, 5)])
274   
275    def _fill_shape_combo(self):
276        """
277        Fill up the shape combo box
278        """
279        shape_combo = wx.ComboBox(self, -1, size=(150, -1), 
280                                      style=wx.CB_READONLY) 
281        shape_combo.Append('Rectangular')
282        shape_combo.Append('Ellipsoid')
283        shape_combo.Bind(wx.EVT_COMBOBOX, self._on_shape_select)
284        shape_combo.SetSelection(0)
285        return shape_combo
286   
287    def _on_shape_select(self, event):
288        """
289        On selecting a shape
290        """
291        event.Skip()
292        label = event.GetEventObject().GetValue().lower() 
293        self.default_shape = label
294        self.parent.set_omfpanel_default_shap(self.default_shape)
295        self.parent.set_omfpanel_npts()
296       
297    def _fill_orient_combo(self):
298        """
299        Fill up the orientation combo box: used only for atomic structure
300        """
301        orient_combo = wx.ComboBox(self, -1, size=(150, -1), 
302                                      style=wx.CB_READONLY) 
303        orient_combo.Append('Fixed orientation')
304        orient_combo.Append('Debye full avg.')
305        #orient_combo.Append('Debye sph. sym.')
306       
307        orient_combo.Bind(wx.EVT_COMBOBOX, self._on_orient_select)
308        orient_combo.SetSelection(0)
309        return orient_combo
310   
311    def _on_orient_select(self, event):
312        """
313        On selecting a orientation
314        """
315        event.Skip()
316        cb = event.GetEventObject()
317        if cb.GetCurrentSelection() == 2:
318            self.is_avg = None
319        else:
320            is_avg = cb.GetCurrentSelection() == 1
321            self.is_avg = is_avg
322        self.model.set_is_avg(self.is_avg)
323        self.set_est_time()   
324           
325    def _layout_qrange(self):
326        """
327        Fill the sizer containing qrange
328        """
329        sizer = wx.GridBagSizer(2, 3)
330        ix = 0
331        iy = 0
332        #key_list.sort()
333        name = wx.StaticText(self, -1, 'No. of Qx (Qy) bins: ')
334        sizer.Add(name, (iy, ix), (1, 1), \
335                        wx.EXPAND | wx.ADJUST_MINSIZE, 0)
336        ## add parameter value
337        ix += 1
338        self.npt_ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH * 1.5, 20),
339                            style=wx.TE_PROCESS_ENTER)
340        self.npt_ctl.Bind(wx.EVT_TEXT, self._onparamEnter)
341        self.npt_ctl.SetValue(format_number(self.npts_x, True))
342        sizer.Add(self.npt_ctl, (iy, ix), (1, 1), wx.EXPAND)
343        ## add unit
344        ix += 1
345        unit = wx.StaticText(self, -1, '')
346        sizer.Add(unit, (iy, ix), (1, 1), \
347                        wx.EXPAND | wx.ADJUST_MINSIZE, 0)
348        iy += 1
349        ix = 0
350        name = wx.StaticText(self, -1, 'Qx (Qy) Max: ')
351        sizer.Add(name, (iy, ix), (1, 1), \
352                        wx.EXPAND | wx.ADJUST_MINSIZE, 0)
353        ## add parameter value
354        ix += 1
355        self.qmax_ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH * 1.5, 20),
356                            style=wx.TE_PROCESS_ENTER)
357        self.qmax_ctl.Bind(wx.EVT_TEXT, self._onparamEnter )
358        self.qmax_ctl.SetValue(format_number(self.qmax_x, True))
359        sizer.Add(self.qmax_ctl, (iy, ix), (1, 1), wx.EXPAND)
360        ## add unit
361        ix += 1
362        unit = wx.StaticText(self, -1, '[1/A]')
363        sizer.Add(unit, (iy, ix), (1, 1), \
364                        wx.EXPAND | wx.ADJUST_MINSIZE, 0)
365        self.qrange_sizer.Add(sizer, 0, wx.LEFT, 10)
366   
367    def _layout_button(self): 
368        """
369            Do the layout for the button widgets
370        """ 
371        self.est_time = '*Estimated Computation time : %s'
372        self.time_text = wx.StaticText(self, -1, self.est_time% str('2 sec') )
373        self.orient_combo = self._fill_orient_combo()
374        self.orient_combo.Show(False)
375        self.bt_compute = wx.Button(self, wx.NewId(),'Compute')
376        self.bt_compute.Bind(wx.EVT_BUTTON, self.on_compute)
377        self.bt_compute.SetToolTipString("Compute 2D Scattering Pattern.")
378        self.button_sizer.AddMany([(self.time_text , 0, wx.LEFT, 20),
379                                   (self.orient_combo , 0, wx.LEFT, 40),
380                                   (self.bt_compute, 0, wx.LEFT, 20)])
381       
382    def estimate_ctime(self):
383        """
384        Calculation time estimation
385        """
386        n_qbins = float(self.npt_ctl.GetValue())
387        n_qbins *= n_qbins
388        n_pixs = float(self.parent.get_npix())
389        if self.is_avg:
390            n_pixs *= (n_pixs / 200)
391        x_in = n_qbins * n_pixs / 100000
392        # magic equation: not very accurate
393        etime = 1.0 + 0.085973 * x_in
394        return int(etime)
395       
396    def set_est_time(self):
397        """
398        Set text for est. computation time
399        """
400        unit = 'sec'
401        if self.time_text != None:
402            self.time_text.SetForegroundColour('black')
403            etime = self.estimate_ctime()
404            if etime > 60:
405                etime /= 60
406                unit = 'min'
407                self.time_text.SetForegroundColour('red')
408            time_str = str(etime) + ' ' + unit
409            self.time_text.SetLabel(self.est_time% time_str)
410       
411    def _do_layout(self):
412        """
413        Draw window content
414        """
415        self._define_structure()
416        self._layout_data_name()
417        self._layout_param_size()
418        self._layout_qrange()
419        self._layout_hint()
420        self._layout_shape()
421        self._layout_button()
422        self.boxsizer_source.AddMany([(self.data_name_sizer, 0,
423                                        wx.EXPAND|wx.TOP|wx.BOTTOM, 5),
424                                      (self.hint_sizer, 0,
425                                        wx.EXPAND|wx.TOP|wx.BOTTOM, 5),
426                                      (self.shape_sizer, 0, 
427                                        wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
428        self.boxsizer_parameters.AddMany([(self.param_sizer, 0,
429                                     wx.EXPAND|wx.TOP|wx.BOTTOM, 5),])
430        self.boxsizer_qrange.AddMany([(self.qrange_sizer, 0,
431                                     wx.EXPAND|wx.TOP|wx.BOTTOM, 5),])
432        self.main_sizer.AddMany([(self.boxsizer_source, 0, 
433                                  wx.EXPAND|wx.ALL, 10),
434                                 (self.boxsizer_parameters, 0, 
435                                  wx.EXPAND|wx.ALL, 10),
436                                 (self.boxsizer_qrange, 0, 
437                                  wx.EXPAND|wx.ALL, 10),
438                                 (self.button_sizer, 0,
439                                  wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
440        self.SetSizer(self.main_sizer)
441        self.SetAutoLayout(True)
442   
443    def _create_default_sld_data(self):
444        """
445        Making default sld-data
446        """
447        sld_n_default = 6.97e-06
448        omfdata = sans_gen.OMFData()
449        omf2sld = sans_gen.OMF2SLD()
450        omf2sld.set_data(omfdata, self.default_shape)
451        self.sld_data = omf2sld.output
452        self.sld_data.is_data = False
453        self.sld_data.filename = "Default SLD Profile"
454        self.sld_data.set_sldn(sld_n_default)
455        self.data_name_tcl.SetValue(self.sld_data.filename)       
456               
457    def choose_data_file(self, location=None):
458        """
459        Choosing a dtata file
460        """
461        path = None
462        filename = ''
463        if location == None:
464            location = os.getcwd()
465       
466        omf_type = self.omfreader.type
467        sld_type = self.sldreader.type
468        pdb_type = self.pdbreader.type
469        wildcard = []
470        for type in sld_type:
471            wildcard.append(type)
472        for type in omf_type:
473            wildcard.append(type)
474        for type in pdb_type:
475            wildcard.append(type)
476        wildcard = '|'.join(wildcard)
477        dlg = wx.FileDialog(self, "Choose a file", location,
478                            "", wildcard, wx.OPEN)
479        if dlg.ShowModal() == wx.ID_OK:
480            path = dlg.GetPath()
481            filename = os.path.basename(path)
482        dlg.Destroy() 
483        return path
484       
485    def on_load_data(self, event):
486        """
487        Open a file dialog to allow the user to select a given file.
488        The user is only allow to load file with extension .omf, .txt, .sld.
489        Display the slit size corresponding to the loaded data.
490        """
491        location = self.parent.get_path()
492        path = self.choose_data_file(location=location)
493        if path is None:
494            return 
495       
496        self.shape_sizer.ShowItems(False)
497        self.default_shape = 'rectangular'
498        self.parent.set_omfpanel_default_shap(self.default_shape)
499       
500        self.parent.set_file_location(os.path.dirname(path))
501        try:
502            #Load data
503            self.ext = os.path.splitext(path)[-1]
504            if self.ext in self.omfreader.ext:
505                loader = self.omfreader
506            elif self.ext in self.sldreader.ext:
507                loader = self.sldreader
508            elif self.ext in self.pdbreader.ext:
509                loader = self.pdbreader
510            else:
511                loader = None
512            if self.reader is not None and self.reader.isrunning():
513                self.reader.stop()
514            self.browse_button.Enable(False)
515            self.browse_button.SetLabel("Loading...")
516            if self.parent.parent is not None:
517                wx.PostEvent(self.parent.parent, 
518                                StatusEvent(status="Loading...",
519                                type="progress"))
520            self.reader = GenReader(path=path, loader=loader,
521                                    completefn=self.complete_loading,
522                                    updatefn=self.load_update)
523            self.reader.queue()
524            #self.load_update()
525        except:
526            self.ext = None
527            if self.parent.parent is None:
528                return 
529            msg = "Generic SANS Calculator: %s" % (sys.exc_value)
530            wx.PostEvent(self.parent.parent,
531                          StatusEvent(status=msg, type='stop'))
532            self.SetFocus()
533            return 
534       
535    def load_update(self):
536        """
537        print update on the status bar
538        """       
539        if self.parent.parent is None:
540                return 
541        if self.reader.isrunning():
542            type = "progress"
543        else:
544            type = "stop"
545        wx.PostEvent(self.parent.parent, StatusEvent(status="",
546                                                  type=type))
547           
548    def complete_loading(self, data=None, filename=''):
549        """
550        Complete the loading
551        """
552        #compute the slit size
553        self.browse_button.Enable(True)
554        self.browse_button.SetLabel('Load')
555        try:
556            is_pdbdata = False
557            filename = data.filename
558            self.data_name_tcl.SetValue(str(filename))
559            self.file_name = filename.split('.')[0]
560            self.orient_combo.SetSelection(0)
561            self.is_avg = False
562            if self.ext in self.omfreader.ext:
563                gen = sans_gen.OMF2SLD()
564                gen.set_data(data)
565                #omf_data = data
566                self.sld_data = gen.get_magsld()
567            elif self.ext in self.sldreader.ext:
568                self.sld_data = data
569            elif self.ext in self.pdbreader.ext:
570                self.sld_data = data
571                is_pdbdata = True
572                #omf_data = None
573            else:
574                raise
575            self.orient_combo.Show(is_pdbdata)
576            self.button_sizer.Layout()
577            self._set_sld_data_helper(True)
578        except:
579            if self.parent.parent is None:
580                raise
581            msg = "Loading Error: This file format is not supported "
582            msg += "for GenSANS." 
583            wx.PostEvent(self.parent.parent,
584                          StatusEvent(status=msg, type='stop', info='Error'))
585            self.SetFocus()
586            return 
587        if self.parent.parent is None:
588            return 
589       
590        msg = "Load Complete"
591        wx.PostEvent(self.parent.parent, StatusEvent(status=msg, type='stop'))
592        self.SetFocus()
593       
594    def _set_sld_data_helper(self, is_draw=False):
595        """
596        Set sld data helper
597        """
598        #is_avg = self.orient_combo.GetCurrentSelection() == 1
599        self.model.set_is_avg(self.is_avg)
600        self.model.set_sld_data(self.sld_data)
601       
602        self.draw_button.Enable(self.sld_data!=None)
603        wx.CallAfter(self.parent.set_sld_data, self.sld_data)
604        self._update_model_params()
605        if is_draw:
606            wx.CallAfter(self.sld_draw, None, False)
607   
608    def _update_model_params(self):
609        """
610        Update the model parameter values
611        """
612        for list in self.parameters:
613            param_name = list[0].GetLabelText()
614            val = str(self.model.params[param_name])
615            list[1].SetValue(val)
616   
617    def set_volume_ctl_val(self, val):
618        """
619        Set volume txtctrl value
620        """
621        for list in self.parameters:
622            param_name = list[0].GetLabelText()
623            if param_name.lower() == 'total_volume':
624                list[1].SetValue(val)
625                list[1].Refresh()
626                break
627                           
628    def _onparamEnter(self, event):
629        """
630        On param enter
631        """
632        try:
633            item = event.GetEventObject()
634            self._check_value()
635            item.Refresh()
636        except:
637            pass
638   
639    def sld_draw(self, event=None, has_arrow=True):
640        """
641        Draw 3D sld profile
642        """
643        flag = self.parent.check_omfpanel_inputs()
644        if not flag:
645            infor = 'Error'
646            msg = 'Error: Wrong inputs in the SLD info panel.'
647            # inform msg to wx
648            wx.PostEvent(self.parent.parent,
649                    StatusEvent(status=msg, info=infor))
650            self.SetFocus()
651            return
652
653        self.sld_data = self.parent.get_sld_from_omf()
654        output = self.sld_data 
655        #frame_size = wx.Size(470, 470)   
656        self.plot_frame = PlotFrame(self, -1, 'testView')
657        frame = self.plot_frame
658        frame.Show(False)
659        add_icon(self.parent, frame)
660        panel = frame.plotpanel   
661        try:
662            # mpl >= 1.0.0
663            ax = panel.figure.gca(projection='3d')
664        except:
665            # mpl < 1.0.0
666            try:
667                from mpl_toolkits.mplot3d import Axes3D
668                ax = Axes3D(panel.figure)
669            except:
670                logging.error("PlotPanel could not import Axes3D")
671                raise
672        panel.dimension = 3   
673        graph_title = self._sld_plot_helper(ax, output, has_arrow)
674        # Use y, z axes (in mpl 3d) as z, y axes
675        # that consistent with our SANS detector coords.
676        ax.set_xlabel('x ($\A%s$)'% output.pos_unit)
677        ax.set_ylabel('z ($\A%s$)'% output.pos_unit)
678        ax.set_zlabel('y ($\A%s$)'% output.pos_unit)
679        panel.subplot.figure.subplots_adjust(left=0.05, right=0.95, 
680                                             bottom=0.05, top=0.96)
681        if output.pix_type == 'atom':
682            ax.legend(loc='upper left', prop={'size':10})
683        num_graph = str(self.graph_num)
684        frame.SetTitle('Graph %s: %s'% (num_graph, graph_title))       
685        wx.CallAfter(frame.Show, True)
686        self.graph_num += 1
687
688    def _sld_plot_helper(self, ax, output, has_arrow=False):
689        """
690        Actual plot definition happens here
691        :Param ax: axis3d
692        :Param output: sld_data [MagSLD]
693        :Param has_arrow: whether or not draws M vector [bool]
694        """
695        # Set the locals
696        color_dic = {'H':'blue', 'D':'purple', 'N': 'orange', 
697                     'O':'red', 'C':'green', 'P':'cyan', 'Other':'k'}
698        marker = ','
699        m_size = 2
700        graph_title = self.file_name
701        graph_title += "   3D SLD Profile "
702        pos_x = output.pos_x
703        pos_y = output.pos_y
704        pos_z = output.pos_z
705        sld_mx = output.sld_mx
706        sld_my = output.sld_my
707        sld_mz = output.sld_mz
708        pix_symbol = output.pix_symbol
709        if output.pix_type == 'atom':
710            marker = 'o'
711            m_size = 3.5
712        sld_tot = (numpy.fabs(sld_mx) + numpy.fabs(sld_my) + \
713                   numpy.fabs(sld_mz) + numpy.fabs(output.sld_n))
714        is_nonzero = sld_tot > 0.0 
715        is_zero = sld_tot == 0.0   
716        # I. Plot null points
717        if is_zero.any():
718            ax.plot(pos_x[is_zero], pos_z[is_zero], pos_y[is_zero], marker, 
719                    c="y", alpha=0.5, markeredgecolor='y', markersize=m_size) 
720            pos_x = pos_x[is_nonzero]
721            pos_y = pos_y[is_nonzero]
722            pos_z = pos_z[is_nonzero]
723            sld_mx = sld_mx[is_nonzero]
724            sld_my = sld_my[is_nonzero]
725            sld_mz = sld_mz[is_nonzero]
726            pix_symbol = output.pix_symbol[is_nonzero]
727        # II. Plot selective points in color
728        other_color = numpy.ones(len(pix_symbol), dtype='bool')
729        for key in color_dic.keys():
730            chosen_color = pix_symbol == key
731            if numpy.any(chosen_color):
732                other_color = other_color  & (chosen_color != True)
733                color = color_dic[key]
734                ax.plot(pos_x[chosen_color], pos_z[chosen_color], 
735                        pos_y[chosen_color], marker, c=color, alpha=0.5, 
736                        markeredgecolor=color, markersize=m_size, label=key) 
737        # III. Plot All others       
738        if numpy.any(other_color):
739            a_name = ''
740            if output.pix_type == 'atom':
741                # Get atom names not in the list
742                a_names = [symb  for symb in pix_symbol \
743                           if symb not in color_dic.keys()]
744                a_name = a_names[0]
745                for name in a_names:
746                    new_name = ", " + name
747                    if a_name.count(name) == 0:
748                        a_name += new_name
749            # plot in black
750            ax.plot(pos_x[other_color], pos_z[other_color], pos_y[other_color], 
751                    marker, c="k", alpha=0.5, markeredgecolor="k", 
752                    markersize=m_size, label=a_name) 
753        # IV. Draws atomic bond with grey lines if any
754        if output.has_conect:
755            for ind in range(len(output.line_x)):
756                ax.plot(output.line_x[ind], output.line_z[ind], 
757                        output.line_y[ind], '-', lw=0.6, c="grey", alpha=0.3) 
758        # V. Draws magnetic vectors
759        if has_arrow and len(pos_x) > 0:     
760            graph_title += " - Magnetic Vector as Arrow -" 
761            panel = self.plot_frame.plotpanel
762            def _draw_arrow(input=None, update=None):
763                """
764                draw magnetic vectors w/arrow
765                """
766                max_mx = max(numpy.fabs(sld_mx))
767                max_my = max(numpy.fabs(sld_my))
768                max_mz = max(numpy.fabs(sld_mz))
769                max_m = max(max_mx, max_my, max_mz)
770                try:
771                    max_step = max(output.xstepsize, output.ystepsize, 
772                                   output.zstepsize)
773                except:
774                    max_step = 0
775                if max_step <= 0:
776                    max_step = 5
777                try:
778                    if max_m != 0:
779                        unit_x2 = sld_mx / max_m
780                        unit_y2 = sld_my / max_m
781                        unit_z2 = sld_mz / max_m
782                        # 0.8 is for avoiding the color becomes white=(1,1,1))
783                        color_x = numpy.fabs(unit_x2 * 0.8)
784                        color_y = numpy.fabs(unit_y2 * 0.8)
785                        color_z = numpy.fabs(unit_z2 * 0.8)
786                        x2 = pos_x + unit_x2 * max_step
787                        y2 = pos_y + unit_y2 * max_step
788                        z2 = pos_z + unit_z2 * max_step
789                        x_arrow = numpy.column_stack((pos_x, x2))
790                        y_arrow = numpy.column_stack((pos_y, y2))
791                        z_arrow = numpy.column_stack((pos_z, z2))
792                        colors = numpy.column_stack((color_x, color_y, color_z))
793                        arrows = Arrow3D(panel, x_arrow, z_arrow, y_arrow, 
794                                        colors, mutation_scale=10, lw=1, 
795                                        arrowstyle="->", alpha = 0.5)
796                        ax.add_artist(arrows) 
797                except:
798                    pass 
799                msg = "Arrow Drawing completed.\n"
800                status_type = 'stop'
801                self._status_info(msg, status_type) 
802            msg = "Arrow Drawing is in progress..."
803            status_type = 'progress'
804            self._status_info(msg, status_type) 
805            draw_out = CalcGen(input=ax,
806                             completefn=_draw_arrow, updatefn=self._update)
807            draw_out.queue()
808        return graph_title
809 
810    def set_input_params(self):
811        """
812        Set model parameters
813        """
814        for list in self.parameters:
815            param_name = list[0].GetLabelText()
816            param_value = float(list[1].GetValue())
817            self.model.setParam(param_name, param_value)
818           
819    def on_compute(self, event):
820        """
821        Compute I(qx, qy)
822        """
823        flag = self.parent.check_omfpanel_inputs()
824        if not flag and self.parent.parent != None:
825            infor = 'Error'
826            msg = 'Error: Wrong inputs in the SLD info panel.'
827            # inform msg to wx
828            wx.PostEvent(self.parent.parent,
829                    StatusEvent(status=msg, info=infor))
830            self.SetFocus()
831            return
832        self.sld_data = self.parent.get_sld_from_omf()
833        if self.sld_data == None:
834            if self.parent.parent != None:
835                infor = 'Error'
836                msg = 'Error: No data has been selected.'
837                # inform msg to wx
838                wx.PostEvent(self.parent.parent,
839                        StatusEvent(status=msg, info=infor))
840                self.SetFocus()
841            return
842        flag = self._check_value()
843        if not flag:
844            _set_error(self, None, True)
845            return
846        try:
847            self.model.set_sld_data(self.sld_data)
848            self.set_input_params()
849            if self.is_avg or self.is_avg == None:
850                self._create_default_1d_data()
851                i_out = numpy.zeros(len(self.data.y))
852                inputs = [self.data.x, [], i_out]
853            else:
854                self._create_default_2d_data()
855                i_out = numpy.zeros(len(self.data.data))
856                inputs=[self.data.qx_data, self.data.qy_data, i_out]
857               
858            msg = "Computation is in progress..."
859            status_type = 'progress'
860            self._status_info(msg, status_type)
861            cal_out = CalcGen(input=inputs, 
862                              completefn=self.complete, 
863                              updatefn=self._update)
864            cal_out.queue()             
865           
866        except:
867            msg = "%s."% sys.exc_value
868            status_type = 'stop'
869            self._status_info(msg, status_type)
870            wx.PostEvent(self.parent.parent,
871                        StatusEvent(status=msg, info='Error'))
872            self.SetFocus()
873
874    def _check_value(self):
875        """
876        Check input values if float
877        """
878        flag = True
879        self.npt_ctl.SetBackgroundColour("white")
880        self.qmax_ctl.SetBackgroundColour("white")
881        try:
882            npt_val = float(self.npt_ctl.GetValue()) 
883            if npt_val < 2 or npt_val > 1000:
884                raise
885            self.npt_ctl.SetValue(str(int(npt_val)))
886            self.set_est_time()
887        except:
888            flag =  _set_error(self, self.npt_ctl)
889        try:
890            qmax_val = float(self.qmax_ctl.GetValue()) 
891            if qmax_val <= 0 or qmax_val > 1000:
892                raise
893        except:
894            flag = _set_error(self, self.qmax_ctl)       
895        for list in self.parameters:
896            list[1].SetBackgroundColour("white")
897            param_name = list[0].GetLabelText()
898            try: 
899                param_val = float(list[1].GetValue())
900                if param_name.count('frac') > 0:
901                    if param_val < 0 or param_val > 1:
902                       raise
903            except:
904                flag = _set_error(self, list[1])
905        return flag
906                   
907    def _status_info(self, msg = '', type = "update"):
908        """
909        Status msg
910        """
911        if type == "stop":
912            label = "Compute"
913            able = True
914        else:   
915            label = "Wait..."
916            able = False
917        self.bt_compute.Enable(able)
918        self.bt_compute.SetLabel(label)
919        self.bt_compute.SetToolTipString(label)
920        if self.parent.parent != None:
921            wx.PostEvent(self.parent.parent, 
922                             StatusEvent(status = msg, type = type )) 
923
924    def _update(self, time=None):
925        """
926        Update the progress bar
927        """
928        if self.parent.parent == None:
929            return
930        type = "progress"
931        msg = "Please wait. Computing... (Note: Window may look frozen.)"
932        wx.PostEvent(self.parent.parent, StatusEvent(status=msg,
933                                                  type=type))
934                               
935    def complete(self, input, update=None):   
936        """
937        Gen compute complete function
938        :Param input: input list [qx_data, qy_data, i_out]
939        """
940        out = numpy.empty(0)
941        #s = time.time()
942        for ind in range(len(input[0])):
943            if self.is_avg:
944                if ind % 1 == 0 and update != None:
945                    update()
946                    time.sleep(0.1)
947                inputi = [input[0][ind:ind+1], [], input[2][ind:ind+1]]
948                outi = self.model.run(inputi)
949                out = numpy.append(out, outi)
950            else:
951                if ind % 50 == 0  and update != None:
952                    update()
953                    time.sleep(0.001)
954                inputi = [input[0][ind:ind+1], input[1][ind:ind+1], 
955                          input[2][ind:ind+1]]
956                outi = self.model.runXY(inputi)
957                out = numpy.append(out, outi)
958        #print time.time() - s
959        if self.is_avg or self.is_avg == None:
960            self._draw1D(out)
961        else:
962            #out = self.model.runXY(input)
963            self._draw2D(out)
964           
965        msg = "Gen computation completed.\n"
966        status_type = 'stop'
967        self._status_info(msg, status_type)
968               
969    def _create_default_2d_data(self):
970        """
971        Create 2D data by default
972        Only when the page is on theory mode.
973        :warning: This data is never plotted.
974        """
975        self.qmax_x = float(self.qmax_ctl.GetValue())
976        self.npts_x = int(float(self.npt_ctl.GetValue()))
977        self.data = Data2D()
978        qmax = self.qmax_x #/ numpy.sqrt(2)
979        self.data.xaxis('\\rm{Q_{x}}', '\AA^{-1}')
980        self.data.yaxis('\\rm{Q_{y}}', '\AA^{-1}')
981        self.data.is_data = False
982        self.data.id = str(self.uid) + " GenData"
983        self.data.group_id = str(self.uid) + " Model2D"
984        ## Default values
985        self.data.detector.append(Detector())
986        index = len(self.data.detector) - 1
987        self.data.detector[index].distance = 8000   # mm
988        self.data.source.wavelength = 6             # A
989        self.data.detector[index].pixel_size.x = 5  # mm
990        self.data.detector[index].pixel_size.y = 5  # mm
991        self.data.detector[index].beam_center.x = qmax
992        self.data.detector[index].beam_center.y = qmax
993        xmax = qmax
994        xmin = -qmax
995        ymax = qmax
996        ymin = -qmax
997        qstep = self.npts_x
998
999        x = numpy.linspace(start=xmin, stop=xmax, num=qstep, endpoint=True)
1000        y = numpy.linspace(start=ymin, stop=ymax, num=qstep, endpoint=True)
1001        ## use data info instead
1002        new_x = numpy.tile(x, (len(y), 1))
1003        new_y = numpy.tile(y, (len(x), 1))
1004        new_y = new_y.swapaxes(0, 1)
1005        # all data reuire now in 1d array
1006        qx_data = new_x.flatten()
1007        qy_data = new_y.flatten()
1008        q_data = numpy.sqrt(qx_data * qx_data + qy_data * qy_data)
1009        # set all True (standing for unmasked) as default
1010        mask = numpy.ones(len(qx_data), dtype=bool)
1011        # store x and y bin centers in q space
1012        x_bins = x
1013        y_bins = y
1014        self.data.source = Source()
1015        self.data.data = numpy.ones(len(mask))
1016        self.data.err_data = numpy.ones(len(mask))
1017        self.data.qx_data = qx_data
1018        self.data.qy_data = qy_data
1019        self.data.q_data = q_data
1020        self.data.mask = mask
1021        self.data.x_bins = x_bins
1022        self.data.y_bins = y_bins
1023        # max and min taking account of the bin sizes
1024        self.data.xmin = xmin
1025        self.data.xmax = xmax
1026        self.data.ymin = ymin
1027        self.data.ymax = ymax
1028
1029    def _create_default_1d_data(self):
1030        """
1031        Create 2D data by default
1032        Only when the page is on theory mode.
1033        :warning: This data is never plotted.
1034                    residuals.x = data_copy.x[index]
1035            residuals.dy = numpy.ones(len(residuals.y))
1036            residuals.dx = None
1037            residuals.dxl = None
1038            residuals.dxw = None
1039        """
1040        self.qmax_x = float(self.qmax_ctl.GetValue())
1041        self.npts_x = int(float(self.npt_ctl.GetValue()))
1042        qmax = self.qmax_x #/ numpy.sqrt(2)
1043        ## Default values
1044        xmax = qmax
1045        xmin = qmax * _Q1D_MIN
1046        qstep = self.npts_x
1047        x = numpy.linspace(start=xmin, stop=xmax, num=qstep, endpoint=True)
1048        # store x and y bin centers in q space
1049        #self.data.source = Source()
1050        y = numpy.ones(len(x))
1051        dy = numpy.zeros(len(x))
1052        dx = numpy.zeros(len(x))
1053        self.data = Data1D(x=x, y=y)
1054        self.data.dx = dx
1055        self.data.dy = dy
1056
1057    def _draw1D(self, y_out):
1058        """
1059        Complete get the result of modelthread and create model 2D
1060        that can be plot.
1061        """
1062        page_id = self.id
1063        data = self.data
1064       
1065        model = self.model
1066        state = None
1067       
1068        new_plot = Data1D(x=data.x, y=y_out)
1069        new_plot.dx = data.dx
1070        new_plot.dy = data.dy
1071        new_plot.xaxis('\\rm{Q_{x}}', '\AA^{-1}')
1072        new_plot.yaxis('\\rm{Intensity}', 'cm^{-1}')
1073        new_plot.is_data = False
1074        new_plot.id = str(self.uid) + " GenData1D"
1075        new_plot.group_id = str(self.uid) + " Model1D"
1076        new_plot.name = model.name + '1d'
1077        new_plot.title = "Generic model1D "
1078        new_plot.id = str(page_id) + ': ' + self.file_name \
1079                        + ' #%s'% str(self.graph_num) + "_1D"
1080        new_plot.group_id = str(page_id) + " Model1D"  +\
1081                             ' #%s'% str(self.graph_num) + "_1D"
1082        new_plot.is_data = False
1083
1084        title = new_plot.title
1085        _yaxis, _yunit = new_plot.get_yaxis()
1086        _xaxis, _xunit = new_plot.get_xaxis()
1087        new_plot.xaxis(str(_xaxis), str(_xunit))
1088        new_plot.yaxis(str(_yaxis), str(_yunit))
1089       
1090        if new_plot.is_data:
1091            data_name = str(new_plot.name)
1092        else:
1093            data_name = str(model.__class__.__name__) + '1d'
1094
1095        if len(title) > 1:
1096            new_plot.title = "Gen Theory for %s "% model.name + data_name
1097        new_plot.name = new_plot.id
1098        new_plot.label = new_plot.id
1099        #theory_data = deepcopy(new_plot)
1100        if self.parent.parent != None:
1101            self.parent.parent.update_theory(data_id=new_plot.id,
1102                                           theory=new_plot,
1103                                           state=state)
1104        title = new_plot.title
1105        num_graph = str(self.graph_num)
1106        wx.CallAfter(self.parent.draw_graph, new_plot, 
1107                     title="Graph %s: "% num_graph + new_plot.id )
1108        self.graph_num += 1
1109               
1110    def _draw2D(self, image):
1111        """
1112        Complete get the result of modelthread and create model 2D
1113        that can be plot.
1114        """
1115        page_id = self.id
1116        data = self.data
1117       
1118        model = self.model
1119        qmin = 0.0
1120        state = None
1121       
1122        numpy.nan_to_num(image)
1123        new_plot = Data2D(image=image, err_image=data.err_data)
1124        new_plot.name = model.name + '2d'
1125        new_plot.title = "Generic model 2D "
1126        new_plot.id = str(page_id) + ': ' + self.file_name \
1127                        + ' #%s'% str(self.graph_num) + "_2D"
1128        new_plot.group_id = str(page_id) + " Model2D" \
1129                        + ' #%s'% str(self.graph_num) + "_2D"
1130        new_plot.detector = data.detector
1131        new_plot.source = data.source
1132        new_plot.is_data = False
1133        new_plot.qx_data = data.qx_data
1134        new_plot.qy_data = data.qy_data
1135        new_plot.q_data = data.q_data
1136        new_plot.mask = data.mask
1137        ## plot boundaries
1138        new_plot.ymin = data.ymin
1139        new_plot.ymax = data.ymax
1140        new_plot.xmin = data.xmin
1141        new_plot.xmax = data.xmax
1142        title = data.title
1143        _yaxis, _yunit = data.get_yaxis()
1144        _xaxis, _xunit = data.get_xaxis()
1145        new_plot.xaxis(str(_xaxis), str(_xunit))
1146        new_plot.yaxis(str(_yaxis), str(_yunit))
1147       
1148        new_plot.is_data = False
1149        if data.is_data:
1150            data_name = str(data.name)
1151        else:
1152            data_name = str(model.__class__.__name__) + '2d'
1153
1154        if len(title) > 1:
1155            new_plot.title = "Gen Theory for %s "% model.name + data_name
1156        new_plot.name = new_plot.id
1157        new_plot.label = new_plot.id
1158        #theory_data = deepcopy(new_plot)
1159        if self.parent.parent != None:
1160            self.parent.parent.update_theory(data_id=data.id,
1161                                           theory=new_plot,
1162                                           state=state)
1163        title = new_plot.title
1164        num_graph = str(self.graph_num)
1165        wx.CallAfter(self.parent.draw_graph, new_plot, 
1166                     title="Graph %s: "% num_graph + new_plot.id )
1167        self.graph_num += 1
1168       
1169    def set_scale2d(self, scale):
1170        """
1171        Set SLD plot scale
1172        """
1173        self.scale2d = None
1174       
1175    def on_panel_close(self, event):
1176        """
1177        On Close SLD panel
1178        """
1179        #Not implemented   
1180                 
1181class OmfPanel(ScrolledPanel, PanelBase):
1182    """
1183        Provides the sas gen calculator GUI.
1184    """
1185    ## Internal nickname for the window, used by the AUI manager
1186    window_name = "SLD Pixel Info"
1187    ## Name to appear on the window title bar
1188    window_caption = "SLD Pixel Info "
1189    ## Flag to tell the AUI manager to put this panel in the center pane
1190    CENTER_PANE = False
1191   
1192    def __init__(self, parent, *args, **kwds):
1193        ScrolledPanel.__init__(self, parent, style=wx.RAISED_BORDER, 
1194                               *args, **kwds)
1195        PanelBase.__init__(self)
1196        #Font size
1197        self.SetWindowVariant(variant=FONT_VARIANT)
1198        self.SetupScrolling() 
1199        # Object that receive status event
1200        self.parent = parent
1201        self.sld_data = sans_gen.MagSLD([0], [0], [0]) 
1202        self.sld_ctl = None
1203        self.default_shape = 'rectangular'
1204        self._do_layout()
1205       
1206    def set_slddata(self, slddata):
1207        """
1208        Set sld data related items
1209        """
1210        self.sld_data = slddata
1211        self._set_slddata_ctr_val(slddata)
1212        # Make sure that self._set_slddata_ctr_val() is finished
1213        wx.CallAfter(self._set_omfdata_ctr, slddata)
1214   
1215    def get_sld_val(self):
1216        """
1217        Set sld_n of slddata on sld input
1218        """
1219        sld_sets = {}
1220        if not self.sld_data.is_data:
1221            self._get_other_val()
1222        for list in self.slds:
1223            if list[1].IsEnabled():
1224                list[1].SetBackgroundColour("white")
1225                list[1].Refresh()
1226                try:
1227                    val = float(list[1].GetValue())
1228                    sld_sets[list[0]] = val
1229                except:
1230                    flag = _set_error(self, list[1])
1231                    if not flag:
1232                        return self.sld_data
1233            else:
1234               sld_sets[list[0]] = None
1235        for key in sld_sets.keys():
1236            key_low = key.lower()
1237            if key_low.count('mx') > 0:
1238                if sld_sets[key] == None:
1239                    sld_sets[key] = self.sld_data.sld_mx
1240                mx = sld_sets[key]
1241            elif key_low.count('my') > 0:
1242                if sld_sets[key] == None:
1243                    sld_sets[key] = self.sld_data.sld_my
1244                my = sld_sets[key]
1245            elif key_low.count('mz') > 0:
1246                if sld_sets[key] == None:
1247                    sld_sets[key] = self.sld_data.sld_mz
1248                mz = sld_sets[key]
1249            else:
1250                if sld_sets[key] != None:
1251                    self.sld_data.set_sldn(sld_sets[key])
1252        self.sld_data.set_sldms(mx, my, mz)
1253        self._set_slddata_ctr_val(self.sld_data)
1254       
1255        return self.sld_data
1256   
1257    def get_pix_volumes(self):
1258        """
1259        Get the pixel volume
1260        """
1261        vol = self.sld_data.vol_pix
1262       
1263        return vol
1264               
1265    def _get_other_val(self): 
1266        """
1267        """
1268        omfdata = sans_gen.OMFData()
1269        sets = {}
1270        try:
1271            for lst in self.stepsize:
1272                if lst[1].IsEnabled():
1273                    val = float(lst[1].GetValue())
1274                    sets[lst[0]] = val
1275                else:
1276                    sets[lst[0]] = None
1277                    return
1278            for lst in self.nodes:
1279                if lst[1].IsEnabled():
1280                    val = float(lst[1].GetValue())
1281                    sets[lst[0]] = val
1282                else:
1283                    sets[lst[0]] = None
1284                    return
1285                   
1286            for key in sets.keys():
1287                exec "omfdata.%s = sets['%s']"% (key, key)           
1288
1289            omf2sld = sans_gen.OMF2SLD()
1290            omf2sld.set_data(omfdata, self.default_shape)
1291            self.sld_data = omf2sld.output
1292            self.sld_data.is_data = False
1293            self.sld_data.filename = "Default SLD Profile"
1294        except:
1295            msg = "OMF Panel: %s"% sys.exc_value
1296            infor = 'Error'
1297            #logging.error(msg)
1298            if self.parent.parent != None:
1299                # inform msg to wx
1300                wx.PostEvent(self.parent.parent,
1301                        StatusEvent(status=msg, info=infor))
1302                self.SetFocus()
1303               
1304    def _set_slddata_ctr_val(self, slddata):
1305        """
1306        Set slddata crl
1307        """
1308        try:
1309            val = str(len(slddata.sld_n))
1310        except:
1311            val = 'Unknown'
1312        self.npix_ctl.SetValue(val)
1313       
1314    def _set_omfdata_ctr(self, omfdata):   
1315        """
1316        Set the textctr box values
1317        """
1318       
1319        if omfdata == None:
1320            self._set_none_text()
1321            return
1322        nodes_list = self._get_nodes_key_list(omfdata)
1323        step_list = self._get_step_key_list(omfdata)
1324        for ctr_list in self.nodes:
1325            for key in nodes_list.keys():
1326                if ctr_list[0] == key:
1327                    ctr_list[1].SetValue(format_number(nodes_list[key], True))
1328                    ctr_list[1].Enable(not omfdata.is_data)
1329                    break
1330        for ctr_list in self.stepsize:
1331            for key in step_list.keys():
1332                if ctr_list[0] == key:
1333                    ctr_list[1].SetValue(format_number(step_list[key], True))
1334                    ctr_list[1].Enable(not omfdata.is_data)
1335                    break   
1336               
1337    def _set_none_text(self):
1338        """
1339        Set Unknown in textctrls
1340        """
1341        val = 'Unknown'
1342        for ctr_list in self.nodes:
1343            ctr_list[1].SetValue(val)
1344        for ctr_list in self.stepsize:
1345            ctr_list[1].SetValue(val)
1346               
1347    def _define_structure(self):
1348        """
1349        Define the main sizers building to build this application.
1350        """
1351        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
1352       
1353        self.npixels_sizer = wx.BoxSizer(wx.HORIZONTAL)
1354        self.box_sld = wx.StaticBox(self, -1, 
1355                                    str("Mean SLD"))
1356        self.box_node = wx.StaticBox(self, -1, str("Nodes"))
1357        self.boxsizer_sld = wx.StaticBoxSizer(self.box_sld, wx.VERTICAL)
1358        self.box_stepsize = wx.StaticBox(self, -1, str("Step Size"))
1359        self.boxsizer_node = wx.StaticBoxSizer(self.box_node, wx.VERTICAL)
1360        self.boxsizer_stepsize = wx.StaticBoxSizer(self.box_stepsize,
1361                                                    wx.VERTICAL)
1362        self.sld_sizer = wx.BoxSizer(wx.HORIZONTAL)
1363        self.node_sizer = wx.BoxSizer(wx.HORIZONTAL)
1364        self.step_sizer = wx.BoxSizer(wx.HORIZONTAL)
1365        self.hint_sizer = wx.BoxSizer(wx.HORIZONTAL)
1366        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
1367               
1368    def _layout_npix(self):
1369        """
1370        Build No of pixels sizer
1371        """
1372        num_pix_text = wx.StaticText(self, -1, "No. of Pixels: ") 
1373        self.npix_ctl = OutputTextCtrl(self, -1, size=(_BOX_WIDTH, 20),
1374                                style=wx.TE_PROCESS_ENTER)
1375        self._set_slddata_ctr_val(self.sld_data)
1376        self._set_omfdata_ctr(self.sld_data) 
1377        self.npixels_sizer.AddMany([(num_pix_text, 0,
1378                                          wx.EXPAND|wx.LEFT|wx.TOP, 5),
1379                                     (self.npix_ctl, 0,
1380                                     wx.EXPAND|wx.TOP, 5)])
1381
1382    def _layout_slds(self):
1383        """
1384        Build nuclear sld sizer
1385        """
1386        self.slds = []
1387        omfdata = self.sld_data
1388        if omfdata == None:
1389            raise
1390        sld_key_list = self._get_slds_key_list(omfdata)
1391        # Dic is not sorted
1392        key_list = [key for key in sld_key_list.keys()]
1393        # Sort here
1394        key_list.sort()
1395        is_data = self.sld_data.is_data
1396        sizer = wx.GridBagSizer(2, 3)
1397        ix = 0
1398        iy = -1
1399        for key in key_list:
1400            value = sld_key_list[key]
1401            iy += 1
1402            ix = 0
1403            name = wx.StaticText(self, -1, key)
1404            sizer.Add(name, (iy, ix), (1, 1), \
1405                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1406            ## add parameter value
1407            ix += 1
1408            ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH, 20),
1409                                style=wx.TE_PROCESS_ENTER)
1410            ctl.SetValue(format_number(value, True))
1411            ctl.Enable(not is_data)
1412            sizer.Add(ctl, (iy, ix), (1, 1), wx.EXPAND)
1413            ## add unit
1414            ix += 1
1415            s_unit = '[' + omfdata.sld_unit + ']'
1416            unit = wx.StaticText(self, -1, s_unit)
1417            sizer.Add(unit, (iy, ix), (1, 1), \
1418                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1419            self.slds.append([key, ctl, unit])
1420        self.sld_sizer.Add(sizer, 0, wx.LEFT, 10) 
1421               
1422    def _layout_nodes(self):
1423        """
1424        Fill the sizer containing data's name
1425        """
1426        self.nodes = []
1427        omfdata = self.sld_data
1428        if omfdata == None:
1429            raise
1430        key_list = self._get_nodes_key_list(omfdata)
1431        is_data = self.sld_data.is_data
1432        sizer = wx.GridBagSizer(2, 3)
1433        ix = 0
1434        iy = -1
1435        for key, value in key_list.iteritems():
1436            iy += 1
1437            ix = 0
1438            name = wx.StaticText(self, -1, key)
1439            sizer.Add(name, (iy, ix), (1, 1), \
1440                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1441            ## add parameter value
1442            ix += 1
1443            ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH, 20),
1444                                style=wx.TE_PROCESS_ENTER)
1445            ctl.Bind(wx.EVT_TEXT, self._onparamEnter )
1446            ctl.SetValue(format_number(value, True))
1447            ctl.Enable(not is_data)
1448            sizer.Add(ctl, (iy, ix), (1, 1), wx.EXPAND)
1449            ## add unit
1450            ix += 1
1451            unit = wx.StaticText(self, -1, '')
1452            sizer.Add(unit, (iy, ix), (1, 1), \
1453                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1454            self.nodes.append([key, ctl, unit])
1455        self.node_sizer.Add(sizer, 0, wx.LEFT, 10)
1456           
1457    def _layout_stepsize(self):
1458        """
1459        Fill the sizer containing slit size information
1460        """
1461        self.stepsize = []
1462        omfdata = self.sld_data
1463        if omfdata == None:
1464            raise
1465        key_list = self._get_step_key_list(omfdata)
1466        is_data = self.sld_data.is_data
1467        sizer = wx.GridBagSizer(2, 3)
1468        ix = 0
1469        iy = -1
1470        #key_list.sort()
1471        for key, value in key_list.iteritems():
1472            iy += 1
1473            ix = 0
1474            name = wx.StaticText(self, -1, key)
1475            sizer.Add(name, (iy, ix), (1, 1), \
1476                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1477            ## add parameter value
1478            ix += 1
1479            ctl = InputTextCtrl(self, -1, size=(_BOX_WIDTH, 20),
1480                                style=wx.TE_PROCESS_ENTER)
1481            ctl.Bind(wx.EVT_TEXT, self._onstepsize )
1482            ctl.SetValue(format_number(value, True))
1483            ctl.Enable(not is_data)
1484            sizer.Add(ctl, (iy, ix), (1, 1), wx.EXPAND)
1485            ## add unit
1486            ix += 1
1487            p_unit = '[' + omfdata.pos_unit + ']'
1488            unit = wx.StaticText(self, -1, p_unit)
1489            sizer.Add(unit, (iy, ix), (1, 1), \
1490                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
1491            self.stepsize.append([key, ctl, unit])
1492        self.step_sizer.Add(sizer, 0, wx.LEFT, 10)
1493   
1494    def _layout_hint(self):
1495        """
1496        Fill the sizer containing hint
1497        """
1498        hint_msg = "Load an omf or 3d sld profile data file."
1499        self.hint_txt = wx.StaticText(self, -1, hint_msg)
1500        self.hint_sizer.AddMany([(self.hint_txt, 0, wx.LEFT, 15)])
1501   
1502    def _layout_button(self): 
1503        """
1504        Do the layout for the button widgets
1505        """ 
1506        self.bt_draw = wx.Button(self, wx.NewId(),'Draw Points')
1507        self.bt_draw.Bind(wx.EVT_BUTTON, self.on_sld_draw)
1508        self.bt_draw.SetToolTipString("Draw a scatter plot for sld profile.")
1509        self.bt_save = wx.Button(self, wx.NewId(),'Save SLD Data')
1510        self.bt_save.Bind(wx.EVT_BUTTON, self.on_save)
1511        self.bt_save.Enable(False)
1512        self.bt_save.SetToolTipString("Save SLD data.")
1513        self.button_sizer.AddMany([(self.bt_draw, 0, wx.LEFT, 10),
1514                                   (self.bt_save, 0, wx.LEFT, 10)])
1515       
1516    def _do_layout(self):
1517        """
1518        Draw window content
1519        """
1520        self._define_structure()
1521        self._layout_nodes()
1522        self._layout_stepsize()
1523        self._layout_npix()
1524        self._layout_slds()
1525        #self._layout_hint()
1526        self._layout_button()
1527        self.boxsizer_node.AddMany([(self.node_sizer, 0,
1528                                    wx.EXPAND|wx.TOP, 5),
1529                                     (self.hint_sizer, 0,
1530                                     wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
1531        self.boxsizer_stepsize.AddMany([(self.step_sizer, 0,
1532                                     wx.EXPAND|wx.TOP|wx.BOTTOM, 5),])
1533        self.boxsizer_sld.AddMany([(self.sld_sizer, 0,
1534                                     wx.EXPAND|wx.BOTTOM, 5),])
1535        self.main_sizer.AddMany([(self.npixels_sizer, 0, wx.EXPAND|wx.ALL, 10),
1536                        (self.boxsizer_sld, 0, wx.EXPAND|wx.ALL, 10),
1537                        (self.boxsizer_node, 0, wx.EXPAND|wx.ALL, 10),
1538                        (self.boxsizer_stepsize, 0, wx.EXPAND|wx.ALL, 10),
1539                        (self.button_sizer, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
1540        self.SetSizer(self.main_sizer)
1541        self.SetAutoLayout(True)
1542       
1543    def _get_nodes_key_list(self, data):
1544        """
1545        Return nodes key list
1546       
1547        :Param data: OMFData
1548        """
1549        key_list = {'xnodes' : data.xnodes, 
1550                    'ynodes' : data.ynodes,
1551                    'znodes' : data.znodes}
1552        return key_list
1553       
1554    def _get_slds_key_list(self, data):
1555        """
1556        Return nodes key list
1557       
1558        :Param data: OMFData
1559        """
1560        key_list = {'Nucl.' : data.sld_n, 
1561                    'Mx' : data.sld_mx,
1562                    'My' : data.sld_my,
1563                    'Mz' : data.sld_mz}
1564        return key_list
1565
1566    def _get_step_key_list(self, data):
1567        """
1568        Return step key list
1569       
1570        :Param data: OMFData
1571        """
1572        key_list = {'xstepsize' : data.xstepsize, 
1573                    'ystepsize' : data.ystepsize,
1574                    'zstepsize' : data.zstepsize}
1575        return key_list       
1576   
1577    def set_sld_ctr(self, sld_data):
1578        """
1579        Set sld textctrls
1580        """
1581        if sld_data == None:
1582            for ctr_list in self.slds:
1583                ctr_list[1].Enable(False)
1584                #break   
1585            return
1586       
1587        self.sld_data = sld_data
1588        sld_list = self._get_slds_key_list(sld_data)
1589        for ctr_list in self.slds:
1590            for key in sld_list.keys():
1591                if ctr_list[0] == key:
1592                    min_val = numpy.min(sld_list[key])
1593                    max_val = numpy.max(sld_list[key])
1594                    mean_val = numpy.mean(sld_list[key])
1595                    enable = (min_val == max_val) and \
1596                             sld_data.pix_type == 'pixel'
1597                    ctr_list[1].SetValue(format_number(mean_val, True))
1598                    ctr_list[1].Enable(enable)
1599                    #ctr_list[2].SetLabel("[" + sld_data.sld_unit + "]")
1600                    break   
1601
1602    def on_sld_draw(self, event):
1603        """
1604        Draw sld profile as scattered plot
1605        """
1606        self.parent.sld_draw()
1607         
1608    def on_save(self, event):
1609        """
1610        Close the window containing this panel
1611        """
1612        flag = True
1613        flag = self.check_inputs()
1614        if not flag:
1615            return
1616        self.sld_data = self.get_sld_val()
1617        self.parent.set_main_panel_sld_data(self.sld_data)
1618       
1619        reader = sans_gen.SLDReader() 
1620        extension = '*.sld'
1621        path = None
1622        data= None
1623        location = self.parent.get_path()
1624        dlg = wx.FileDialog(self, "Save sld file",
1625                            location, "sld_file",
1626                             extension, 
1627                             wx.SAVE)
1628        if dlg.ShowModal() == wx.ID_OK:
1629            path = dlg.GetPath()
1630            self.parent.set_file_location(os.path.dirname(path))
1631        else:
1632            return None
1633        dlg.Destroy()
1634        try:
1635            if path is None:
1636                return
1637           
1638            data = self.parent.get_sld_data()
1639            fName = os.path.splitext(path)[0] + '.' + extension.split('.')[-1]
1640            if data != None:
1641                try:
1642                    reader.write(fName, data)
1643                except:
1644                    raise
1645            else:
1646                msg = "%s cannot write %s\n" % ('Generic Scattering', str(path))
1647                infor = 'Error'
1648                #logging.error(msg)
1649                if self.parent.parent != None:
1650                    # inform msg to wx
1651                    wx.PostEvent(self.parent.parent,
1652                            StatusEvent(status=msg, info=infor))
1653                    self.SetFocus()
1654            return
1655        except:
1656            msg = "Error occurred while saving. "
1657            infor = 'Error'
1658            if self.parent.parent != None:
1659                # inform msg to wx
1660                wx.PostEvent(self.parent.parent,
1661                        StatusEvent(status=msg, info=infor)) 
1662                self.SetFocus()   
1663
1664    def _onparamEnter(self, event):
1665        """
1666        """
1667        flag = True
1668        if event != None:
1669            event.Skip()
1670            ctl = event.GetEventObject()
1671            ctl.SetBackgroundColour("white")
1672            #_set_error(self, ctl)
1673        try:
1674            float(ctl.GetValue())
1675        except:
1676            flag = _set_error(self, ctl)
1677        if flag:
1678            npts = 1
1679            for item in self.nodes:
1680                n_val = float(item[1].GetValue())
1681                if n_val <= 0:
1682                    item[1].SetBackgroundColour("pink")
1683                    npts = -1
1684                    break
1685                if numpy.isfinite(n_val):
1686                    npts *= int(n_val)
1687            if npts > 0:
1688                nop = self.set_npts_from_slddata()
1689                if nop == None:
1690                    nop = npts
1691                self.display_npts(nop)
1692               
1693        ctl.Refresh()
1694        return flag
1695   
1696    def _set_volume_ctr_val(self, npts):
1697        """
1698        Set total volume
1699        """
1700        total_volume = npts * self.sld_data.vol_pix[0]
1701        self.parent.set_volume_ctr_val(total_volume)
1702                   
1703    def _onstepsize(self, event):
1704        """
1705        On stepsize event
1706        """
1707        flag = True
1708        if event != None:
1709            event.Skip()
1710            ctl = event.GetEventObject()
1711            ctl.SetBackgroundColour("white")
1712
1713        if flag and not self.sld_data.is_data:#ctl.IsEnabled():
1714            s_size = 1.0
1715            try:
1716                for item in self.stepsize:
1717                    s_val = float(item[1].GetValue())
1718                    if s_val <= 0:
1719                        item[1].SetBackgroundColour("pink")
1720                        ctl.Refresh()
1721                        return
1722                    if numpy.isfinite(s_val):
1723                        s_size *= s_val
1724                self.sld_data.set_pixel_volumes(s_size)
1725                if ctl.IsEnabled():
1726                    total_volume = sum(self.sld_data.vol_pix)
1727                    self.parent.set_volume_ctr_val(total_volume)
1728            except:
1729                pass
1730        ctl.Refresh()
1731 
1732         
1733    def set_npts_from_slddata(self):
1734        """
1735        Set total n. of points form the sld data
1736        """
1737        try:
1738            sld_data = self.parent.get_sld_from_omf()
1739            #nop = (nop * numpy.pi) / 6
1740            nop = len(sld_data.sld_n)
1741        except:
1742            nop = None
1743        return nop
1744   
1745    def display_npts(self, nop):
1746        """
1747        Displays Npts ctrl
1748        """
1749        try:
1750            self.npix_ctl.SetValue(str(nop))
1751            self.npix_ctl.Refresh()
1752            self.parent.set_etime()
1753            wx.CallAfter(self._set_volume_ctr_val, nop)
1754        except:
1755            # On Init
1756            pass
1757   
1758    def check_inputs(self):
1759        """
1760        check if the inputs are valid
1761        """
1762        flag = self._check_input_helper(self.slds)
1763        if flag:
1764            flag = self._check_input_helper(self.nodes)
1765        if flag:
1766            flag = self._check_input_helper(self.stepsize)
1767        return flag
1768   
1769    def _check_input_helper(self, list):
1770        """
1771        Check list values
1772        """
1773        flag = True
1774        for item in list:
1775            item[1].SetBackgroundColour("white")
1776            item[1].Refresh()
1777            try:
1778                float(item[1].GetValue())
1779            except:
1780                flag = _set_error(self, item[1])
1781                break
1782        return flag
1783
1784class SasGenWindow(wx.Frame):
1785    """
1786    GEN SAS main window
1787    """
1788    def __init__(self, parent=None, title="Generic Scattering Calculator",
1789                size=(PANEL_WIDTH * 1.3, PANEL_HEIGHT * 1.65), *args, **kwds):
1790        """
1791        Init
1792        """
1793        kwds['size'] = size
1794        kwds['title'] = title
1795       
1796        wx.Frame.__init__(self, parent, *args, **kwds)
1797        self.parent = parent
1798        self.omfpanel = OmfPanel(parent=self)
1799        self.panel = SasGenPanel(parent=self)
1800        self.data = None
1801        self.omfdata = sans_gen.OMFData()
1802        self.sld_data = None
1803        self._default_save_location = os.getcwd() 
1804       
1805        self._mgr = aui.AuiManager(self)
1806        self._mgr.SetDockSizeConstraint(0.5, 0.5)
1807        self._plot_title = ''
1808        self.scale2d = 'log_{10}'
1809       
1810        self._build_toolbar()
1811        self._build_menubar()
1812       
1813        self.build_panels()
1814        self.Centre()
1815        self.Show(True)
1816   
1817    def _build_toolbar(self):
1818        """
1819        Build toolbar
1820        """
1821        tsize = (20, 20)
1822        tb = self.CreateToolBar(wx.TB_HORIZONTAL | wx.TB_FLAT)
1823        open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, 
1824                                            tsize)
1825        save_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE_AS, wx.ART_TOOLBAR,
1826                                            tsize)
1827        close_bmp = wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_TOOLBAR, 
1828                                            tsize)
1829        help_bmp = wx.ArtProvider.GetBitmap(wx.ART_HELP, wx.ART_TOOLBAR, 
1830                                           (17, 20))
1831       
1832        id = wx.NewId()
1833        tb.AddLabelTool(id, "Open", open_bmp, shortHelp="Open", 
1834                        longHelp="Open sld/omf file")
1835        self.Bind(wx.EVT_TOOL, self.on_open_file, id=id)
1836
1837        id = wx.NewId()
1838        tb.AddSimpleTool(id, save_bmp, "Save", "Save as sld file")
1839        self.Bind(wx.EVT_TOOL, self.on_save_file, id=id)
1840       
1841        tb.AddSeparator()
1842        id = wx.NewId()
1843        tb.AddSimpleTool(id, close_bmp, "Quit", "Quit")
1844        self.Bind(wx.EVT_TOOL, self.on_close, id=id)
1845       
1846        tb.AddSeparator()
1847        id = wx.NewId()
1848        tb.AddSimpleTool(id, help_bmp, "Help", "Help")
1849        self.Bind(wx.EVT_TOOL, self.on_help, id=id)
1850
1851        tb.Realize()
1852       
1853    def _build_menubar(self):
1854        """
1855        Build menubar
1856        """
1857        tsize = (13, 13)
1858        open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, 
1859                                            tsize)
1860        save_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE_AS, wx.ART_TOOLBAR,
1861                                            tsize)
1862        quit_bmp = wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_TOOLBAR, 
1863                                           tsize)
1864        help_bmp = wx.ArtProvider.GetBitmap(wx.ART_HELP, wx.ART_TOOLBAR, 
1865                                           (13, 15))
1866       
1867        menu_bar = wx.MenuBar()
1868       
1869        menu = wx.Menu()
1870        id = wx.NewId()
1871        item = wx.MenuItem(menu, id, "&Open sld/omf file")
1872        item.SetBitmap(open_bmp)
1873        menu.AppendItem(item)
1874        wx.EVT_MENU(self, id, self.on_open_file)
1875       
1876        id = wx.NewId()
1877        item = wx.MenuItem(menu, id, "&Save as sld file")
1878        item.SetBitmap(save_bmp)
1879        menu.AppendItem(item)
1880        wx.EVT_MENU(self, id, self.on_save_file)
1881       
1882        menu.AppendSeparator()
1883        id = wx.NewId()
1884        item = wx.MenuItem(menu, id, "&Quit")
1885        item.SetBitmap(quit_bmp)
1886        menu.AppendItem(item)
1887
1888        menu_bar.Append(menu, "&File")
1889        wx.EVT_MENU(self, id, self.on_close)
1890       
1891        menu_help = wx.Menu()
1892        id = wx.NewId()
1893        item = wx.MenuItem(menu_help, id, "&Theory and GUI")
1894        item.SetBitmap(help_bmp)
1895        menu_help.AppendItem(item)
1896        wx.EVT_MENU(self, id, self.on_help)
1897       
1898        menu_bar.Append(menu_help, "&Help")
1899       
1900        self.SetMenuBar(menu_bar)
1901       
1902    def build_panels(self):
1903        """
1904        """
1905       
1906        self.set_sld_data(self.sld_data)
1907       
1908        self._mgr.AddPane(self.panel, aui.AuiPaneInfo().
1909                              Name(self.panel.window_name).
1910                              CenterPane().
1911                              # This is where we set the size of
1912                              # the application window
1913                              BestSize(wx.Size(PANEL_WIDTH, 
1914                                               PANEL_HEIGHT)).
1915                              Show()) 
1916        self._mgr.AddPane(self.omfpanel, aui.AuiPaneInfo().
1917                              Name(self.omfpanel.window_name).
1918                              Caption(self.omfpanel.window_caption).
1919                              CloseButton(False).
1920                              Right().
1921                              Floatable(False).
1922                              BestSize(wx.Size(PANEL_WIDTH/2.5, PANEL_HEIGHT)).
1923                              Show()) 
1924        self._mgr.Update()
1925
1926    def get_sld_data(self):
1927        """
1928        Return slddata
1929        """
1930        return self.sld_data
1931   
1932    def get_sld_from_omf(self):
1933        """
1934        """
1935        self.sld_data = self.omfpanel.get_sld_val()
1936        return self.sld_data
1937   
1938    def set_sld_n(self, sld):
1939        """
1940        """
1941        self.panel.sld_data = sld
1942        self.panel.model.set_sld_data(sld)
1943       
1944    def set_sld_data(self, data):
1945        """
1946        Set omfdata
1947        """
1948        if data == None:
1949            return
1950        self.sld_data = data
1951        enable = (not data==None)
1952        self._set_omfpanel_sld_data(self.sld_data)
1953        self.omfpanel.bt_save.Enable(enable)
1954        self.set_etime()
1955   
1956    def set_omfpanel_npts(self):
1957        """
1958        Set Npts in omf panel
1959        """
1960        nop = self.omfpanel.set_npts_from_slddata()
1961        self.omfpanel.display_npts(nop)
1962       
1963    def _set_omfpanel_sld_data(self, data):
1964        """
1965        Set sld_data in omf panel
1966        """
1967        self.omfpanel.set_slddata(data) 
1968        self.omfpanel.set_sld_ctr(data)
1969   
1970    def check_omfpanel_inputs(self):
1971        """
1972        Check OMF panel inputs
1973        """
1974        return self.omfpanel.check_inputs() 
1975       
1976    def set_main_panel_sld_data(self, sld_data):
1977        """
1978        """
1979        self.sld_data = sld_data
1980       
1981    def set_file_location(self, path):
1982        """
1983        File location
1984        """
1985        self._default_save_location = path
1986   
1987    def get_path(self):
1988        """
1989        File location
1990        """
1991        return self._default_save_location
1992   
1993    def draw_graph(self, plot, title=''):
1994        """
1995        """
1996        frame = PlotFrame(self, -1, 'testView', self.scale2d)
1997        add_icon(self.parent, frame)
1998        frame.add_plot(plot)
1999        frame.SetTitle(title)
2000        frame.Show(True)
2001        frame.SetFocus()
2002   
2003    def get_npix(self):
2004        """
2005        Get no. of pixels from omf panel
2006        """
2007        n_pix = self.omfpanel.npix_ctl.GetValue()
2008        return n_pix
2009   
2010    def get_pix_volumes(self):
2011        """
2012        Get a pixel volume
2013        """
2014        vol = self.omfpanel.get_pix_volumes()
2015        return vol
2016   
2017    def set_volume_ctr_val(self, val):
2018        """
2019        Set volume txtctl value
2020        """
2021        try:
2022            self.panel.set_volume_ctl_val(str(val))
2023        except:
2024            print "self.panel is not initialized yet"
2025           
2026    def set_omfpanel_default_shap(self, shape):
2027        """
2028        Set default_shape in omfpanel
2029        """
2030        self.omfpanel.default_shape = shape
2031   
2032    def set_etime(self):
2033        """
2034        Sets est. computation time on panel
2035        """
2036        self.panel.set_est_time()
2037   
2038    def get_sld_data_from_omf(self):
2039        """
2040        """
2041        data = self.omfpanel.get_sld_val() 
2042        return data
2043       
2044    def set_scale2d(self, scale):
2045        """
2046        """
2047        self.scale2d = scale
2048           
2049    def on_panel_close(self, event):
2050        """
2051        """
2052        #Not implemented
2053         
2054    def on_open_file(self, event):
2055        """
2056        On Open
2057        """
2058        self.panel.on_load_data(event)
2059   
2060    def sld_draw(self):
2061        """
2062        sld draw
2063        """
2064        self.panel.sld_draw(event=None, has_arrow=False)
2065       
2066    def on_save_file(self, event):
2067        """
2068        On Close
2069        """
2070        self.omfpanel.on_save(event)
2071       
2072    def on_close(self, event):
2073        """
2074        Close
2075        """
2076        self.Destroy()
2077       
2078    def on_help(self, event):   
2079        """
2080        Gen scatter angle help panel
2081        """
2082        from sans.perspectives.calculator.help_panel import  HelpWindow
2083        # Get models help model_function path
2084        import sans.perspectives.calculator as calmedia
2085
2086        media = calmedia.get_data_path(media='media')
2087        path = os.path.join(media,"gen_sans_help.html") 
2088        name = "Polarization Angle"
2089        frame = HelpWindow(self, -1, title=' Help: Polarization Angle', 
2090                           pageToOpen=path, size=(865, 450))   
2091        try: 
2092            frame.splitter.DetachWindow(frame.lpanel)
2093            # Display only the right side one
2094            frame.lpanel.Hide() 
2095            frame.Show(True)
2096        except:
2097            frame.Destroy() 
2098            msg = 'Display Error\n'
2099            info = "Info"
2100            wx.MessageBox(msg, info)
2101           
2102if __name__ == "__main__": 
2103    app = wx.PySimpleApp()
2104    SGframe = SasGenWindow()   
2105    SGframe.Show(True)
2106    app.MainLoop()     
Note: See TracBrowser for help on using the repository browser.