source: sasview/sansview/perspectives/fitting/basepage.py @ ee2b492

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

working on guiframe

  • Property mode set to 100644
File size: 104.3 KB
Line 
1
2import sys
3import os
4import wx
5import numpy
6import time
7import copy 
8import math
9import string
10from sans.guiframe.panel_base import PanelBase
11from wx.lib.scrolledpanel import ScrolledPanel
12from sans.guiframe.utils import format_number,check_float
13from sans.guiframe.events import PanelOnFocusEvent
14from sans.guiframe.events import StatusEvent
15from sans.guiframe.events import AppendBookmarkEvent
16import pagestate
17from pagestate import PageState
18(PageInfoEvent, EVT_PAGE_INFO)   = wx.lib.newevent.NewEvent()
19(PreviousStateEvent, EVT_PREVIOUS_STATE)   = wx.lib.newevent.NewEvent()
20(NextStateEvent, EVT_NEXT_STATE)   = wx.lib.newevent.NewEvent()
21
22_BOX_WIDTH = 76
23_QMIN_DEFAULT = 0.0005
24_QMAX_DEFAULT = 0.5
25_NPTS_DEFAULT = 50
26#Control panel width
27if sys.platform.count("darwin")==0:
28    PANEL_WIDTH = 450
29    FONT_VARIANT = 0
30    ON_MAC = False
31else:
32    PANEL_WIDTH = 500
33    FONT_VARIANT = 1
34    ON_MAC = True
35
36
37
38class BasicPage(ScrolledPanel, PanelBase):
39    """
40    This class provide general structure of  fitpanel page
41    """
42     ## Internal name for the AUI manager
43    window_name = "Fit Page"
44    ## Title to appear on top of the window
45    window_caption = "Fit Page "
46   
47    def __init__(self, parent,color='blue', **kwargs):
48        """
49        """
50        ScrolledPanel.__init__(self, parent, **kwargs)
51        PanelBase.__init__(self)
52        self.SetupScrolling()
53        #Set window's font size
54        self.SetWindowVariant(variant=FONT_VARIANT)
55     
56        self.SetBackgroundColour(color)
57        ## parent of the page
58        self.parent = parent
59        ## manager is the fitting plugin
60        ## owner of the page (fitting plugin)
61        self.event_owner = None
62         ## current model
63        self.model = None
64        ## data
65        self.data = None
66        self.mask = None
67        self.id = None
68        ## Q range
69        self.qmax_x = _QMAX_DEFAULT
70        self.qmin_x = _QMIN_DEFAULT
71        self.npts_x = _NPTS_DEFAULT
72        ## total number of point: float
73        self.npts = None
74        ## default fitengine type
75        self.engine_type = 'scipy'
76        ## smear default
77        self.smearer = None
78        self.current_smearer = None
79        ## 2D smear accuracy default
80        self.smear2d_accuracy = 'Low'
81        ## slit smear:
82        self.dxl = None
83        self.dxw = None
84        ## pinhole smear
85        self.dx_min = None
86        self.dx_max = None
87       
88        self.disp_cb_dict = {}
89   
90        self.state = PageState(parent=parent)
91        ## dictionary containing list of models
92        self.model_list_box = {}
93       
94        ## Data member to store the dispersion object created
95        self._disp_obj_dict = {}
96        ## selected parameters to apply dispersion
97        self.disp_cb_dict ={}
98
99        ## smearer object
100        self.smearer = None
101       
102        ##list of model parameters. each item must have same length
103        ## each item related to a given parameters
104        ##[cb state, name, value, "+/-", error of fit, min, max , units]
105        self.parameters = []
106        # non-fittable parameter whose value is astring
107        self.str_parameters = []
108        ## list of parameters to fit , must be like self.parameters
109        self.param_toFit = []
110        ## list of looking like parameters but with non fittable parameters info
111        self.fixed_param = []
112        ## list of looking like parameters but with  fittable parameters info
113        self.fittable_param = []
114        ##list of dispersion parameters
115        self.disp_list = []
116        self.disp_name = ""
117       
118        ## list of orientation parameters
119        self.orientation_params = []
120        self.orientation_params_disp = []
121        if self.model != None:
122            self.disp_list = self.model.getDispParamList()
123       
124        ##enable model 2D draw
125        self.enable2D = False
126        ## check that the fit range is correct to plot the model again
127        self.fitrange = True
128        ## Create memento to save the current state
129        self.state = PageState(parent=self.parent,
130                               model=self.model, data=self.data)
131        ## flag to determine if state has change
132        self.state_change = False
133        ## save customized array
134        self.values = []
135        self.weights = []
136        ## retrieve saved state
137        self.number_saved_state = 0
138        ## dictionary of saved state
139        self.saved_states = {} 
140        ## Create context menu for page
141        self.popUpMenu = wx.Menu()
142   
143        id = wx.NewId()
144        self._keep = wx.MenuItem(self.popUpMenu,id,"BookMark",
145                                 " Keep the panel status to recall it later")
146        self.popUpMenu.AppendItem(self._keep)
147        self._keep.Enable(True)
148        self._set_bookmark_flag(False)
149        self._set_save_flag(False)
150        wx.EVT_MENU(self, id, self.on_bookmark)
151        self.popUpMenu.AppendSeparator()
152   
153        ## Default locations
154        self._default_save_location = os.getcwd()     
155        ## save initial state on context menu
156        #self.onSave(event=None)
157        self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu)
158
159        ## create the basic structure of the panel with empty sizer
160        self.define_page_structure()
161        ## drawing Initial dispersion parameters sizer
162        self.set_dispers_sizer()
163       
164        ## layout
165        self.set_layout()
166       
167   
168       
169    def on_set_focus(self, event):
170        """
171        """
172        if self._manager is not None:
173            wx.PostEvent(self._manager.parent, PanelOnFocusEvent(panel=self))
174       
175    class ModelTextCtrl(wx.TextCtrl):
176        """
177        Text control for model and fit parameters.
178        Binds the appropriate events for user interactions.
179        Default callback methods can be overwritten on initialization
180       
181        :param kill_focus_callback: callback method for EVT_KILL_FOCUS event
182        :param set_focus_callback:  callback method for EVT_SET_FOCUS event
183        :param mouse_up_callback:   callback method for EVT_LEFT_UP event
184        :param text_enter_callback: callback method for EVT_TEXT_ENTER event
185       
186        """
187        ## Set to True when the mouse is clicked while the whole string is selected
188        full_selection = False
189        ## Call back for EVT_SET_FOCUS events
190        _on_set_focus_callback = None
191       
192        def __init__(self, parent, id=-1, 
193                     value=wx.EmptyString, 
194                     pos=wx.DefaultPosition, 
195                     size=wx.DefaultSize,
196                     style=0, 
197                     validator=wx.DefaultValidator,
198                     name=wx.TextCtrlNameStr,
199                     kill_focus_callback=None,
200                     set_focus_callback=None,
201                     mouse_up_callback=None,
202                     text_enter_callback = None):
203             
204            wx.TextCtrl.__init__(self, parent, id, value, pos,
205                                  size, style, validator, name)
206           
207            # Bind appropriate events
208            self._on_set_focus_callback = parent.onSetFocus \
209                      if set_focus_callback is None else set_focus_callback
210            self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
211            self.Bind(wx.EVT_KILL_FOCUS, self._silent_kill_focus \
212                      if kill_focus_callback is None else kill_focus_callback)               
213            self.Bind(wx.EVT_TEXT_ENTER, parent._onparamEnter \
214                      if text_enter_callback is None else text_enter_callback)
215            if not ON_MAC :
216                self.Bind(wx.EVT_LEFT_UP,    self._highlight_text \
217                          if mouse_up_callback is None else mouse_up_callback)
218           
219        def _on_set_focus(self, event):
220            """
221            Catch when the text control is set in focus to highlight the whole
222            text if necessary
223           
224            :param event: mouse event
225           
226            """
227            event.Skip()
228            self.full_selection = True
229            return self._on_set_focus_callback(event)
230       
231 
232           
233        def _highlight_text(self, event):
234            """
235            Highlight text of a TextCtrl only of no text has be selected
236           
237            :param event: mouse event
238           
239            """
240            # Make sure the mouse event is available to other listeners
241            event.Skip()
242            control  = event.GetEventObject()
243            if self.full_selection:
244                self.full_selection = False
245                # Check that we have a TextCtrl
246                if issubclass(control.__class__, wx.TextCtrl):
247                    # Check whether text has been selected,
248                    # if not, select the whole string
249                    (start, end) = control.GetSelection()
250                    if start==end:
251                        control.SetSelection(-1,-1)
252                       
253        def _silent_kill_focus(self,event):
254            """
255            Save the state of the page
256            """
257           
258            event.Skip()
259            pass
260   
261    def set_page_info(self, page_info):
262        """
263        set some page important information at once
264        """
265       ##window_name
266        self.window_name = page_info.window_name
267        ##window_caption
268        self.window_caption = page_info.window_caption
269        ## manager is the fitting plugin
270        self._manager= page_info.manager
271        ## owner of the page (fitting plugin)
272        self.event_owner= page_info.event_owner
273         ## current model
274        self.model = page_info.model
275        ## data
276        self.data = page_info.data
277        ## dictionary containing list of models
278        self.model_list_box = page_info.model_list_box
279        ## Data member to store the dispersion object created
280        self.populate_box(dict=self.model_list_box)
281       
282    def onContextMenu(self, event): 
283        """
284        Retrieve the state selected state
285        """
286        # Skipping the save state functionality for release 0.9.0
287        #return
288   
289        pos = event.GetPosition()
290        pos = self.ScreenToClient(pos)
291       
292        self.PopupMenu(self.popUpMenu, pos) 
293     
294       
295    def onUndo(self, event):
296        """
297        Cancel the previous action
298        """
299        event = PreviousStateEvent(page = self)
300        wx.PostEvent(self.parent, event)
301       
302    def onRedo(self, event):
303        """
304        Restore the previous action cancelled
305        """
306        event = NextStateEvent(page= self)
307        wx.PostEvent(self.parent, event)
308   
309    def define_page_structure(self):
310        """
311        Create empty sizer for a panel
312        """
313        self.vbox  = wx.BoxSizer(wx.VERTICAL)
314        self.sizer0 = wx.BoxSizer(wx.VERTICAL)
315        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
316        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
317        self.sizer3 = wx.BoxSizer(wx.VERTICAL)
318        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
319        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
320        self.sizer6 = wx.BoxSizer(wx.VERTICAL)
321       
322        self.sizer0.SetMinSize((PANEL_WIDTH,-1))
323        self.sizer1.SetMinSize((PANEL_WIDTH,-1))
324        self.sizer2.SetMinSize((PANEL_WIDTH,-1))
325        self.sizer3.SetMinSize((PANEL_WIDTH,-1))
326        self.sizer4.SetMinSize((PANEL_WIDTH,-1))
327        self.sizer5.SetMinSize((PANEL_WIDTH,-1))
328        self.sizer6.SetMinSize((PANEL_WIDTH,-1))
329       
330        self.vbox.Add(self.sizer0)
331        self.vbox.Add(self.sizer1)
332        self.vbox.Add(self.sizer2)
333        self.vbox.Add(self.sizer3)
334        self.vbox.Add(self.sizer4)
335        self.vbox.Add(self.sizer5)
336        self.vbox.Add(self.sizer6)
337       
338    def set_layout(self):
339        """
340        layout
341        """
342        self.vbox.Layout()
343        self.vbox.Fit(self) 
344        self.SetSizer(self.vbox)
345        self.Centre()
346 
347    def set_owner(self,owner):
348        """
349        set owner of fitpage
350       
351        :param owner: the class responsible of plotting
352       
353        """
354        self.event_owner = owner   
355        self.state.event_owner = owner
356       
357    def get_state(self):
358        """
359        """
360        return self.state
361    def get_data(self):
362        """
363        return the current data
364        """
365        return self.data 
366   
367    def set_manager(self, manager):
368        """
369        set panel manager
370       
371        :param manager: instance of plugin fitting
372       
373        """
374        self._manager = manager 
375        self.state.manager = manager
376       
377    def populate_box(self, dict):
378        """
379        Store list of model
380       
381        :param dict: dictionary containing list of models
382       
383        """
384        self.model_list_box = dict
385        self.state.model_list_box = self.model_list_box
386        self.initialize_combox()
387       
388    def initialize_combox(self): 
389        """
390        put default value in the combobox
391        """ 
392        ## fill combox box
393        if self.model_list_box is None:
394            return
395        if len(self.model_list_box) > 0:
396            self._populate_box(self.formfactorbox,
397                               self.model_list_box["Shapes"])
398       
399        if len(self.model_list_box) > 0:
400            self._populate_box(self.structurebox,
401                                self.model_list_box["Structure Factors"])
402            self.structurebox.Insert("None", 0, None)
403            self.structurebox.SetSelection(0)
404            self.structurebox.Hide()
405            self.text2.Hide()
406            self.structurebox.Disable()
407            self.text2.Disable()
408             
409            if self.model.__class__ in self.model_list_box["P(Q)*S(Q)"]:
410                self.structurebox.Show()
411                self.text2.Show()
412                self.structurebox.Enable()
413                self.text2.Enable()           
414               
415    def set_dispers_sizer(self):
416        """
417        fill sizer containing dispersity info
418        """
419        self.sizer4.Clear(True)
420        name="Polydispersity and Orientational Distribution"
421        box_description= wx.StaticBox(self, -1,name)
422        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
423        #----------------------------------------------------
424        self.disable_disp = wx.RadioButton(self, -1, 'Off', (10, 10),
425                                            style=wx.RB_GROUP)
426        self.enable_disp = wx.RadioButton(self, -1, 'On', (10, 30))
427       
428       
429        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
430                     id=self.disable_disp.GetId())
431        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
432                   id=self.enable_disp.GetId())
433        #MAC needs SetValue
434        self.disable_disp.SetValue(True)
435        sizer_dispersion = wx.BoxSizer(wx.HORIZONTAL)
436        sizer_dispersion.Add((20,20))
437        name=""#Polydispersity and \nOrientational Distribution "
438        sizer_dispersion.Add(wx.StaticText(self,-1,name))
439        sizer_dispersion.Add(self.enable_disp )
440        sizer_dispersion.Add((20,20))
441        sizer_dispersion.Add(self.disable_disp )
442        sizer_dispersion.Add((10,10))
443       
444        ## fill a sizer with the combobox to select dispersion type
445        sizer_select_dispers = wx.BoxSizer(wx.HORIZONTAL) 
446        self.model_disp = wx.StaticText(self, -1, 'Distribution Function ')
447           
448        import sans.models.dispersion_models 
449        self.polydisp= sans.models.dispersion_models.models
450        self.disp_box = wx.ComboBox(self, -1)
451
452        for key, value in self.polydisp.iteritems():
453            name = str(key)
454            self.disp_box.Append(name,value)
455        self.disp_box.SetStringSelection("gaussian") 
456        wx.EVT_COMBOBOX(self.disp_box,-1, self._on_select_Disp) 
457             
458        sizer_select_dispers.Add((10,10)) 
459        sizer_select_dispers.Add(self.model_disp) 
460        sizer_select_dispers.Add(self.disp_box,0,
461                wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5)
462     
463        self.model_disp.Hide()
464        self.disp_box.Hide()
465       
466        boxsizer1.Add( sizer_dispersion,0,
467                wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5)
468        #boxsizer1.Add( (10,10) )
469        boxsizer1.Add( sizer_select_dispers )
470        self.sizer4_4 = wx.GridBagSizer(5,5)
471        boxsizer1.Add( self.sizer4_4  )
472        #-----------------------------------------------------
473        self.sizer4.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
474        self.sizer4_4.Layout()
475        self.sizer4.Layout()
476        self.Layout()
477     
478        self.Refresh()
479        ## saving the state of enable dispersity button
480        self.state.enable_disp= self.enable_disp.GetValue()
481        self.state.disable_disp= self.disable_disp.GetValue()
482
483    def select_disp_angle(self, event): 
484        """
485        Event for when a user select a parameter to average over.
486       
487        :param event: radiobutton event
488       
489        """
490        self.values=[]
491        self.weights=[]
492        if event.GetEventObject()==self.noDisper_rbox:
493            if self.noDisper_rbox.GetValue():
494                #No array dispersity apply yet
495                self._reset_dispersity()
496                ## Redraw the model ???
497                self._draw_model()
498        # Go through the list of dispersion check boxes to identify
499        # which one has changed
500        for p in self.disp_cb_dict:
501            self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
502            # Catch which one of the box was just checked or unchecked.
503            if event.GetEventObject() == self.disp_cb_dict[p]:             
504                if self.disp_cb_dict[p].GetValue() == True:
505                   
506                    ##Temp. FIX for V1.0 regarding changing checkbox
507                    #to radiobutton.
508                    ##This (self._reset_dispersity) should be removed
509                    #when the array dispersion is fixed.               
510                    self._reset_dispersity()
511
512                    # The user wants this parameter to be averaged.
513                    # Pop up the file selection dialog.
514                    path = self._selectDlg()
515                   
516                    # If nothing was selected, just return
517                    if path is None:
518                        self.disp_cb_dict[p].SetValue(False)
519                        self.noDisper_rbox.SetValue(True)
520                        return
521                    try:
522                        self._default_save_location = os.path.dirname(path)
523                    except:
524                        pass 
525                    try:
526                        self.values,self.weights = self.read_file(path)
527                    except:
528                        msg="Could not read input file"
529                        wx.PostEvent(self.parent.parent, 
530                                     StatusEvent(status=msg))
531                        return
532                   
533                    # If any of the two arrays is empty, notify the user that we won't
534                    # proceed
535                    if self.values is None or self.weights is None or \
536                         self.values ==[] or self.weights ==[]:
537                        msg = "The loaded %s distrubtion is"
538                        msg + " corrupted or empty" % p
539                        wx.PostEvent(self.parent.parent, 
540                                     StatusEvent(status=msg))
541                        return
542                       
543                    # Tell the user that we are about to apply the distribution
544                    msg = "Applying loaded %s distribution: %s" % (p, path)
545                    wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) 
546                   
547                    # Create the dispersion objects
548                    from sans.models.dispersion_models import ArrayDispersion
549                    disp_model = ArrayDispersion()
550                    disp_model.set_weights(self.values, self.weights)
551                   
552                    # Store the object to make it persist outside the
553                    # scope of this method
554                    #TODO: refactor model to clean this up?
555                    self._disp_obj_dict[p] = disp_model
556                    self.state._disp_obj_dict [p]= disp_model
557                    self.state.values = []
558                    self.state.weights = []
559                    self.state.values = copy.deepcopy(self.values)
560                    self.state.weights = copy.deepcopy(self.weights)
561                    # Set the new model as the dispersion object for the
562                    #selected parameter
563                    self.model.set_dispersion(p, disp_model)
564                    # Store a reference to the weights in the model object
565                    #so that
566                    # it's not lost when we use the model within another thread.
567                    #TODO: total hack - fix this
568                    self.state.model= self.model.clone()
569
570                    self.model._persistency_dict = {}
571                    self.model._persistency_dict[p] = \
572                                                    [self.values, self.weights]
573                    self.state.model._persistency_dict[p] = \
574                                                    [self.values,self.weights]
575                else:
576                    self._reset_dispersity()
577             
578                ## Redraw the model
579                self._draw_model()
580       
581        ## post state to fit panel
582        event = PageInfoEvent(page = self)
583        wx.PostEvent(self.parent, event)
584       
585   
586    def onResetModel(self, event):
587        """
588        Reset model state
589        """
590        menu = event.GetEventObject()
591        ## post help message for the selected model
592        msg = menu.GetHelpString(event.GetId())
593        msg +=" reloaded"
594        wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
595       
596        name = menu.GetLabel(event.GetId())
597        self._on_select_model_helper()
598       
599        if name in self.saved_states.keys():
600            previous_state = self.saved_states[name]
601            ## reset state of checkbox,textcrtl  and  regular parameters value
602            self.reset_page(previous_state)     
603         
604    def on_save(self, event):   
605        """
606        Save the current state into file
607        """ 
608        self.save_current_state()
609        new_state = self.state.clone()
610        # Ask the user the location of the file to write to.
611        path = None
612        dlg = wx.FileDialog(self, "Choose a file", self._default_save_location,
613                                                 "", "*.fitv", wx.SAVE)
614        if dlg.ShowModal() == wx.ID_OK:
615            path = dlg.GetPath()
616            self._default_save_location = os.path.dirname(path)
617        else:
618            return None
619        #the manager write the state into file
620        self._manager.save_fit_state(filepath=path, fitstate=new_state)
621        return new_state 
622   
623    def _get_time_stamp(self):
624        """
625        return time and date stings
626        """
627        # date and time
628        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
629        current_time= str(hour)+":"+str(minute)+":"+str(second)
630        current_date= str( month)+"/"+str(day)+"/"+str(year)
631        return current_time, current_date
632     
633    def on_bookmark(self, event):
634        """
635        save history of the data and model
636        """
637        if self.model==None:
638            msg="Can not bookmark; Please select Data and Model first..."
639            wx.MessageBox(msg, 'Info')
640            return 
641        self.save_current_state()
642        new_state = self.state.clone()
643        ##Add model state on context menu
644        self.number_saved_state += 1
645        current_time, current_date = self._get_time_stamp()
646        #name= self.model.name+"[%g]"%self.number_saved_state
647        name = "Fitting: %g]" % self.number_saved_state
648        name += self.model.__class__.__name__
649        name += "bookmarked at %s on %s" % (current_time, current_date)
650        self.saved_states[name]= new_state
651       
652        ## Add item in the context menu
653        msg =  "Model saved at %s on %s"%(current_time, current_date)
654         ## post help message for the selected model
655        msg +=" Saved! right click on this page to retrieve this model"
656        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
657       
658        #id = wx.NewId()
659        #self.popUpMenu.Append(id,name,str(msg))
660        #wx.EVT_MENU(self, id, self.onResetModel)
661        wx.PostEvent(self.parent.parent, 
662                     AppendBookmarkEvent(title=name, 
663                                         hint=str(msg), handler=self.onResetModel))
664       
665    def old_on_bookmark(self, event):
666        """
667        save history of the data and model
668        """
669        if self.model==None:
670            msg="Can not bookmark; Please select Data and Model first..."
671            wx.MessageBox(msg, 'Info')
672            return 
673        if hasattr(self,"enable_disp"):
674            self.state.enable_disp = copy.deepcopy(self.enable_disp.GetValue())
675        if hasattr(self, "disp_box"):
676            self.state.disp_box = copy.deepcopy(self.disp_box.GetSelection())
677
678        self.state.model.name= self.model.name
679       
680        #Remember fit engine_type for fit panel
681        if self.engine_type == None: 
682            self.engine_type = "scipy"
683        if self._manager !=None:
684            self._manager._on_change_engine(engine=self.engine_type)
685       
686            self.state.engine_type = self.engine_type
687
688        new_state = self.state.clone()
689        new_state.model.name = self.state.model.name
690       
691        new_state.enable2D = copy.deepcopy(self.enable2D)
692        ##Add model state on context menu
693        self.number_saved_state += 1
694        #name= self.model.name+"[%g]"%self.number_saved_state
695        name= self.model.__class__.__name__+"[%g]"%self.number_saved_state
696        self.saved_states[name]= new_state
697       
698        ## Add item in the context menu
699       
700        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
701        my_time= str(hour)+" : "+str(minute)+" : "+str(second)+" "
702        date= str( month)+"|"+str(day)+"|"+str(year)
703        msg=  "Model saved at %s on %s"%(my_time, date)
704         ## post help message for the selected model
705        msg +=" Saved! right click on this page to retrieve this model"
706        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
707       
708        id = wx.NewId()
709        self.popUpMenu.Append(id,name,str(msg))
710        wx.EVT_MENU(self, id, self.onResetModel)
711       
712    def onSetFocus(self, evt):
713        """
714        highlight the current textcrtl and hide the error text control shown
715        after fitting
716        """
717        return
718   
719    def read_file(self, path):
720        """
721        Read two columns file
722       
723        :param path: the path to the file to read
724       
725        """
726        try:
727            if path==None:
728                wx.PostEvent(self.parent.parent, StatusEvent(status=\
729                            " Selected Distribution was not loaded: %s"%path))
730                return None, None
731            input_f = open(path, 'r')
732            buff = input_f.read()
733            lines = buff.split('\n')
734           
735            angles = []
736            weights=[]
737            for line in lines:
738                toks = line.split()
739                try:
740                    angle = float(toks[0])
741                    weight = float(toks[1])
742                except:
743                    # Skip non-data lines
744                    pass
745                angles.append(angle)
746                weights.append(weight)
747            return numpy.array(angles), numpy.array(weights)
748        except:
749            raise 
750
751    def createMemento(self):
752        """
753        return the current state of the page
754        """
755        return self.state.clone()
756   
757   
758    def save_current_state(self):
759        """
760        Store current state
761        """
762        self.state.engine_type = copy.deepcopy(self.engine_type)
763        ## save model option
764        if self.model!= None:
765            self.disp_list= self.model.getDispParamList()
766            self.state.disp_list= copy.deepcopy(self.disp_list)
767            self.state.model = self.model.clone()
768        #save radiobutton state for model selection
769        self.state.shape_rbutton = self.shape_rbutton.GetValue()
770        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
771        self.state.struct_rbutton = self.struct_rbutton.GetValue()
772        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
773        #model combobox
774        self.state.structurebox = self.structurebox.GetSelection()
775        self.state.formfactorbox = self.formfactorbox.GetSelection()
776       
777        self.state.enable2D = copy.deepcopy(self.enable2D)
778        self.state.values= copy.deepcopy(self.values)
779        self.state.weights = copy.deepcopy( self.weights)
780        ## save data   
781        self.state.data= copy.deepcopy(self.data)
782        self.state.qmax_x = self.qmax_x
783        self.state.qmin_x = self.qmin_x
784        try:
785            n = self.disp_box.GetCurrentSelection()
786            dispersity= self.disp_box.GetClientData(n)
787            name= dispersity.__name__
788            self.disp_name = name
789            if name == "GaussianDispersion" :
790               if hasattr(self,"cb1"):
791                   self.state.cb1= self.cb1.GetValue()
792        except:
793            pass
794     
795        if hasattr(self,"enable_disp"):
796            self.state.enable_disp= self.enable_disp.GetValue()
797            self.state.disable_disp = self.disable_disp.GetValue()
798           
799        self.state.smearer = copy.deepcopy(self.smearer)
800        if hasattr(self,"enable_smearer"):
801            self.state.enable_smearer = \
802                                copy.deepcopy(self.enable_smearer.GetValue())
803            self.state.disable_smearer = \
804                                copy.deepcopy(self.disable_smearer.GetValue())
805
806        self.state.pinhole_smearer = \
807                                copy.deepcopy(self.pinhole_smearer.GetValue())
808        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
809                 
810        if hasattr(self,"disp_box"):
811            self.state.disp_box = self.disp_box.GetSelection()
812
813            if len(self.disp_cb_dict)>0:
814                for k , v in self.disp_cb_dict.iteritems():
815         
816                    if v ==None :
817                        self.state.disp_cb_dict[k]= v
818                    else:
819                        try:
820                            self.state.disp_cb_dict[k]=v.GetValue()
821                        except:
822                            self.state.disp_cb_dict[k]= None
823           
824            if len(self._disp_obj_dict)>0:
825                for k , v in self._disp_obj_dict.iteritems():
826     
827                    self.state._disp_obj_dict[k]= v
828                       
829           
830            self.state.values = copy.deepcopy(self.values)
831            self.state.weights = copy.deepcopy(self.weights)
832        ## save plotting range
833        self._save_plotting_range()
834       
835        self.state.orientation_params =[]
836        self.state.orientation_params_disp =[]
837        self.state.parameters =[]
838        self.state.fittable_param =[]
839        self.state.fixed_param =[]
840
841       
842        ## save checkbutton state and txtcrtl values
843        self._copy_parameters_state(self.orientation_params,
844                                     self.state.orientation_params)
845        self._copy_parameters_state(self.orientation_params_disp,
846                                     self.state.orientation_params_disp)
847       
848        self._copy_parameters_state(self.parameters, self.state.parameters)
849        self._copy_parameters_state(self.fittable_param,
850                                     self.state.fittable_param)
851        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
852        #save chisqr
853        self.state.tcChi = self.tcChi.GetValue()
854       
855    def save_current_state_fit(self):
856        """
857        Store current state for fit_page
858        """
859        ## save model option
860        if self.model!= None:
861            self.disp_list= self.model.getDispParamList()
862            self.state.disp_list= copy.deepcopy(self.disp_list)
863            self.state.model = self.model.clone()
864        if hasattr(self, "engine_type"):
865            self.state.engine_type = copy.deepcopy(self.engine_type)
866           
867        self.state.enable2D = copy.deepcopy(self.enable2D)
868        self.state.values= copy.deepcopy(self.values)
869        self.state.weights = copy.deepcopy( self.weights)
870        ## save data   
871        self.state.data= copy.deepcopy(self.data)
872        try:
873            n = self.disp_box.GetCurrentSelection()
874            dispersity= self.disp_box.GetClientData(n)
875            name= dispersity.__name__
876            self.disp_name = name
877            if name == "GaussianDispersion" :
878               if hasattr(self,"cb1"):
879                   self.state.cb1= self.cb1.GetValue()
880
881        except:
882            pass
883       
884        if hasattr(self,"enable_disp"):
885            self.state.enable_disp= self.enable_disp.GetValue()
886            self.state.disable_disp = self.disable_disp.GetValue()
887           
888        self.state.smearer = copy.deepcopy(self.smearer)
889        if hasattr(self,"enable_smearer"):
890            self.state.enable_smearer = \
891                                copy.deepcopy(self.enable_smearer.GetValue())
892            self.state.disable_smearer = \
893                                copy.deepcopy(self.disable_smearer.GetValue())
894           
895        self.state.pinhole_smearer = \
896                                copy.deepcopy(self.pinhole_smearer.GetValue())
897        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
898           
899        if hasattr(self,"disp_box"):
900            self.state.disp_box = self.disp_box.GetCurrentSelection()
901
902            if len(self.disp_cb_dict) > 0:
903                for k, v in self.disp_cb_dict.iteritems():
904         
905                    if v == None :
906                        self.state.disp_cb_dict[k] = v
907                    else:
908                        try:
909                            self.state.disp_cb_dict[k] = v.GetValue()
910                        except:
911                            self.state.disp_cb_dict[k] = None
912           
913            if len(self._disp_obj_dict) > 0:
914                for k , v in self._disp_obj_dict.iteritems():
915     
916                    self.state._disp_obj_dict[k] = v
917                       
918           
919            self.state.values = copy.deepcopy(self.values)
920            self.state.weights = copy.deepcopy(self.weights)
921           
922        ## save plotting range
923        self._save_plotting_range()
924       
925        ## save checkbutton state and txtcrtl values
926        self._copy_parameters_state(self.orientation_params,
927                                     self.state.orientation_params)
928        self._copy_parameters_state(self.orientation_params_disp,
929                                     self.state.orientation_params_disp)
930        self._copy_parameters_state(self.parameters, self.state.parameters)
931        self._copy_parameters_state(self.fittable_param,
932                                             self.state.fittable_param)
933        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
934   
935         
936    def check_invalid_panel(self): 
937        """
938        check if the user can already perform some action with this panel
939        """ 
940        flag = False
941        if self.data is None:
942            self.disable_smearer.SetValue(True)
943            self.disable_disp.SetValue(True)
944            msg = "Please load Data and select Model to start..."
945            wx.MessageBox(msg, 'Info')
946            return  True
947       
948    def set_model_state(self, state):
949        """
950        reset page given a model state
951        """
952        self.disp_cb_dict = state.disp_cb_dict
953        self.disp_list = state.disp_list
954     
955        ## set the state of the radio box
956        self.shape_rbutton.SetValue(state.shape_rbutton )
957        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
958        self.struct_rbutton.SetValue(state.struct_rbutton)
959        self.plugin_rbutton.SetValue(state.plugin_rbutton)
960       
961        ## fill model combobox
962        self._show_combox_helper()
963        #select the current model
964        self.formfactorbox.Select(int(state.formfactorcombobox))
965        self.structurebox.SetSelection(state.structurecombobox )
966        if state.multi_factor != None:
967            self.multifactorbox.SetSelection(state.multi_factor)
968           
969         ## reset state of checkbox,textcrtl  and  regular parameters value
970        self._reset_parameters_state(self.orientation_params_disp,
971                                     state.orientation_params_disp)
972        self._reset_parameters_state(self.orientation_params,
973                                     state.orientation_params)
974        self._reset_parameters_state(self.str_parameters,
975                                     state.str_parameters)
976        self._reset_parameters_state(self.parameters,state.parameters)
977         ## display dispersion info layer       
978        self.enable_disp.SetValue(state.enable_disp)
979        self.disable_disp.SetValue(state.disable_disp)
980       
981        if hasattr(self, "disp_box"):
982           
983            self.disp_box.SetSelection(state.disp_box) 
984            n= self.disp_box.GetCurrentSelection()
985            dispersity= self.disp_box.GetClientData(n)
986            name = dispersity.__name__     
987
988            self._set_dipers_Param(event=None)
989       
990            if name == "ArrayDispersion":
991               
992                for item in self.disp_cb_dict.keys():
993                   
994                    if hasattr(self.disp_cb_dict[item], "SetValue") :
995                        self.disp_cb_dict[item].SetValue(\
996                                                    state.disp_cb_dict[item])
997                        # Create the dispersion objects
998                        from sans.models.dispersion_models import ArrayDispersion
999                        disp_model = ArrayDispersion()
1000                        if hasattr(state,"values")and\
1001                                 self.disp_cb_dict[item].GetValue() == True:
1002                            if len(state.values)>0:
1003                                self.values=state.values
1004                                self.weights=state.weights
1005                                disp_model.set_weights(self.values,
1006                                                        state.weights)
1007                            else:
1008                                self._reset_dispersity()
1009                       
1010                        self._disp_obj_dict[item] = disp_model
1011                        # Set the new model as the dispersion object
1012                        #for the selected parameter
1013                        self.model.set_dispersion(item, disp_model)
1014                   
1015                        self.model._persistency_dict[item] = \
1016                                                [state.values, state.weights]
1017                   
1018            else:
1019                keys = self.model.getParamList()
1020                for item in keys:
1021                    if item in self.disp_list and \
1022                        not self.model.details.has_key(item):
1023                        self.model.details[item] = ["", None, None]
1024                for k,v in self.state.disp_cb_dict.iteritems():
1025                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1026                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1027         ## smearing info  restore
1028        if hasattr(self, "enable_smearer"):
1029            ## set smearing value whether or not the data
1030            #contain the smearing info
1031            self.enable_smearer.SetValue(state.enable_smearer)
1032            self.disable_smearer.SetValue(state.disable_smearer)
1033            self.onSmear(event=None)           
1034        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1035        self.slit_smearer.SetValue(state.slit_smearer)
1036        ## we have two more options for smearing
1037        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1038        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1039       
1040        ## reset state of checkbox,textcrtl  and dispersity parameters value
1041        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1042        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1043       
1044        ## draw the model with previous parameters value
1045        self._onparamEnter_helper()
1046        self.select_param(event=None) 
1047        #Save state_fit
1048        self.save_current_state_fit()
1049        self._lay_out()
1050        self.Refresh()
1051       
1052    def reset_page_helper(self, state):
1053        """
1054        Use page_state and change the state of existing page
1055       
1056        :precondition: the page is already drawn or created
1057       
1058        :postcondition: the state of the underlying data change as well as the
1059            state of the graphic interface
1060        """
1061        if state == None:
1062            #self._undo.Enable(False)
1063            return 
1064   
1065        self.set_data(state.data)
1066        self.enable2D= state.enable2D
1067        self.engine_type = state.engine_type
1068
1069        self.disp_cb_dict = state.disp_cb_dict
1070        self.disp_list = state.disp_list
1071     
1072        ## set the state of the radio box
1073        self.shape_rbutton.SetValue(state.shape_rbutton )
1074        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1075        self.struct_rbutton.SetValue(state.struct_rbutton)
1076        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1077       
1078        ## fill model combobox
1079        self._show_combox_helper()
1080        #select the current model
1081        self.formfactorbox.Select(int(state.formfactorcombobox))
1082        self.structurebox.SetSelection(state.structurecombobox )
1083        if state.multi_factor != None:
1084            self.multifactorbox.SetSelection(state.multi_factor)
1085
1086        #reset the fitting engine type
1087        self.engine_type = state.engine_type
1088        #draw the pnael according to the new model parameter
1089        self._on_select_model(event=None)
1090       
1091        if self._manager !=None:
1092            self._manager._on_change_engine(engine=self.engine_type)
1093        ## set the select all check box to the a given state
1094        self.cb1.SetValue(state.cb1)
1095     
1096        ## reset state of checkbox,textcrtl  and  regular parameters value
1097        self._reset_parameters_state(self.orientation_params_disp,
1098                                     state.orientation_params_disp)
1099        self._reset_parameters_state(self.orientation_params,
1100                                     state.orientation_params)
1101        self._reset_parameters_state(self.str_parameters,
1102                                     state.str_parameters)
1103        self._reset_parameters_state(self.parameters,state.parameters)   
1104         ## display dispersion info layer       
1105        self.enable_disp.SetValue(state.enable_disp)
1106        self.disable_disp.SetValue(state.disable_disp)
1107       
1108        if hasattr(self, "disp_box"):
1109           
1110            self.disp_box.SetSelection(state.disp_box) 
1111            n= self.disp_box.GetCurrentSelection()
1112            dispersity= self.disp_box.GetClientData(n)
1113            name = dispersity.__name__     
1114
1115            self._set_dipers_Param(event=None)
1116       
1117            if name == "ArrayDispersion":
1118               
1119                for item in self.disp_cb_dict.keys():
1120                   
1121                    if hasattr(self.disp_cb_dict[item], "SetValue") :
1122                        self.disp_cb_dict[item].SetValue(\
1123                                                    state.disp_cb_dict[item])
1124                        # Create the dispersion objects
1125                        from sans.models.dispersion_models import ArrayDispersion
1126                        disp_model = ArrayDispersion()
1127                        if hasattr(state,"values")and\
1128                                 self.disp_cb_dict[item].GetValue() == True:
1129                            if len(state.values)>0:
1130                                self.values=state.values
1131                                self.weights=state.weights
1132                                disp_model.set_weights(self.values,
1133                                                        state.weights)
1134                            else:
1135                                self._reset_dispersity()
1136                       
1137                        self._disp_obj_dict[item] = disp_model
1138                        # Set the new model as the dispersion object
1139                        #for the selected parameter
1140                        self.model.set_dispersion(item, disp_model)
1141                   
1142                        self.model._persistency_dict[item] = \
1143                                                [state.values, state.weights]
1144                   
1145            else:
1146                keys = self.model.getParamList()
1147                for item in keys:
1148                    if item in self.disp_list and \
1149                        not self.model.details.has_key(item):
1150                        self.model.details[item] = ["", None, None]
1151                for k,v in self.state.disp_cb_dict.iteritems():
1152                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1153                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1154
1155        ##plotting range restore   
1156        self._reset_plotting_range(state)
1157        ## smearing info  restore
1158        if hasattr(self, "enable_smearer"):
1159            ## set smearing value whether or not the data
1160            #contain the smearing info
1161            self.enable_smearer.SetValue(state.enable_smearer)
1162            self.disable_smearer.SetValue(state.disable_smearer)
1163            self.onSmear(event=None)           
1164        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1165        self.slit_smearer.SetValue(state.slit_smearer)
1166        ## we have two more options for smearing
1167        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1168        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1169       
1170        ## reset state of checkbox,textcrtl  and dispersity parameters value
1171        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1172        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1173       
1174        ## draw the model with previous parameters value
1175        self._onparamEnter_helper()
1176        #reset the value of chisqr when not consistent with the value computed
1177        self.tcChi.SetValue(str(self.state.tcChi))
1178        ## reset context menu items
1179        self._reset_context_menu()
1180       
1181        ## set the value of the current state to the state given as parameter
1182        self.state = state.clone() 
1183   
1184       
1185    def old_reset_page_helper(self, state):
1186        """
1187        Use page_state and change the state of existing page
1188       
1189        :precondition: the page is already drawn or created
1190       
1191        :postcondition: the state of the underlying data change as well as the
1192            state of the graphic interface
1193        """
1194        if state ==None:
1195            #self._undo.Enable(False)
1196            return 
1197       
1198        self.model= state.model
1199        self.data = state.data
1200        if self.data !=None:
1201            from DataLoader.qsmearing import smear_selection
1202            self.smearer= smear_selection(self.data, self.model)
1203        self.enable2D= state.enable2D
1204        self.engine_type = state.engine_type
1205
1206        self.disp_cb_dict = state.disp_cb_dict
1207        self.disp_list = state.disp_list
1208
1209        ## set the state of the radio box
1210        self.shape_rbutton.SetValue(state.shape_rbutton )
1211        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1212        self.struct_rbutton.SetValue(state.struct_rbutton )
1213        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1214        ##draw sizer containing model parameters value for the current model
1215        self._set_model_sizer_selection( self.model )
1216        self.set_model_param_sizer(self.model)
1217
1218        ## reset value of combox box
1219        self.structurebox.SetSelection(state.structurecombobox )
1220        self.formfactorbox.SetSelection(state.formfactorcombobox)
1221       
1222       
1223        ## enable the view 2d button if this is a modelpage type
1224        if hasattr(self,"model_view"):
1225            if self.enable2D:
1226                self.model_view.Disable()
1227            else:
1228                self.model_view.Enable()
1229        ## set the select all check box to the a given state
1230        if hasattr(self, "cb1"):   
1231            self.cb1.SetValue(state.cb1)
1232     
1233        ## reset state of checkbox,textcrtl  and  regular parameters value
1234           
1235        self._reset_parameters_state(self.orientation_params_disp,
1236                                     state.orientation_params_disp)
1237        self._reset_parameters_state(self.orientation_params,
1238                                     state.orientation_params)
1239        self._reset_parameters_state(self.parameters,state.parameters)   
1240         ## display dispersion info layer       
1241        self.enable_disp.SetValue(state.enable_disp)
1242        self.disable_disp.SetValue(state.disable_disp)
1243       
1244        if hasattr(self, "disp_box"):
1245           
1246            self.disp_box.SetSelection(state.disp_box) 
1247            n= self.disp_box.GetCurrentSelection()
1248            dispersity= self.disp_box.GetClientData(n)
1249            name= dispersity.__name__     
1250
1251            self._set_dipers_Param(event=None)
1252       
1253            if name=="ArrayDispersion":
1254               
1255                for item in self.disp_cb_dict.keys():
1256                   
1257                    if hasattr(self.disp_cb_dict[item],"SetValue") :
1258                        self.disp_cb_dict[item].SetValue(state.disp_cb_dict[item])
1259                        # Create the dispersion objects
1260                        from sans.models.dispersion_models import ArrayDispersion
1261                        disp_model = ArrayDispersion()
1262                        if hasattr(state,"values") and\
1263                             self.disp_cb_dict[item].GetValue()==True:
1264                            if len(state.values) > 0:
1265                                self.values = state.values
1266                                self.weights = state.weights
1267                                disp_model.set_weights(self.values,
1268                                                        state.weights)
1269                            else:
1270                                self._reset_dispersity()
1271                       
1272                        self._disp_obj_dict[item] = disp_model
1273                        # Set the new model as the dispersion
1274                        #object for the selected parameter
1275                        self.model.set_dispersion(item, disp_model)
1276                   
1277                        self.model._persistency_dict[item] = [state.values,
1278                                                               state.weights]
1279                   
1280            else:
1281                keys = self.model.getParamList()
1282                for item in keys:
1283                    if item in self.disp_list and \
1284                            not self.model.details.has_key(item):
1285                        self.model.details[item]=["",None,None]
1286                for k,v in self.state.disp_cb_dict.iteritems():
1287                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1288                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1289
1290        ##plotting range restore   
1291        self._reset_plotting_range(state)
1292
1293        ## smearing info  restore
1294        if hasattr(self,"enable_smearer"):
1295            ## set smearing value whether or not the data
1296            #contain the smearing info
1297            self.enable_smearer.SetValue(state.enable_smearer)
1298            self.disable_smearer.SetValue(state.disable_smearer)
1299            self.onSmear(event=None)           
1300        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1301        self.slit_smearer.SetValue(state.slit_smearer)
1302        ## we have two more options for smearing
1303        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1304        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1305       
1306        ## reset state of checkbox,textcrtl  and dispersity parameters value
1307        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1308        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1309       
1310        ## draw the model with previous parameters value
1311        self._onparamEnter_helper()
1312       
1313        ## reset context menu items
1314        self._reset_context_menu()
1315   
1316        ## set the value of the current state to the state given as parameter
1317        self.state = state.clone() 
1318        self._draw_model()
1319
1320    def _selectDlg(self):
1321        """
1322        open a dialog file to selected the customized dispersity
1323        """
1324        import os
1325        dlg = wx.FileDialog(self, "Choose a weight file",
1326                                self._default_save_location , "", 
1327                                "*.*", wx.OPEN)
1328        path = None
1329        if dlg.ShowModal() == wx.ID_OK:
1330            path = dlg.GetPath()
1331        dlg.Destroy()
1332        return path
1333
1334    def _reset_context_menu(self):
1335        """
1336        reset the context menu
1337        """
1338        for name, state in self.state.saved_states.iteritems():
1339            self.number_saved_state += 1
1340            ## Add item in the context menu
1341            id = wx.NewId()
1342            msg = 'Save model and state %g' % self.number_saved_state
1343            self.popUpMenu.Append(id, name, msg)
1344            wx.EVT_MENU(self, id, self.onResetModel)
1345   
1346    def _reset_plotting_range(self, state):
1347        """
1348        Reset the plotting range to a given state
1349        """
1350        # if self.check_invalid_panel():
1351        #    return
1352        self.qmin_tctrl.SetValue(str(state.qmin))
1353        self.qmax.SetValue(str(state.qmax)) 
1354
1355    def _save_typeOfmodel(self):
1356        """
1357        save radiobutton containing the type model that can be selected
1358        """
1359        self.state.shape_rbutton = self.shape_rbutton.GetValue()
1360        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
1361        self.state.struct_rbutton = self.struct_rbutton.GetValue()
1362        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
1363        self.state.structurebox= self.structurebox.GetCurrentSelection()
1364        self.state.formfactorbox = self.formfactorbox.GetCurrentSelection()
1365       
1366        #self._undo.Enable(True)
1367        ## post state to fit panel
1368        event = PageInfoEvent(page = self)
1369        wx.PostEvent(self.parent, event)
1370       
1371    def _save_plotting_range(self ):
1372        """
1373        save the state of plotting range
1374        """
1375        self.state.qmin = self.qmin_x
1376        self.state.qmax = self.qmax_x
1377        self.state.npts = self.npts_x
1378           
1379    def _onparamEnter_helper(self):
1380        """
1381        check if values entered by the user are changed and valid to replot
1382        model
1383        """
1384        # Flag to register when a parameter has changed.   
1385        is_modified = False
1386        self.fitrange = True
1387        is_2Ddata = False
1388        #self._undo.Enable(True)
1389        # check if 2d data
1390        if self.data.__class__.__name__ == "Data2D":
1391            is_2Ddata = True
1392        if self.model !=None:
1393            try:
1394                is_modified = self._check_value_enter(self.fittable_param,
1395                                                     is_modified)
1396                is_modified = self._check_value_enter(self.fixed_param,
1397                                                      is_modified)
1398                is_modified = self._check_value_enter(self.parameters,
1399                                                      is_modified) 
1400            except:
1401                pass
1402            #if is_modified:
1403
1404            # Here we should check whether the boundaries have been modified.
1405            # If qmin and qmax have been modified, update qmin and qmax and
1406            # set the is_modified flag to True
1407            if self._validate_qrange(self.qmin_tcrl, self.qmax):
1408                tempmin = float(self.qmin_tcrl.GetValue())
1409                if tempmin != self.qmin_x:
1410                    self.qmin_x = tempmin
1411                    is_modified = True
1412                tempmax = float(self.qmax.GetValue())
1413                if tempmax != self.qmax_x:
1414                    self.qmax_x = tempmax
1415                    is_modified = True
1416           
1417                if is_2Ddata:
1418                    # set mask   
1419                    is_modified = self._validate_Npts()
1420                   
1421            else:
1422                self.fitrange = False   
1423
1424            ## if any value is modify draw model with new value
1425            if not self.fitrange:
1426                #self.btFit.Disable()
1427                if is_2Ddata: self.btEditMask.Disable()
1428            else:
1429                #self.btFit.Enable(True)
1430                if is_2Ddata: self.btEditMask.Enable(True)
1431
1432            if is_modified and self.fitrange:
1433                self.state_change= True
1434                self._draw_model() 
1435                self.Refresh()
1436        return is_modified
1437   
1438    def _update_paramv_on_fit(self):
1439        """
1440        make sure that update param values just before the fitting
1441        """
1442        #flag for qmin qmax check values
1443        flag = True
1444        self.fitrange = True
1445        is_modified = False
1446
1447        wx.PostEvent(self._manager.parent, StatusEvent(status=" \
1448        updating ... ",type="update"))
1449
1450        ##So make sure that update param values on_Fit.
1451        #self._undo.Enable(True)
1452        if self.model !=None:           
1453            ##Check the values
1454            self._check_value_enter( self.fittable_param ,is_modified)
1455            self._check_value_enter( self.fixed_param ,is_modified)
1456            self._check_value_enter( self.parameters ,is_modified)
1457
1458            # If qmin and qmax have been modified, update qmin and qmax and
1459             # Here we should check whether the boundaries have been modified.
1460            # If qmin and qmax have been modified, update qmin and qmax and
1461            # set the is_modified flag to True
1462            self.fitrange = self._validate_qrange(self.qmin_tcrl, self.qmax)
1463            if self.fitrange:
1464                tempmin = float(self.qmin_tcrl.GetValue())
1465                if tempmin != self.qmin_x:
1466                    self.qmin_x = tempmin
1467                tempmax = float(self.qmax.GetValue())
1468                if tempmax != self.qmax_x:
1469                    self.qmax_x = tempmax
1470                if tempmax == tempmin:
1471                    flag = False   
1472                temp_smearer = None
1473                if not self.disable_smearer.GetValue():
1474                    temp_smearer= self.current_smearer
1475                    if self.slit_smearer.GetValue():
1476                        flag = self.update_slit_smear()
1477                    elif self.pinhole_smearer.GetValue():
1478                        flag = self.update_pinhole_smear()
1479                    else:
1480                        self._manager.set_smearer(smearer=temp_smearer,
1481                                                  id=self.id,
1482                                                     qmin=float(self.qmin_x),
1483                                                      qmax=float(self.qmax_x),
1484                                                      draw=False)
1485                elif not self._is_2D():
1486                    self._manager.set_smearer(smearer=temp_smearer,
1487                                              qmin=float(self.qmin_x),
1488                                              id=self.id, 
1489                                                 qmax= float(self.qmax_x))
1490                    index_data = ((self.qmin_x <= self.data.x)&\
1491                                  (self.data.x <= self.qmax_x))
1492                    val = str(len(self.data.x[index_data==True]))
1493                    self.Npts_fit.SetValue(val)
1494                    flag = True
1495                if self._is_2D():
1496                    # only 2D case set mask   
1497                    flag = self._validate_Npts()
1498                    if not flag:
1499                        return flag
1500            else: flag = False
1501        else: 
1502            flag = False
1503
1504        #For invalid q range, disable the mask editor and fit button, vs.   
1505        if not self.fitrange:
1506            #self.btFit.Disable()
1507            if self._is_2D():self.btEditMask.Disable()
1508        else:
1509            #self.btFit.Enable(True)
1510            if self._is_2D():self.btEditMask.Enable(True)
1511
1512        if not flag:
1513            msg = "Cannot Plot or Fit :Must select a "
1514            msg += " model or Fitting range is not valid!!!  "
1515            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
1516       
1517        self.save_current_state()
1518   
1519        return flag                           
1520               
1521    def _is_modified(self, is_modified):
1522        """
1523        return to self._is_modified
1524        """
1525        return is_modified
1526                       
1527    def _reset_parameters_state(self, listtorestore, statelist):
1528        """
1529        Reset the parameters at the given state
1530        """
1531        if len(statelist) == 0 or len(listtorestore) == 0:
1532            return
1533        if len(statelist) !=  len(listtorestore):
1534            return
1535
1536        for j in range(len(listtorestore)):
1537            item_page = listtorestore[j]
1538            item_page_info = statelist[j]
1539            ##change the state of the check box for simple parameters
1540            if item_page[0]!=None:   
1541                item_page[0].SetValue(item_page_info[0])
1542            if item_page[2]!=None:
1543                item_page[2].SetValue(item_page_info[2])
1544            if item_page[3]!=None:
1545                ## show or hide text +/-
1546                if item_page_info[2]:
1547                    item_page[3].Show(True)
1548                else:
1549                    item_page[3].Hide()
1550            if item_page[4]!=None:
1551                ## show of hide the text crtl for fitting error
1552                if item_page_info[4][0]:
1553                    item_page[4].Show(True)
1554                    item_page[4].SetValue(item_page_info[4][1])
1555                else:
1556                    item_page[3].Hide()
1557            if item_page[5]!=None:
1558                ## show of hide the text crtl for fitting error
1559                if item_page_info[5][0]:
1560                    item_page[5].Show(True)
1561                    item_page[5].SetValue(item_page_info[5][1])
1562                else:
1563                    item_page[5].Hide()
1564                   
1565            if item_page[6]!=None:
1566                ## show of hide the text crtl for fitting error
1567                if item_page_info[6][0]:
1568                    item_page[6].Show(True)
1569                    item_page[6].SetValue(item_page_info[6][1])
1570                else:
1571                    item_page[6].Hide()
1572                                     
1573    def _copy_parameters_state(self, listtocopy, statelist):
1574        """
1575        copy the state of button
1576       
1577        :param listtocopy: the list of check button to copy
1578        :param statelist: list of state object to store the current state
1579       
1580        """
1581        if len(listtocopy)==0:
1582            return
1583       
1584        for item in listtocopy:
1585 
1586            checkbox_state = None
1587            if item[0]!= None:
1588                checkbox_state= item[0].GetValue()
1589            parameter_name = item[1]
1590            parameter_value = None
1591            if item[2]!=None:
1592                parameter_value = item[2].GetValue()
1593            static_text = None
1594            if item[3]!=None:
1595                static_text = item[3].IsShown()
1596            error_value = None
1597            error_state = None
1598            if item[4]!= None:
1599                error_value = item[4].GetValue()
1600                error_state = item[4].IsShown()
1601               
1602            min_value = None
1603            min_state = None
1604            if item[5]!= None:
1605                min_value = item[5].GetValue()
1606                min_state = item[5].IsShown()
1607               
1608            max_value = None
1609            max_state = None
1610            if item[6]!= None:
1611                max_value = item[6].GetValue()
1612                max_state = item[6].IsShown()
1613            unit=None
1614            if item[7]!=None:
1615                unit = item[7].GetLabel()
1616               
1617            statelist.append([checkbox_state, parameter_name, parameter_value,
1618                              static_text ,[error_state, error_value],
1619                                [min_state, min_value],
1620                                [max_state, max_value], unit])
1621           
1622    def _set_model_sizer_selection(self, model):
1623        """
1624        Display the sizer according to the type of the current model
1625        """
1626        if model == None:
1627            return
1628        if hasattr(model ,"s_model"):
1629           
1630            class_name = model.s_model.__class__
1631            name = model.s_model.name
1632            flag = (name != "NoStructure")
1633            if flag and \
1634                (class_name in self.model_list_box["Structure Factors"]):
1635                self.structurebox.Show()
1636                self.text2.Show()               
1637                self.structurebox.Enable()
1638                self.text2.Enable()
1639                items = self.structurebox.GetItems()
1640                self.sizer1.Layout()
1641               
1642                for i in range(len(items)):
1643                    if items[i]== str(name):
1644                        self.structurebox.SetSelection(i)
1645                        break
1646                   
1647        if hasattr(model ,"p_model"):
1648            class_name = model.p_model.__class__
1649            name = model.p_model.name
1650            self.formfactorbox.Clear()
1651           
1652            for k, list in self.model_list_box.iteritems():
1653                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1654                    self.shape_rbutton.SetValue(True)
1655                    ## fill the form factor list with new model
1656                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1657                    items = self.formfactorbox.GetItems()
1658                    ## set comboxbox to the selected item
1659                    for i in range(len(items)):
1660                        if items[i]== str(name):
1661                            self.formfactorbox.SetSelection(i)
1662                            break
1663                    return
1664                elif k == "Shape-Independent":
1665                    self.shape_indep_rbutton.SetValue(True)
1666                elif k == "Structure Factors":
1667                     self.struct_rbutton.SetValue(True)
1668                elif  k == "Multi-Functions":
1669                    continue
1670                else:
1671                    self.plugin_rbutton.SetValue(True)
1672               
1673                if class_name in list:
1674                    ## fill the form factor list with new model
1675                    self._populate_box(self.formfactorbox, list)
1676                    items = self.formfactorbox.GetItems()
1677                    ## set comboxbox to the selected item
1678                    for i in range(len(items)):
1679                        if items[i]== str(name):
1680                            self.formfactorbox.SetSelection(i)
1681                            break
1682                    break
1683        else:
1684
1685            ## Select the model from the menu
1686            class_name = model.__class__
1687            name = model.name
1688            self.formfactorbox.Clear()
1689            items = self.formfactorbox.GetItems()
1690   
1691            for k, list in self.model_list_box.iteritems():         
1692                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1693                    if class_name in self.model_list_box["P(Q)*S(Q)"]:
1694                        self.structurebox.Show()
1695                        self.text2.Show()
1696                        self.structurebox.Enable()
1697                        self.structurebox.SetSelection(0)
1698                        self.text2.Enable()
1699                    else:
1700                        self.structurebox.Hide()
1701                        self.text2.Hide()
1702                        self.structurebox.Disable()
1703                        self.structurebox.SetSelection(0)
1704                        self.text2.Disable()
1705                       
1706                    self.shape_rbutton.SetValue(True)
1707                    ## fill the form factor list with new model
1708                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1709                    items = self.formfactorbox.GetItems()
1710                    ## set comboxbox to the selected item
1711                    for i in range(len(items)):
1712                        if items[i]== str(name):
1713                            self.formfactorbox.SetSelection(i)
1714                            break
1715                    return
1716                elif k == "Shape-Independent":
1717                    self.shape_indep_rbutton.SetValue(True)
1718                elif k == "Structure Factors":
1719                    self.struct_rbutton.SetValue(True)
1720                elif  k == "Multi-Functions":
1721                    continue
1722                else:
1723                    self.plugin_rbutton.SetValue(True)
1724                if class_name in list:
1725                    self.structurebox.SetSelection(0)
1726                    self.structurebox.Disable()
1727                    self.text2.Disable()                   
1728                    ## fill the form factor list with new model
1729                    self._populate_box(self.formfactorbox, list)
1730                    items = self.formfactorbox.GetItems()
1731                    ## set comboxbox to the selected item
1732                    for i in range(len(items)):
1733                        if items[i]== str(name):
1734                            self.formfactorbox.SetSelection(i)
1735                            break
1736                    break
1737   
1738    def _draw_model(self):
1739        """
1740        Method to draw or refresh a plotted model.
1741        The method will use the data member from the model page
1742        to build a call to the fitting perspective manager.
1743        """
1744        #if self.check_invalid_panel():
1745        #    return
1746        if self.model !=None:
1747            temp_smear=None
1748            if hasattr(self, "enable_smearer"):
1749                if not self.disable_smearer.GetValue():
1750                    temp_smear= self.current_smearer
1751            toggle_mode_on = self.model_view.IsEnabled()
1752            self._manager.draw_model(self.model, 
1753                                    data=self.data,
1754                                    smearer= temp_smear,
1755                                    qmin=float(self.qmin_x), 
1756                                    qmax=float(self.qmax_x),
1757                                    qstep= float(self.npts_x),
1758                                    id=self.id,
1759                                    toggle_mode_on=toggle_mode_on, 
1760                                    state = self.state,
1761                                    enable2D=self.enable2D)
1762       
1763       
1764    def _on_show_sld(self, event=None):
1765        """
1766        Plot SLD profile
1767        """
1768        # get profile data
1769        x,y=self.model.getProfile()
1770
1771        from danse.common.plottools import Data1D
1772        #from sans.perspectives.theory.profile_dialog import SLDPanel
1773        from sans.guiframe.local_perspectives.plotting.profile_dialog \
1774        import SLDPanel
1775        sld_data = Data1D(x,y)
1776        sld_data.name = 'SLD'
1777        sld_data.axes = self.sld_axes
1778        self.panel = SLDPanel(self, data=sld_data,axes =self.sld_axes,id =-1 )
1779        self.panel.ShowModal()   
1780       
1781    def _set_multfactor_combobox(self, multiplicity=10):   
1782        """
1783        Set comboBox for muitfactor of CoreMultiShellModel
1784        :param multiplicit: no. of multi-functionality
1785        """
1786        # build content of the combobox
1787        for idx in range(0,multiplicity):
1788            self.multifactorbox.Append(str(idx),int(idx))
1789            #self.multifactorbox.SetSelection(1)
1790        self._hide_multfactor_combobox()
1791       
1792    def _show_multfactor_combobox(self):   
1793        """
1794        Show the comboBox of muitfactor of CoreMultiShellModel
1795        """ 
1796        if not self.mutifactor_text.IsShown():
1797            self.mutifactor_text.Show(True)
1798            self.mutifactor_text1.Show(True)
1799        if not self.multifactorbox.IsShown():
1800            self.multifactorbox.Show(True) 
1801             
1802    def _hide_multfactor_combobox(self):   
1803        """
1804        Hide the comboBox of muitfactor of CoreMultiShellModel
1805        """ 
1806        if self.mutifactor_text.IsShown():
1807            self.mutifactor_text.Hide()
1808            self.mutifactor_text1.Hide()
1809        if self.multifactorbox.IsShown():
1810            self.multifactorbox.Hide()   
1811
1812       
1813    def _show_combox_helper(self):
1814        """
1815        Fill panel's combo box according to the type of model selected
1816        """
1817        self.model_list_box = self.parent.update_model_list()
1818        if self.shape_rbutton.GetValue():
1819            ##fill the combobox with form factor list
1820            self.structurebox.SetSelection(0)
1821            self.structurebox.Disable()
1822            self.formfactorbox.Clear()
1823            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
1824        if self.shape_indep_rbutton.GetValue():
1825            ##fill the combobox with shape independent  factor list
1826            self.structurebox.SetSelection(0)
1827            self.structurebox.Disable()
1828            self.formfactorbox.Clear()
1829            self._populate_box( self.formfactorbox,
1830                                self.model_list_box["Shape-Independent"])
1831        if self.struct_rbutton.GetValue():
1832            ##fill the combobox with structure factor list
1833            self.structurebox.SetSelection(0)
1834            self.structurebox.Disable()
1835            self.formfactorbox.Clear()
1836            self._populate_box( self.formfactorbox,
1837                                self.model_list_box["Structure Factors"])
1838        if self.plugin_rbutton.GetValue():
1839            ##fill the combobox with form factor list
1840            self.structurebox.Disable()
1841            self.formfactorbox.Clear()
1842            self._populate_box( self.formfactorbox,
1843                                self.model_list_box["Customized Models"])
1844       
1845    def _show_combox(self, event=None):
1846        """
1847        Show combox box associate with type of model selected
1848        """
1849        #if self.check_invalid_panel():
1850        #    self.shape_rbutton.SetValue(True)
1851        #    return
1852
1853        self._show_combox_helper()
1854        self._on_select_model(event=None)
1855        self._save_typeOfmodel()
1856        self.sizer4_4.Layout()
1857        self.sizer4.Layout()
1858        self.Layout()
1859        self.Refresh()
1860 
1861    def _populate_box(self, combobox, list):
1862        """
1863        fill combox box with dict item
1864       
1865        :param list: contains item to fill the combox
1866            item must model class
1867        """
1868        for models in list:
1869            model= models()
1870            name = model.__class__.__name__
1871            if models.__name__!="NoStructure":
1872                if hasattr(model, "name"):
1873                    name = model.name
1874                combobox.Append(name,models)
1875        return 0
1876   
1877    def _onQrangeEnter(self, event):
1878        """
1879        Check validity of value enter in the Q range field
1880       
1881        """
1882        tcrtl = event.GetEventObject()
1883        #Clear msg if previously shown.
1884        msg = ""
1885        wx.PostEvent(self.parent, StatusEvent(status=msg))
1886        # Flag to register when a parameter has changed.
1887        is_modified = False
1888        if tcrtl.GetValue().lstrip().rstrip() != "":
1889            try:
1890                value = float(tcrtl.GetValue())
1891                tcrtl.SetBackgroundColour(wx.WHITE)
1892                # If qmin and qmax have been modified, update qmin and qmax
1893                if self._validate_qrange(self.qmin_tcrl, self.qmax):
1894                    tempmin = float(self.qmin_tcrl.GetValue())
1895                    if tempmin != self.qmin_x:
1896                        self.qmin_x = tempmin
1897                    tempmax = float(self.qmax.GetValue())
1898                    if tempmax != self.qmax_x:
1899                        self.qmax_x = tempmax
1900                else:
1901                    tcrtl.SetBackgroundColour("pink")
1902                    msg = "Model Error:wrong value entered : %s" % sys.exc_value
1903                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1904                    return 
1905            except:
1906                tcrtl.SetBackgroundColour("pink")
1907                msg = "Model Error:wrong value entered : %s" % sys.exc_value
1908                wx.PostEvent(self.parent, StatusEvent(status=msg))
1909                return 
1910            #Check if # of points for theory model are valid(>0).
1911            if self.npts != None:
1912                if check_float(self.npts):
1913                    temp_npts = float(self.npts.GetValue())
1914                    if temp_npts !=  self.num_points:
1915                        self.num_points = temp_npts
1916                        is_modified = True
1917                else:
1918                    msg = "Cannot Plot :No npts in that Qrange!!!  "
1919                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1920        else:
1921           tcrtl.SetBackgroundColour("pink")
1922           msg = "Model Error:wrong value entered!!!"
1923           wx.PostEvent(self.parent, StatusEvent(status=msg))
1924        #self._undo.Enable(True)
1925        self.save_current_state()
1926        event = PageInfoEvent(page=self)
1927        wx.PostEvent(self.parent, event)
1928        self.state_change = False
1929        #Draw the model for a different range
1930        self._draw_model()
1931                   
1932    def _theory_qrange_enter(self, event):
1933        """
1934        Check validity of value enter in the Q range field
1935        """
1936       
1937        tcrtl= event.GetEventObject()
1938        #Clear msg if previously shown.
1939        msg= ""
1940        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
1941        # Flag to register when a parameter has changed.
1942        is_modified = False
1943        if tcrtl.GetValue().lstrip().rstrip()!="":
1944            try:
1945                value = float(tcrtl.GetValue())
1946                tcrtl.SetBackgroundColour(wx.WHITE)
1947
1948                # If qmin and qmax have been modified, update qmin and qmax
1949                if self._validate_qrange(self.theory_qmin, self.theory_qmax):
1950                    tempmin = float(self.theory_qmin.GetValue())
1951                    if tempmin != self.theory_qmin_x:
1952                        self.theory_qmin_x = tempmin
1953                    tempmax = float(self.theory_qmax.GetValue())
1954                    if tempmax != self.qmax_x:
1955                        self.theory_qmax_x = tempmax
1956                else:
1957                    tcrtl.SetBackgroundColour("pink")
1958                    msg= "Model Error:wrong value entered : %s"% sys.exc_value
1959                    wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
1960                    return 
1961            except:
1962                tcrtl.SetBackgroundColour("pink")
1963                msg= "Model Error:wrong value entered : %s"% sys.exc_value
1964                wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
1965                return 
1966            #Check if # of points for theory model are valid(>0).
1967            if self.theory_npts != None:
1968                if check_float(self.theory_npts):
1969                    temp_npts = float(self.theory_npts.GetValue())
1970                    if temp_npts !=  self.num_points:
1971                        self.num_points = temp_npts
1972                        is_modified = True
1973                else:
1974                    msg= "Cannot Plot :No npts in that Qrange!!!  "
1975                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
1976        else:
1977           tcrtl.SetBackgroundColour("pink")
1978           msg = "Model Error:wrong value entered!!!"
1979           wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
1980        #self._undo.Enable(True)
1981        self.save_current_state()
1982        event = PageInfoEvent(page = self)
1983        wx.PostEvent(self.parent, event)
1984        self.state_change= False
1985        #Draw the model for a different range
1986        self._draw_model()
1987                   
1988    def _on_select_model_helper(self): 
1989        """
1990        call back for model selection
1991        """
1992        ## reset dictionary containing reference to dispersion
1993        self._disp_obj_dict = {}
1994        self.disp_cb_dict ={}
1995       
1996        f_id = self.formfactorbox.GetCurrentSelection()
1997        #For MAC
1998        form_factor = None
1999        if f_id >= 0:
2000            form_factor = self.formfactorbox.GetClientData(f_id)
2001
2002        if not form_factor in  self.model_list_box["multiplication"]:
2003            self.structurebox.Hide()
2004            self.text2.Hide()           
2005            self.structurebox.Disable()
2006            self.structurebox.SetSelection(0)
2007            self.text2.Disable()
2008        else:
2009            self.structurebox.Show()
2010            self.text2.Show()
2011            self.structurebox.Enable()
2012            self.text2.Enable()
2013           
2014        if form_factor != None:   
2015            # set multifactor for Mutifunctional models   
2016            if form_factor().__class__ in self.model_list_box["Multi-Functions"]:
2017                m_id = self.multifactorbox.GetCurrentSelection()
2018                multiplicity = form_factor().multiplicity_info[0]
2019                self.multifactorbox.Clear()
2020                #self.mutifactor_text.SetLabel(form_factor().details[])
2021                self._set_multfactor_combobox(multiplicity)
2022                self._show_multfactor_combobox()
2023                #ToDo:  this info should be called directly from the model
2024                text = form_factor().multiplicity_info[1]#'No. of Shells: '
2025
2026                #self.mutifactor_text.Clear()
2027                self.mutifactor_text.SetLabel(text)
2028                if m_id > multiplicity -1:
2029                    # default value
2030                    m_id = 1
2031                   
2032                self.multi_factor = self.multifactorbox.GetClientData(m_id)
2033                if self.multi_factor == None: self.multi_factor =0
2034                form_factor = form_factor(int(self.multi_factor))
2035                self.multifactorbox.SetSelection(m_id)
2036                # Check len of the text1 and max_multiplicity
2037                text = ''
2038                if form_factor.multiplicity_info[0] == len(form_factor.multiplicity_info[2]):
2039                    text = form_factor.multiplicity_info[2][self.multi_factor]
2040                self.mutifactor_text1.SetLabel(text)
2041                # Check if model has  get sld profile.
2042                if len(form_factor.multiplicity_info[3]) > 0:
2043                    self.sld_axes = form_factor.multiplicity_info[3]
2044                    self.show_sld_button.Show(True)
2045                else:
2046                    self.sld_axes = ""
2047
2048            else:
2049                self._hide_multfactor_combobox()
2050                self.show_sld_button.Hide()
2051                form_factor = form_factor()
2052                self.multi_factor = None
2053        else:
2054            self._hide_multfactor_combobox()
2055            self.show_sld_button.Hide()
2056            self.multi_factor = None 
2057             
2058        s_id = self.structurebox.GetCurrentSelection()
2059        struct_factor = self.structurebox.GetClientData( s_id )
2060       
2061        if  struct_factor !=None:
2062            from sans.models.MultiplicationModel import MultiplicationModel
2063            self.model= MultiplicationModel(form_factor,struct_factor())
2064           
2065        else:
2066            if form_factor != None:
2067                self.model= form_factor
2068            else:
2069                self.model = None
2070                return self.model
2071           
2072
2073        ## post state to fit panel
2074        self.state.parameters =[]
2075        self.state.model =self.model
2076        self.state.qmin = self.qmin_x
2077        self.state.multi_factor = self.multi_factor
2078        self.disp_list =self.model.getDispParamList()
2079        self.state.disp_list = self.disp_list
2080        self.Layout()     
2081       
2082    def _validate_qrange(self, qmin_ctrl, qmax_ctrl):
2083        """
2084        Verify that the Q range controls have valid values
2085        and that Qmin < Qmax.
2086       
2087        :param qmin_ctrl: text control for Qmin
2088        :param qmax_ctrl: text control for Qmax
2089       
2090        :return: True is the Q range is value, False otherwise
2091       
2092        """
2093        qmin_validity = check_float(qmin_ctrl)
2094        qmax_validity = check_float(qmax_ctrl)
2095        if not (qmin_validity and qmax_validity):
2096            return False
2097        else:
2098            qmin = float(qmin_ctrl.GetValue())
2099            qmax = float(qmax_ctrl.GetValue())
2100            if qmin <= qmax:
2101                #Make sure to set both colours white. 
2102                qmin_ctrl.SetBackgroundColour(wx.WHITE)
2103                qmin_ctrl.Refresh()
2104                qmax_ctrl.SetBackgroundColour(wx.WHITE)
2105                qmax_ctrl.Refresh()
2106            else:
2107                qmin_ctrl.SetBackgroundColour("pink")
2108                qmin_ctrl.Refresh()
2109                qmax_ctrl.SetBackgroundColour("pink")
2110                qmax_ctrl.Refresh()
2111                msg= "Invalid Q range: Q min must be smaller than Q max"
2112                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2113                return False
2114        return True
2115   
2116    def _validate_Npts(self): 
2117        """
2118        Validate the number of points for fitting is more than 10 points.
2119        If valid, setvalues Npts_fit otherwise post msg.
2120        """
2121        #default flag
2122        flag = True
2123
2124        # q value from qx and qy
2125        radius= numpy.sqrt( self.data.qx_data * self.data.qx_data + 
2126                            self.data.qy_data * self.data.qy_data )
2127        #get unmasked index
2128        index_data = (float(self.qmin_tcrl.GetValue()) <= radius) & \
2129                        (radius <= float(self.qmax.GetValue()))
2130        index_data = (index_data) & (self.data.mask) 
2131        index_data = (index_data) & (numpy.isfinite(self.data.data))
2132
2133        if len(index_data[index_data]) < 10:
2134            # change the color pink.
2135            self.qmin_tcrl.SetBackgroundColour("pink")
2136            self.qmin_tcrl.Refresh()
2137            self.qmax.SetBackgroundColour("pink")
2138            self.qmax.Refresh()
2139            msg= "Cannot Plot :No or too little npts in that data range!!!  "
2140            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2141            self.fitrange = False
2142            flag = False
2143        else:
2144            self.Npts_fit.SetValue(str(len(self.data.mask[index_data==True])))
2145            self.fitrange = True
2146           
2147        return flag
2148   
2149    def _check_value_enter(self, list, modified):
2150        """
2151        :param list: model parameter and panel info
2152        :Note: each item of the list should be as follow:
2153            item=[check button state, parameter's name,
2154                paramater's value, string="+/-",
2155                parameter's error of fit,
2156                parameter's minimum value,
2157                parrameter's maximum value ,
2158                parameter's units]
2159        """ 
2160        is_modified =  modified
2161        if len(list)==0:
2162            return is_modified
2163        for item in list:
2164            #skip angle parameters for 1D
2165            if self.data.__class__.__name__ !="Data2D":
2166                if item in self.orientation_params:
2167                    continue
2168            #try:
2169            name = str(item[1])
2170           
2171            if string.find(name,".npts") ==-1 and string.find(name,".nsigmas")==-1:     
2172                ## check model parameters range             
2173                param_min= None
2174                param_max= None
2175               
2176                ## check minimun value
2177                if item[5]!= None and item[5]!= "":
2178                    if item[5].GetValue().lstrip().rstrip()!="":
2179                        try:
2180                           
2181                            param_min = float(item[5].GetValue())
2182                            if not self._validate_qrange(item[5],item[2]):
2183                                if numpy.isfinite(param_min):
2184                                    item[2].SetValue(format_number(param_min))
2185                           
2186                            item[5].SetBackgroundColour(wx.WHITE)
2187                            item[2].SetBackgroundColour(wx.WHITE)
2188                                           
2189                        except:
2190                            msg = "Wrong Fit parameter range entered "
2191                            wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2192                            raise ValueError, msg
2193                        is_modified = True
2194                ## check maximum value
2195                if item[6]!= None and item[6]!= "":
2196                    if item[6].GetValue().lstrip().rstrip()!="":
2197                        try:                         
2198                            param_max = float(item[6].GetValue())
2199                            if not self._validate_qrange(item[2],item[6]):
2200                                if numpy.isfinite(param_max):
2201                                    item[2].SetValue(format_number(param_max)) 
2202                           
2203                            item[6].SetBackgroundColour(wx.WHITE)
2204                            item[2].SetBackgroundColour(wx.WHITE)
2205                        except:
2206                            msg = "Wrong Fit parameter range entered "
2207                            wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2208                            raise ValueError, msg
2209                        is_modified = True
2210               
2211
2212                if param_min != None and param_max !=None:
2213                    if not self._validate_qrange(item[5], item[6]):
2214                        msg= "Wrong Fit range entered for parameter "
2215                        msg+= "name %s of model %s "%(name, self.model.name)
2216                        wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2217               
2218                if name in self.model.details.keys():   
2219                        self.model.details[name][1:3]= param_min,param_max
2220                        is_modified = True
2221             
2222                else:
2223                        self.model.details [name] = ["",param_min,param_max] 
2224                        is_modified = True
2225            try:     
2226                value= float(item[2].GetValue())
2227                item[2].SetBackgroundColour("white")
2228                # If the value of the parameter has changed,
2229                # +update the model and set the is_modified flag
2230                if value != self.model.getParam(name) and numpy.isfinite(value):
2231                    self.model.setParam(name,value)
2232                    is_modified = True   
2233            except:
2234                item[2].SetBackgroundColour("pink")
2235                msg = "Wrong Fit parameter value entered "
2236                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2237               
2238        return is_modified
2239       
2240 
2241    def _set_dipers_Param(self, event):
2242        """
2243        respond to self.enable_disp and self.disable_disp radio box.
2244        The dispersity object is reset inside the model into Gaussian.
2245        When the user select yes , this method display a combo box for more selection
2246        when the user selects No,the combo box disappears.
2247        Redraw the model with the default dispersity (Gaussian)
2248        """
2249        #if self.check_invalid_panel():
2250        #    return
2251        ## On selction if no model exists.
2252        if self.model ==None:
2253            self.disable_disp.SetValue(True)
2254            msg="Please select a Model first..."
2255            wx.MessageBox(msg, 'Info')
2256            wx.PostEvent(self._manager.parent, StatusEvent(status=\
2257                            "Polydispersion: %s"%msg))
2258            return
2259
2260        self._reset_dispersity()
2261   
2262        if self.model ==None:
2263            self.model_disp.Hide()
2264            self.disp_box.Hide()
2265            self.sizer4_4.Clear(True)
2266            return
2267
2268        if self.enable_disp.GetValue():
2269            self.model_disp.Show(True)
2270            self.disp_box.Show(True)
2271            ## layout for model containing no dispersity parameters
2272           
2273            self.disp_list= self.model.getDispParamList()
2274             
2275            if len(self.disp_list)==0 and len(self.disp_cb_dict)==0:
2276                self._layout_sizer_noDipers() 
2277            else:
2278                ## set gaussian sizer
2279                self._on_select_Disp(event=None)
2280        else:
2281            self.model_disp.Hide()
2282            self.disp_box.Hide()
2283            self.disp_box.SetSelection(0) 
2284            self.sizer4_4.Clear(True)
2285           
2286        ## post state to fit panel
2287        self.save_current_state()
2288        if event !=None:
2289            #self._undo.Enable(True)
2290            event = PageInfoEvent(page = self)
2291            wx.PostEvent(self.parent, event)
2292        #draw the model with the current dispersity
2293        self._draw_model()
2294        self.sizer4_4.Layout()
2295        self.sizer5.Layout()
2296        self.Layout()
2297        self.Refresh()     
2298         
2299       
2300    def _layout_sizer_noDipers(self):
2301        """
2302        Draw a sizer with no dispersity info
2303        """
2304        ix=0
2305        iy=1
2306        self.fittable_param=[]
2307        self.fixed_param=[]
2308        self.orientation_params_disp=[]
2309       
2310        self.model_disp.Hide()
2311        self.disp_box.Hide()
2312        self.sizer4_4.Clear(True)
2313        text = "No polydispersity available for this model"
2314        model_disp = wx.StaticText(self, -1, text)
2315        self.sizer4_4.Add(model_disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
2316        self.sizer4_4.Layout()
2317        self.sizer4.Layout()
2318   
2319    def _reset_dispersity(self):
2320        """
2321        put gaussian dispersity into current model
2322        """
2323        if len(self.param_toFit)>0:
2324            for item in self.fittable_param:
2325                if item in self.param_toFit:
2326                    self.param_toFit.remove(item)
2327
2328            for item in self.orientation_params_disp:
2329                if item in self.param_toFit:
2330                    self.param_toFit.remove(item)
2331         
2332        self.fittable_param=[]
2333        self.fixed_param=[]
2334        self.orientation_params_disp=[]
2335        self.values=[]
2336        self.weights=[]
2337     
2338        from sans.models.dispersion_models import GaussianDispersion, ArrayDispersion
2339        if len(self.disp_cb_dict)==0:
2340            self.save_current_state()
2341            self.sizer4_4.Clear(True)
2342            self.Layout()
2343 
2344            return 
2345        if (len(self.disp_cb_dict)>0) :
2346            for p in self.disp_cb_dict:
2347                # The parameter was un-selected. Go back to Gaussian model (with 0 pts)                   
2348                disp_model = GaussianDispersion()
2349               
2350                self._disp_obj_dict[p] = disp_model
2351                # Set the new model as the dispersion object for the selected parameter
2352                try:
2353                   self.model.set_dispersion(p, disp_model)
2354                except:
2355
2356                    pass
2357
2358        ## save state into
2359        self.save_current_state()
2360        self.Layout() 
2361        self.Refresh()
2362                 
2363    def _on_select_Disp(self,event):
2364        """
2365        allow selecting different dispersion
2366        self.disp_list should change type later .now only gaussian
2367        """
2368        n = self.disp_box.GetCurrentSelection()
2369        name = self.disp_box.GetValue()
2370        dispersity= self.disp_box.GetClientData(n)
2371        self.disp_name = name
2372       
2373        if name.lower() == "array":
2374            self._set_sizer_arraydispersion()
2375        else:
2376            self._set_sizer_dispersion(dispersity= dispersity)
2377           
2378        self.state.disp_box= n
2379        ## Redraw the model
2380        self._draw_model() 
2381        #self._undo.Enable(True)
2382        event = PageInfoEvent(page = self)
2383        wx.PostEvent(self.parent, event)
2384       
2385        self.sizer4_4.Layout()
2386        self.sizer4.Layout()
2387   
2388    def _set_sizer_arraydispersion(self):
2389        """
2390        draw sizer with array dispersity  parameters
2391        """
2392       
2393        if len(self.param_toFit)>0:
2394            for item in self.fittable_param:
2395                if item in self.param_toFit:
2396                    self.param_toFit.remove(item)
2397            for item in self.orientation_params_disp:
2398                if item in self.param_toFit:
2399                    self.param_toFit.remove(item)
2400        for item in self.model.details.keys():
2401            if item in self.model.fixed:
2402                del self.model.details [item]                           
2403
2404        self.fittable_param=[]
2405        self.fixed_param=[]
2406        self.orientation_params_disp=[]
2407        self.sizer4_4.Clear(True) 
2408        self._reset_dispersity()
2409        ix=0
2410        iy=1     
2411        disp1 = wx.StaticText(self, -1, 'Array Dispersion')
2412        self.sizer4_4.Add(disp1,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
2413       
2414        # Look for model parameters to which we can apply an ArrayDispersion model
2415        # Add a check box for each parameter.
2416        self.disp_cb_dict = {}
2417        ix+=1 
2418        self.noDisper_rbox = wx.RadioButton(self, -1,"None", (10, 10),style= wx.RB_GROUP)
2419        self.Bind(wx.EVT_RADIOBUTTON,self.select_disp_angle , id=self.noDisper_rbox.GetId())
2420        #MAC needs SetValue
2421        self.noDisper_rbox.SetValue(True)
2422        self.sizer4_4.Add(self.noDisper_rbox, (iy, ix),
2423                           (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
2424       
2425        for p in self.model.dispersion.keys():
2426            if not p in self.model.orientation_params:
2427                ix+=1 
2428                self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10))
2429                self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
2430                self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId())
2431                self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
2432       
2433        for p in self.model.dispersion.keys():
2434            if p in self.model.orientation_params:
2435                ix+=1 
2436                self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10))
2437                self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
2438                if not (self.enable2D or self.data.__class__.__name__ =="Data2D"):
2439                    self.disp_cb_dict[p].Hide()
2440                else:
2441                    self.disp_cb_dict[p].Show(True)
2442                self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId())
2443                self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
2444
2445
2446        ix =0
2447        iy +=1 
2448        self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)       
2449        self.Layout()
2450
2451        self.state.orientation_params =[]
2452        self.state.orientation_params_disp =[]
2453        self.state.parameters =[]
2454        self.state.fittable_param =[]
2455        self.state.fixed_param =[]
2456       
2457        ## save checkbutton state and txtcrtl values
2458       
2459        self._copy_parameters_state(self.orientation_params,
2460                                     self.state.orientation_params)
2461
2462        self._copy_parameters_state(self.orientation_params_disp,
2463                                     self.state.orientation_params_disp)
2464       
2465        self._copy_parameters_state(self.parameters, self.state.parameters)
2466        self._copy_parameters_state(self.fittable_param, self.state.fittable_param)
2467        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
2468       
2469       
2470        ## post state to fit panel
2471        event = PageInfoEvent(page = self)
2472        wx.PostEvent(self.parent, event)
2473   
2474    def _lay_out(self):
2475        """
2476        returns self.Layout
2477       
2478        :Note: Mac seems to like this better when self.
2479            Layout is called after fitting.
2480        """
2481        self._sleep4sec()
2482        self.Layout()
2483        return 
2484   
2485    def _sleep4sec(self):
2486        """
2487            sleep for 1 sec only applied on Mac
2488            Note: This 1sec helps for Mac not to crash on self.:ayout after self._draw_model
2489        """
2490        if ON_MAC == True:
2491            time.sleep(1)
2492           
2493    def on_reset_clicked(self,event):
2494        """
2495        On 'Reset' button  for Q range clicked
2496        """
2497        flag = True
2498        #if self.check_invalid_panel():
2499        #    return
2500        ##For 3 different cases: Data2D, Data1D, and theory
2501        if self.data.__class__.__name__ == "Data2D":
2502            data_min= 0
2503            x= max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
2504            y= max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
2505            self.qmin_x = data_min
2506            self.qmax_x = math.sqrt(x*x + y*y)
2507            # check smearing
2508            if not self.disable_smearer.GetValue():
2509                temp_smearer= self.current_smearer
2510                ## set smearing value whether or not the data contain the smearing info
2511                if self.pinhole_smearer.GetValue():
2512                    flag = self.update_pinhole_smear()
2513                else:
2514                    flag = True
2515        elif self.data.__class__.__name__ != "Data2D":
2516            self.qmin_x = min(self.data.x)
2517            self.qmax_x = max(self.data.x)
2518            # check smearing
2519            if not self.disable_smearer.GetValue():
2520                temp_smearer= self.current_smearer
2521                ## set smearing value whether or not the data contain the smearing info
2522                if self.slit_smearer.GetValue():
2523                    flag = self.update_slit_smear()
2524                elif self.pinhole_smearer.GetValue():
2525                    flag = self.update_pinhole_smear()
2526                else:
2527                    flag = True
2528        else:
2529            self.qmin_x = _QMIN_DEFAULT
2530            self.qmax_x = _QMAX_DEFAULT
2531            self.num_points = _NPTS_DEFAULT           
2532            self.state.npts = self.num_points
2533           
2534        if flag == False:
2535            msg= "Cannot Plot :Must enter a number!!!  "
2536            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2537        else:
2538            # set relative text ctrs.
2539            self.qmin_tcrl.SetValue(str(self.qmin_x))
2540            self.qmax.SetValue(str(self.qmax_x))
2541            self.set_npts2fit()
2542            # At this point, some button and variables satatus (disabled?) should be checked
2543            # such as color that should be reset to white in case that it was pink.
2544            self._onparamEnter_helper()
2545
2546        self.save_current_state()
2547        self.state.qmin = self.qmin_x
2548        self.state.qmax = self.qmax_x
2549       
2550        #reset the q range values
2551        self._reset_plotting_range(self.state)
2552        #self.compute_chisqr(smearer=self.current_smearer)
2553        #Re draw plot
2554        self._draw_model()
2555
2556    def on_model_help_clicked(self,event):
2557        """
2558        on 'More details' button
2559        """
2560        from help_panel import  HelpWindow
2561       
2562        if self.model == None:
2563            name = 'FuncHelp'
2564        else:
2565            name = self.model.origin_name
2566
2567        frame = HelpWindow(None, -1,  pageToOpen="media/model_functions.html")   
2568        frame.Show(True)
2569        if frame.rhelp.HasAnchor(name):
2570            frame.rhelp.ScrollToAnchor(name)
2571        else:
2572           msg= "Model does not contains an available description "
2573           msg +="Please try searching in the Help window"
2574           wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))                   
2575               
Note: See TracBrowser for help on using the repository browser.