Index: nsview/perspectives/fitting/Copy of basepage.py
===================================================================
--- sansview/perspectives/fitting/Copy of basepage.py	(revision a07e72f8fb8281178797bf691b36e56274d8580b)
+++ 	(revision )
@@ -1,2589 +1,0 @@
-
-import sys
-import os
-import wx
-import numpy
-import time
-import copy 
-import math
-import string
-from sans.guiframe.panel_base import PanelBase
-from wx.lib.scrolledpanel import ScrolledPanel
-from sans.guiframe.utils import format_number,check_float
-from sans.guiframe.events import PanelOnFocusEvent
-from sans.guiframe.events import StatusEvent
-from sans.guiframe.events import AppendBookmarkEvent
-import pagestate
-from pagestate import PageState
-(PageInfoEvent, EVT_PAGE_INFO)   = wx.lib.newevent.NewEvent()
-(PreviousStateEvent, EVT_PREVIOUS_STATE)   = wx.lib.newevent.NewEvent()
-(NextStateEvent, EVT_NEXT_STATE)   = wx.lib.newevent.NewEvent()
-
-_BOX_WIDTH = 76
-_QMIN_DEFAULT = 0.001
-_QMAX_DEFAULT = 0.13
-_NPTS_DEFAULT = 50
-#Control panel width 
-if sys.platform.count("darwin")==0:
-    PANEL_WIDTH = 450
-    FONT_VARIANT = 0
-    ON_MAC = False
-else:
-    PANEL_WIDTH = 500
-    FONT_VARIANT = 1
-    ON_MAC = True
-    
-class BasicPage(ScrolledPanel, PanelBase):
-    """
-    This class provide general structure of  fitpanel page
-    """
-     ## Internal name for the AUI manager
-    window_name = "Basic Page"
-    ## Title to appear on top of the window
-    window_caption = "Basic page "
-    
-    def __init__(self, parent, page_info, **kwargs):
-        """
-        """
-        ScrolledPanel.__init__(self, parent, **kwargs)
-        PanelBase.__init__(self)
-        self.SetupScrolling()
-        #Set window's font size 
-        self.SetWindowVariant(variant=FONT_VARIANT)
-       
-        ## parent of the page
-        self.parent = parent
-        ## manager is the fitting plugin
-        ## owner of the page (fitting plugin)
-        self.event_owner = None
-         ## current model
-        self.model = None
-        ## data
-        self.data = None
-        self.mask = None
-        ## Q range
-        self.qmax_x = None
-        self.qmin_x = None
-        self.num_points= _NPTS_DEFAULT
-        ## total number of point: float
-        self.npts = None
-        ## default fitengine type
-        self.engine_type = 'scipy'
-        ## smear default
-        self.smearer = None
-        self.current_smearer = None
-        ## 2D smear accuracy default
-        self.smear2d_accuracy = 'Low'
-        ## slit smear: 
-        self.dxl = None
-        self.dxw = None
-        ## pinhole smear 
-        self.dx_min = None
-        self.dx_max = None
-       
-        self.disp_cb_dict = {}
-   
-        self.state = PageState(parent=parent)
-        ## dictionary containing list of models
-        self.model_list_box = None
-        self.set_page_info(page_info=page_info)
-        ## Data member to store the dispersion object created
-        self._disp_obj_dict = {}
-        ## selected parameters to apply dispersion
-        self.disp_cb_dict ={}
-
-        ## smearer object
-        self.smearer = None
-        
-        ##list of model parameters. each item must have same length
-        ## each item related to a given parameters
-        ##[cb state, name, value, "+/-", error of fit, min, max , units]
-        self.parameters = []
-        # non-fittable parameter whose value is astring
-        self.str_parameters = []
-        ## list of parameters to fit , must be like self.parameters
-        self.param_toFit = []
-        ## list of looking like parameters but with non fittable parameters info
-        self.fixed_param = []
-        ## list of looking like parameters but with  fittable parameters info
-        self.fittable_param = []
-        ##list of dispersion parameters
-        self.disp_list = []
-        self.disp_name = ""
-        
-        ## list of orientation parameters
-        self.orientation_params = []
-        self.orientation_params_disp = []
-        if self.model != None:
-            self.disp_list = self.model.getDispParamList()
-        
-        ##enable model 2D draw
-        self.enable2D = False
-        ## check that the fit range is correct to plot the model again
-        self.fitrange = True
-        ## Create memento to save the current state
-        self.state = PageState(parent=self.parent,
-                               model=self.model, data=self.data)
-        ## flag to determine if state has change
-        self.state_change = False
-        ## save customized array
-        self.values = []
-        self.weights = []
-        ## retrieve saved state
-        self.number_saved_state = 0
-        ## dictionary of saved state
-        self.saved_states = {} 
-        ## Create context menu for page
-        self.popUpMenu = wx.Menu()
-        #id = wx.NewId()
-        #self._undo = wx.MenuItem(self.popUpMenu,id, "Undo",
-        #"cancel the previous action")
-        #self.popUpMenu.AppendItem(self._undo)
-        #self._undo.Enable(False)
-        #wx.EVT_MENU(self, id, self.onUndo)
-        
-        #id = wx.NewId()
-        #self._redo = wx.MenuItem(self.popUpMenu,id,"Redo",
-        #" Restore the previous action")
-        #self.popUpMenu.AppendItem(self._redo)
-        #self._redo.Enable(False)
-        #wx.EVT_MENU(self, id, self.onRedo)       
-        #self.popUpMenu.AppendSeparator()
-        #if sys.platform.count("win32")>0:        
-        id = wx.NewId()
-        self._keep = wx.MenuItem(self.popUpMenu,id,"BookMark",
-                                 " Keep the panel status to recall it later")
-        self.popUpMenu.AppendItem(self._keep)
-        self._keep.Enable(True)
-        self._set_bookmark_flag(False)
-        self._set_save_flag(False)
-        wx.EVT_MENU(self, id, self.on_bookmark)
-        self.popUpMenu.AppendSeparator()
-    
-        ## Default locations
-        self._default_save_location = os.getcwd()     
-        ## save initial state on context menu
-        #self.onSave(event=None)
-        self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu)
-
-        ## create the basic structure of the panel with empty sizer
-        self.define_page_structure()
-        ## drawing Initial dispersion parameters sizer 
-        self.set_dispers_sizer()
-        
-        ## layout
-        self.set_layout()
-        
-    def on_set_focus(self, event):
-        """
-        """
-        if self._manager is not None:
-            wx.PostEvent(self._manager.parent, PanelOnFocusEvent(panel=self))
-        
-    class ModelTextCtrl(wx.TextCtrl):
-        """
-        Text control for model and fit parameters.
-        Binds the appropriate events for user interactions.
-        Default callback methods can be overwritten on initialization
-        
-        :param kill_focus_callback: callback method for EVT_KILL_FOCUS event
-        :param set_focus_callback:  callback method for EVT_SET_FOCUS event
-        :param mouse_up_callback:   callback method for EVT_LEFT_UP event
-        :param text_enter_callback: callback method for EVT_TEXT_ENTER event
-        
-        """
-        ## Set to True when the mouse is clicked while the whole string is selected
-        full_selection = False
-        ## Call back for EVT_SET_FOCUS events
-        _on_set_focus_callback = None
-        
-        def __init__(self, parent, id=-1, 
-                     value=wx.EmptyString, 
-                     pos=wx.DefaultPosition, 
-                     size=wx.DefaultSize,
-                     style=0, 
-                     validator=wx.DefaultValidator,
-                     name=wx.TextCtrlNameStr,
-                     kill_focus_callback=None,
-                     set_focus_callback=None,
-                     mouse_up_callback=None,
-                     text_enter_callback = None):
-             
-            wx.TextCtrl.__init__(self, parent, id, value, pos,
-                                  size, style, validator, name)
-            
-            # Bind appropriate events
-            self._on_set_focus_callback = parent.onSetFocus \
-                      if set_focus_callback is None else set_focus_callback
-            self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
-            self.Bind(wx.EVT_KILL_FOCUS, self._silent_kill_focus \
-                      if kill_focus_callback is None else kill_focus_callback)                
-            self.Bind(wx.EVT_TEXT_ENTER, parent._onparamEnter \
-                      if text_enter_callback is None else text_enter_callback)
-            if not ON_MAC :
-                self.Bind(wx.EVT_LEFT_UP,    self._highlight_text \
-                          if mouse_up_callback is None else mouse_up_callback)
-            
-        def _on_set_focus(self, event):
-            """
-            Catch when the text control is set in focus to highlight the whole
-            text if necessary
-            
-            :param event: mouse event
-            
-            """
-            event.Skip()
-            self.full_selection = True
-            return self._on_set_focus_callback(event)
-        
- 
-            
-        def _highlight_text(self, event):
-            """
-            Highlight text of a TextCtrl only of no text has be selected
-            
-            :param event: mouse event
-            
-            """
-            # Make sure the mouse event is available to other listeners
-            event.Skip()
-            control  = event.GetEventObject()
-            if self.full_selection:
-                self.full_selection = False
-                # Check that we have a TextCtrl
-                if issubclass(control.__class__, wx.TextCtrl):
-                    # Check whether text has been selected, 
-                    # if not, select the whole string
-                    (start, end) = control.GetSelection()
-                    if start==end:
-                        control.SetSelection(-1,-1)
-                        
-        def _silent_kill_focus(self,event):
-            """
-            Save the state of the page
-            """
-            
-            event.Skip()
-            pass
-    
-    def set_page_info(self, page_info):
-        """
-        set some page important information at once
-        """
-       ##window_name
-        self.window_name = page_info.window_name
-        ##window_caption
-        self.window_caption = page_info.window_caption
-        ## manager is the fitting plugin
-        self._manager= page_info.manager
-        ## owner of the page (fitting plugin)
-        self.event_owner= page_info.event_owner
-         ## current model
-        self.model = page_info.model
-        ## data
-        self.data = page_info.data
-        ## dictionary containing list of models
-        self.model_list_box = page_info.model_list_box
-        ## Data member to store the dispersion object created
-        self.populate_box(dict=self.model_list_box)
-        
-    def onContextMenu(self, event): 
-        """
-        Retrieve the state selected state
-        """
-        # Skipping the save state functionality for release 0.9.0
-        #return
-    
-        pos = event.GetPosition()
-        pos = self.ScreenToClient(pos)
-       
-        self.PopupMenu(self.popUpMenu, pos) 
-      
-        
-    def onUndo(self, event):
-        """
-        Cancel the previous action
-        """
-        #print "enable undo"
-        event = PreviousStateEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        
-    def onRedo(self, event):
-        """
-        Restore the previous action cancelled 
-        """
-        #print "enable redo"
-        event = NextStateEvent(page= self)
-        wx.PostEvent(self.parent, event)
-    
-    def define_page_structure(self):
-        """
-        Create empty sizer for a panel
-        """
-        self.vbox  = wx.BoxSizer(wx.VERTICAL)
-        self.sizer0 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer3 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer6 = wx.BoxSizer(wx.VERTICAL)
-        
-        self.sizer0.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer1.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer2.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer3.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer4.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer5.SetMinSize((PANEL_WIDTH,-1))
-        self.sizer6.SetMinSize((PANEL_WIDTH,-1))
-        
-        self.vbox.Add(self.sizer0)
-        self.vbox.Add(self.sizer1)
-        self.vbox.Add(self.sizer2)
-        self.vbox.Add(self.sizer3)
-        self.vbox.Add(self.sizer4)
-        self.vbox.Add(self.sizer5)
-        self.vbox.Add(self.sizer6)
-        
-    def set_layout(self):
-        """
-        layout
-        """
-        self.vbox.Layout()
-        self.vbox.Fit(self) 
-        self.SetSizer(self.vbox)
-        self.Centre()
- 
-    def set_owner(self,owner):
-        """ 
-        set owner of fitpage
-        
-        :param owner: the class responsible of plotting
-        
-        """
-        self.event_owner = owner    
-        self.state.event_owner = owner
-        
-    def get_state(self):
-        """
-        """
-        return self.state
-    def get_data(self):
-        """
-        return the current data 
-        """
-        return self.data  
-    
-    def set_manager(self, manager):
-        """
-        set panel manager
-        
-        :param manager: instance of plugin fitting
-        
-        """
-        self._manager = manager  
-        self.state.manager = manager
-        
-    def populate_box(self, dict):
-        """
-        Store list of model
-        
-        :param dict: dictionary containing list of models
-        
-        """
-        self.model_list_box = dict
-        self.state.model_list_box = self.model_list_box
-        
-    def initialize_combox(self): 
-        """
-        put default value in the combobox 
-        """  
-        ## fill combox box
-        if self.model_list_box is None:
-            return
-        if len(self.model_list_box) > 0:
-            self._populate_box(self.formfactorbox,
-                               self.model_list_box["Shapes"])
-       
-        if len(self.model_list_box) > 0:
-            self._populate_box(self.structurebox,
-                                self.model_list_box["Structure Factors"])
-            self.structurebox.Insert("None", 0, None)
-            self.structurebox.SetSelection(0)
-            self.structurebox.Hide()
-            self.text2.Hide()
-            self.structurebox.Disable()
-            self.text2.Disable()
-             
-            if self.model.__class__ in self.model_list_box["P(Q)*S(Q)"]:
-                self.structurebox.Show()
-                self.text2.Show()
-                self.structurebox.Enable()
-                self.text2.Enable()            
-                
-    def set_dispers_sizer(self):
-        """
-        fill sizer containing dispersity info
-        """
-        self.sizer4.Clear(True)
-        name="Polydispersity and Orientational Distribution"
-        box_description= wx.StaticBox(self, -1,name)
-        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-        #----------------------------------------------------
-        self.disable_disp = wx.RadioButton(self, -1, 'Off', (10, 10),
-                                            style=wx.RB_GROUP)
-        self.enable_disp = wx.RadioButton(self, -1, 'On', (10, 30))
-       
-        
-        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
-                     id=self.disable_disp.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
-                   id=self.enable_disp.GetId())
-        #MAC needs SetValue
-        self.disable_disp.SetValue(True)
-        sizer_dispersion = wx.BoxSizer(wx.HORIZONTAL)
-        sizer_dispersion.Add((20,20))
-        name=""#Polydispersity and \nOrientational Distribution "
-        sizer_dispersion.Add(wx.StaticText(self,-1,name))
-        sizer_dispersion.Add(self.enable_disp )
-        sizer_dispersion.Add((20,20))
-        sizer_dispersion.Add(self.disable_disp )
-        sizer_dispersion.Add((10,10))
-        
-        ## fill a sizer with the combobox to select dispersion type
-        sizer_select_dispers = wx.BoxSizer(wx.HORIZONTAL)  
-        self.model_disp = wx.StaticText(self, -1, 'Distribution Function ')
-            
-        import sans.models.dispersion_models 
-        self.polydisp= sans.models.dispersion_models.models
-        self.disp_box = wx.ComboBox(self, -1)
-
-        for key, value in self.polydisp.iteritems():
-            name = str(key)
-            self.disp_box.Append(name,value)
-        self.disp_box.SetStringSelection("gaussian") 
-        wx.EVT_COMBOBOX(self.disp_box,-1, self._on_select_Disp) 
-             
-        sizer_select_dispers.Add((10,10)) 
-        sizer_select_dispers.Add(self.model_disp) 
-        sizer_select_dispers.Add(self.disp_box,0,
-                wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5)
-      
-        self.model_disp.Hide()
-        self.disp_box.Hide()
-        
-        boxsizer1.Add( sizer_dispersion,0,
-                wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5)
-        #boxsizer1.Add( (10,10) )
-        boxsizer1.Add( sizer_select_dispers )
-        self.sizer4_4 = wx.GridBagSizer(5,5)
-        boxsizer1.Add( self.sizer4_4  )
-        #-----------------------------------------------------
-        self.sizer4.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
-        self.sizer4_4.Layout()
-        self.sizer4.Layout()
-        self.Layout()
-     
-        self.Refresh()
-        ## saving the state of enable dispersity button
-        self.state.enable_disp= self.enable_disp.GetValue()
-        self.state.disable_disp= self.disable_disp.GetValue()
-
-    def select_disp_angle(self, event): 
-        """
-        Event for when a user select a parameter to average over.
-        
-        :param event: radiobutton event
-        
-        """
-        self.values=[]
-        self.weights=[]
-        if event.GetEventObject()==self.noDisper_rbox:
-            if self.noDisper_rbox.GetValue():
-                #No array dispersity apply yet
-                self._reset_dispersity()
-                ## Redraw the model ???
-                self._draw_model()
-        # Go through the list of dispersion check boxes to identify
-        # which one has changed 
-        for p in self.disp_cb_dict:
-            self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
-            # Catch which one of the box was just checked or unchecked.
-            if event.GetEventObject() == self.disp_cb_dict[p]:              
-                if self.disp_cb_dict[p].GetValue() == True:
-                    
-                    ##Temp. FIX for V1.0 regarding changing checkbox 
-                    #to radiobutton.
-                    ##This (self._reset_dispersity) should be removed 
-                    #when the array dispersion is fixed.                
-                    self._reset_dispersity()
-
-                    # The user wants this parameter to be averaged. 
-                    # Pop up the file selection dialog.
-                    path = self._selectDlg()
-                    
-                    # If nothing was selected, just return
-                    if path is None:
-                        self.disp_cb_dict[p].SetValue(False)
-                        self.noDisper_rbox.SetValue(True)
-                        return
-                    try:
-                        self._default_save_location = os.path.dirname(path)
-                    except:
-                        pass 
-                    try:
-                        self.values,self.weights = self.read_file(path)
-                    except:
-                        msg="Could not read input file"
-                        wx.PostEvent(self.parent.parent, 
-                                     StatusEvent(status=msg))
-                        return
-                    
-                    # If any of the two arrays is empty, notify the user that we won't
-                    # proceed 
-                    if self.values is None or self.weights is None or \
-                         self.values ==[] or self.weights ==[]:
-                        msg = "The loaded %s distrubtion is"
-                        msg + " corrupted or empty" % p
-                        wx.PostEvent(self.parent.parent, 
-                                     StatusEvent(status=msg))
-                        return
-                        
-                    # Tell the user that we are about to apply the distribution
-                    msg = "Applying loaded %s distribution: %s" % (p, path)
-                    wx.PostEvent(self.parent.parent, StatusEvent(status=msg))  
-                    
-                    # Create the dispersion objects
-                    from sans.models.dispersion_models import ArrayDispersion
-                    disp_model = ArrayDispersion()
-                    disp_model.set_weights(self.values, self.weights)
-                   
-                    # Store the object to make it persist outside the
-                    # scope of this method
-                    #TODO: refactor model to clean this up?
-                    self._disp_obj_dict[p] = disp_model
-                    self.state._disp_obj_dict [p]= disp_model
-                    self.state.values = []
-                    self.state.weights = []
-                    self.state.values = copy.deepcopy(self.values)
-                    self.state.weights = copy.deepcopy(self.weights)
-                    # Set the new model as the dispersion object for the 
-                    #selected parameter
-                    self.model.set_dispersion(p, disp_model)
-                    # Store a reference to the weights in the model object 
-                    #so that
-                    # it's not lost when we use the model within another thread.
-                    #TODO: total hack - fix this
-                    self.state.model= self.model.clone()
-
-                    self.model._persistency_dict = {}
-                    self.model._persistency_dict[p] = \
-                                                    [self.values, self.weights]
-                    self.state.model._persistency_dict[p] = \
-                                                    [self.values,self.weights]
-                else:
-                    self._reset_dispersity()
-              
-                ## Redraw the model
-                self._draw_model()
-        
-        ## post state to fit panel
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-       
-    
-    def onResetModel(self, event):
-        """
-        Reset model state
-        """
-        menu = event.GetEventObject()
-        ## post help message for the selected model 
-        msg = menu.GetHelpString(event.GetId())
-        msg +=" reloaded"
-        wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
-        
-        name = menu.GetLabel(event.GetId())
-        self._on_select_model_helper()
-        
-        if name in self.saved_states.keys():
-            previous_state = self.saved_states[name]
-            ## reset state of checkbox,textcrtl  and  regular parameters value
-            self.reset_page(previous_state)      
-         
-    def on_save(self, event):   
-        """
-        Save the current state into file
-        """  
-        self.save_current_state()
-        new_state = self.state.clone()
-        # Ask the user the location of the file to write to.
-        path = None
-        dlg = wx.FileDialog(self, "Choose a file", self._default_save_location,
-                                                 "", "*.fitv", wx.SAVE)
-        if dlg.ShowModal() == wx.ID_OK:
-            path = dlg.GetPath()
-            self._default_save_location = os.path.dirname(path)
-        else:
-            return None
-        #the manager write the state into file
-        self._manager.save_fit_state(filepath=path, fitstate=new_state)
-        return new_state  
-    
-    def _get_time_stamp(self):
-        """
-        return time and date stings
-        """
-        # date and time 
-        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
-        current_time= str(hour)+":"+str(minute)+":"+str(second)
-        current_date= str( month)+"/"+str(day)+"/"+str(year)
-        return current_time, current_date
-      
-    def on_bookmark(self, event):
-        """
-        save history of the data and model
-        """
-        if self.model==None:
-            msg="Can not bookmark; Please select Data and Model first..."
-            wx.MessageBox(msg, 'Info')
-            return 
-        self.save_current_state()
-        new_state = self.state.clone()
-        ##Add model state on context menu
-        self.number_saved_state += 1
-        current_time, current_date = self._get_time_stamp()
-        #name= self.model.name+"[%g]"%self.number_saved_state 
-        name = "Fitting: %g]" % self.number_saved_state 
-        name += self.model.__class__.__name__ 
-        name += "bookmarked at %s on %s" % (current_time, current_date)
-        self.saved_states[name]= new_state
-        
-        ## Add item in the context menu
-        msg =  "Model saved at %s on %s"%(current_time, current_date)
-         ## post help message for the selected model 
-        msg +=" Saved! right click on this page to retrieve this model"
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        
-        #id = wx.NewId()
-        #self.popUpMenu.Append(id,name,str(msg))
-        #wx.EVT_MENU(self, id, self.onResetModel)
-        wx.PostEvent(self.parent.parent, 
-                     AppendBookmarkEvent(title=name, 
-                                         hint=str(msg), handler=self.onResetModel))
-        
-    def old_on_bookmark(self, event):
-        """
-        save history of the data and model
-        """
-        if self.model==None:
-            msg="Can not bookmark; Please select Data and Model first..."
-            wx.MessageBox(msg, 'Info')
-            return 
-        if hasattr(self,"enable_disp"):
-            self.state.enable_disp = copy.deepcopy(self.enable_disp.GetValue())
-        if hasattr(self, "disp_box"):
-            self.state.disp_box = copy.deepcopy(self.disp_box.GetSelection())
-
-        self.state.model.name= self.model.name
-        
-        #Remember fit engine_type for fit panel
-        if self.engine_type == None: 
-            self.engine_type = "scipy"
-        if self._manager !=None:
-            self._manager._on_change_engine(engine=self.engine_type)
-        
-            self.state.engine_type = self.engine_type
-
-        new_state = self.state.clone()
-        new_state.model.name = self.state.model.name
-        
-        new_state.enable2D = copy.deepcopy(self.enable2D)
-        ##Add model state on context menu
-        self.number_saved_state += 1
-        #name= self.model.name+"[%g]"%self.number_saved_state 
-        name= self.model.__class__.__name__+"[%g]"%self.number_saved_state 
-        self.saved_states[name]= new_state
-        
-        ## Add item in the context menu
-        
-        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
-        my_time= str(hour)+" : "+str(minute)+" : "+str(second)+" "
-        date= str( month)+"|"+str(day)+"|"+str(year)
-        msg=  "Model saved at %s on %s"%(my_time, date)
-         ## post help message for the selected model 
-        msg +=" Saved! right click on this page to retrieve this model"
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        
-        id = wx.NewId()
-        self.popUpMenu.Append(id,name,str(msg))
-        wx.EVT_MENU(self, id, self.onResetModel)
-        
-    def onSetFocus(self, evt):
-        """
-        highlight the current textcrtl and hide the error text control shown 
-        after fitting
-        """
-        return
-    
-    def read_file(self, path):
-        """
-        Read two columns file
-        
-        :param path: the path to the file to read
-        
-        """
-        try:
-            if path==None:
-                wx.PostEvent(self.parent.parent, StatusEvent(status=\
-                            " Selected Distribution was not loaded: %s"%path))
-                return None, None
-            input_f = open(path, 'r')
-            buff = input_f.read()
-            lines = buff.split('\n')
-            
-            angles = []
-            weights=[]
-            for line in lines:
-                toks = line.split()
-                try:
-                    angle = float(toks[0])
-                    weight = float(toks[1])
-                except:
-                    # Skip non-data lines
-                    pass
-                angles.append(angle)
-                weights.append(weight)
-            return numpy.array(angles), numpy.array(weights)
-        except:
-            raise 
-
-    def createMemento(self):
-        """
-        return the current state of the page
-        """
-        return self.state.clone()
-    
-    
-    def save_current_state(self):
-        """
-        Store current state
-        """
-        self.state.engine_type = copy.deepcopy(self.engine_type)
-        ## save model option
-        if self.model!= None:
-            self.disp_list= self.model.getDispParamList()
-            self.state.disp_list= copy.deepcopy(self.disp_list)
-            self.state.model = self.model.clone()
-        #save radiobutton state for model selection
-        self.state.shape_rbutton = self.shape_rbutton.GetValue()
-        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
-        self.state.struct_rbutton = self.struct_rbutton.GetValue()
-        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
-        #model combobox
-        self.state.structurebox = self.structurebox.GetSelection()
-        self.state.formfactorbox = self.formfactorbox.GetSelection()
-        
-        self.state.enable2D = copy.deepcopy(self.enable2D)
-        self.state.values= copy.deepcopy(self.values)
-        self.state.weights = copy.deepcopy( self.weights)
-        ## save data    
-        self.state.data= copy.deepcopy(self.data)
-        self.state.qmax_x = self.qmax_x
-        self.state.qmin_x = self.qmin_x
-        try:
-            n = self.disp_box.GetCurrentSelection()
-            dispersity= self.disp_box.GetClientData(n)
-            name= dispersity.__name__
-            self.disp_name = name
-            if name == "GaussianDispersion" :
-               if hasattr(self,"cb1"):
-                   self.state.cb1= self.cb1.GetValue()
-        except:
-            pass
-      
-        if hasattr(self,"enable_disp"):
-            self.state.enable_disp= self.enable_disp.GetValue()
-            self.state.disable_disp = self.disable_disp.GetValue()
-            
-        self.state.smearer = copy.deepcopy(self.smearer)
-        if hasattr(self,"enable_smearer"):
-            self.state.enable_smearer = \
-                                copy.deepcopy(self.enable_smearer.GetValue())
-            self.state.disable_smearer = \
-                                copy.deepcopy(self.disable_smearer.GetValue())
-
-        self.state.pinhole_smearer = \
-                                copy.deepcopy(self.pinhole_smearer.GetValue())
-        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue())  
-                  
-        if hasattr(self,"disp_box"):
-            self.state.disp_box = self.disp_box.GetSelection()
-
-            if len(self.disp_cb_dict)>0:
-                for k , v in self.disp_cb_dict.iteritems():
-         
-                    if v ==None :
-                        self.state.disp_cb_dict[k]= v
-                    else:
-                        try:
-                            self.state.disp_cb_dict[k]=v.GetValue()
-                        except:
-                            self.state.disp_cb_dict[k]= None
-           
-            if len(self._disp_obj_dict)>0:
-                for k , v in self._disp_obj_dict.iteritems():
-      
-                    self.state._disp_obj_dict[k]= v
-                        
-            
-            self.state.values = copy.deepcopy(self.values)
-            self.state.weights = copy.deepcopy(self.weights)
-        ## save plotting range
-        self._save_plotting_range()
-        
-        self.state.orientation_params =[]
-        self.state.orientation_params_disp =[]
-        self.state.parameters =[]
-        self.state.fittable_param =[]
-        self.state.fixed_param =[]
-
-        
-        ## save checkbutton state and txtcrtl values
-        self._copy_parameters_state(self.orientation_params,
-                                     self.state.orientation_params)
-        self._copy_parameters_state(self.orientation_params_disp,
-                                     self.state.orientation_params_disp)
-        
-        self._copy_parameters_state(self.parameters, self.state.parameters)
-        self._copy_parameters_state(self.fittable_param,
-                                     self.state.fittable_param)
-        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
-        #save chisqr
-        self.state.tcChi = self.tcChi.GetValue()
-        
-    def save_current_state_fit(self):
-        """
-        Store current state for fit_page
-        """
-        ## save model option
-        if self.model!= None:
-            self.disp_list= self.model.getDispParamList()
-            self.state.disp_list= copy.deepcopy(self.disp_list)
-            self.state.model = self.model.clone()
-        if hasattr(self, "engine_type"):
-            self.state.engine_type = copy.deepcopy(self.engine_type)
-            
-        self.state.enable2D = copy.deepcopy(self.enable2D)
-        self.state.values= copy.deepcopy(self.values)
-        self.state.weights = copy.deepcopy( self.weights)
-        ## save data    
-        self.state.data= copy.deepcopy(self.data)
-        try:
-            n = self.disp_box.GetCurrentSelection()
-            dispersity= self.disp_box.GetClientData(n)
-            name= dispersity.__name__
-            self.disp_name = name
-            if name == "GaussianDispersion" :
-               if hasattr(self,"cb1"):
-                   self.state.cb1= self.cb1.GetValue()
-
-        except:
-            pass
-        
-        if hasattr(self,"enable_disp"):
-            self.state.enable_disp= self.enable_disp.GetValue()
-            self.state.disable_disp = self.disable_disp.GetValue()
-            
-        self.state.smearer = copy.deepcopy(self.smearer)
-        if hasattr(self,"enable_smearer"):
-            self.state.enable_smearer = \
-                                copy.deepcopy(self.enable_smearer.GetValue())
-            self.state.disable_smearer = \
-                                copy.deepcopy(self.disable_smearer.GetValue())
-            
-        self.state.pinhole_smearer = \
-                                copy.deepcopy(self.pinhole_smearer.GetValue())
-        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue())  
-            
-        if hasattr(self,"disp_box"):
-            self.state.disp_box = self.disp_box.GetCurrentSelection()
-
-            if len(self.disp_cb_dict) > 0:
-                for k, v in self.disp_cb_dict.iteritems():
-         
-                    if v == None :
-                        self.state.disp_cb_dict[k] = v
-                    else:
-                        try:
-                            self.state.disp_cb_dict[k] = v.GetValue()
-                        except:
-                            self.state.disp_cb_dict[k] = None
-           
-            if len(self._disp_obj_dict) > 0:
-                for k , v in self._disp_obj_dict.iteritems():
-      
-                    self.state._disp_obj_dict[k] = v
-                        
-            
-            self.state.values = copy.deepcopy(self.values)
-            self.state.weights = copy.deepcopy(self.weights)
-           
-        ## save plotting range
-        self._save_plotting_range()
-        
-        ## save checkbutton state and txtcrtl values
-        self._copy_parameters_state(self.orientation_params,
-                                     self.state.orientation_params)
-        self._copy_parameters_state(self.orientation_params_disp,
-                                     self.state.orientation_params_disp)
-        self._copy_parameters_state(self.parameters, self.state.parameters)
-        self._copy_parameters_state(self.fittable_param,
-                                             self.state.fittable_param)
-        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
-    
-          
-    def check_invalid_panel(self):  
-        """
-        check if the user can already perform some action with this panel
-        """ 
-        flag = False
-        if self.data is None:
-            self.disable_smearer.SetValue(True)
-            self.disable_disp.SetValue(True)
-            msg = "Please load Data and select Model to start..."
-            wx.MessageBox(msg, 'Info')
-            return  True
-        
-           
-    def reset_page_helper(self, state):
-        """
-        Use page_state and change the state of existing page
-        
-        :precondition: the page is already drawn or created
-        
-        :postcondition: the state of the underlying data change as well as the
-            state of the graphic interface
-        """
-        if state == None:
-            #self._undo.Enable(False)
-            return 
-    
-        self.set_data(state.data)
-        self.enable2D= state.enable2D
-        self.engine_type = state.engine_type
-
-        self.disp_cb_dict = state.disp_cb_dict
-        self.disp_list = state.disp_list
-      
-        ## set the state of the radio box
-        self.shape_rbutton.SetValue(state.shape_rbutton )
-        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
-        self.struct_rbutton.SetValue(state.struct_rbutton)
-        self.plugin_rbutton.SetValue(state.plugin_rbutton)
-        
-        ## fill model combobox
-        self._show_combox_helper()
-        #select the current model
-        self.formfactorbox.Select(int(state.formfactorcombobox))
-        self.structurebox.SetSelection(state.structurecombobox )
-        if state.multi_factor != None:
-            self.multifactorbox.SetSelection(state.multi_factor)
-
-        #reset the fitting engine type
-        self.engine_type = state.engine_type
-        #draw the pnael according to the new model parameter 
-        self._on_select_model(event=None)
-       
-        if self._manager !=None:
-            self._manager._on_change_engine(engine=self.engine_type)
-        ## set the select all check box to the a given state
-        self.cb1.SetValue(state.cb1)
-     
-        ## reset state of checkbox,textcrtl  and  regular parameters value
-        self._reset_parameters_state(self.orientation_params_disp,
-                                     state.orientation_params_disp)
-        self._reset_parameters_state(self.orientation_params,
-                                     state.orientation_params)
-        self._reset_parameters_state(self.str_parameters,
-                                     state.str_parameters)
-        self._reset_parameters_state(self.parameters,state.parameters)    
-         ## display dispersion info layer        
-        self.enable_disp.SetValue(state.enable_disp)
-        self.disable_disp.SetValue(state.disable_disp)
-        
-        if hasattr(self, "disp_box"):
-            
-            self.disp_box.SetSelection(state.disp_box) 
-            n= self.disp_box.GetCurrentSelection()
-            dispersity= self.disp_box.GetClientData(n)
-            name = dispersity.__name__     
-
-            self._set_dipers_Param(event=None)
-       
-            if name == "ArrayDispersion":
-                
-                for item in self.disp_cb_dict.keys():
-                    
-                    if hasattr(self.disp_cb_dict[item], "SetValue") :
-                        self.disp_cb_dict[item].SetValue(\
-                                                    state.disp_cb_dict[item])
-                        # Create the dispersion objects
-                        from sans.models.dispersion_models import ArrayDispersion
-                        disp_model = ArrayDispersion()
-                        if hasattr(state,"values")and\
-                                 self.disp_cb_dict[item].GetValue() == True:
-                            if len(state.values)>0:
-                                self.values=state.values
-                                self.weights=state.weights
-                                disp_model.set_weights(self.values,
-                                                        state.weights)
-                            else:
-                                self._reset_dispersity()
-                        
-                        self._disp_obj_dict[item] = disp_model
-                        # Set the new model as the dispersion object 
-                        #for the selected parameter
-                        self.model.set_dispersion(item, disp_model)
-                    
-                        self.model._persistency_dict[item] = \
-                                                [state.values, state.weights]
-                    
-            else:
-                keys = self.model.getParamList()
-                for item in keys:
-                    if item in self.disp_list and \
-                        not self.model.details.has_key(item):
-                        self.model.details[item] = ["", None, None]
-                for k,v in self.state.disp_cb_dict.iteritems():
-                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
-                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
-
-        ##plotting range restore    
-        self._reset_plotting_range(state)
-        ## smearing info  restore
-        if hasattr(self, "enable_smearer"):
-            ## set smearing value whether or not the data 
-            #contain the smearing info
-            self.enable_smearer.SetValue(state.enable_smearer)
-            self.disable_smearer.SetValue(state.disable_smearer)
-            self.onSmear(event=None)           
-        self.pinhole_smearer.SetValue(state.pinhole_smearer)
-        self.slit_smearer.SetValue(state.slit_smearer)
-        ## we have two more options for smearing
-        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
-        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
-       
-        ## reset state of checkbox,textcrtl  and dispersity parameters value
-        self._reset_parameters_state(self.fittable_param,state.fittable_param)
-        self._reset_parameters_state(self.fixed_param,state.fixed_param)
-        
-        ## draw the model with previous parameters value
-        self._onparamEnter_helper()
-        #reset the value of chisqr when not consistent with the value computed
-        self.tcChi.SetValue(str(self.state.tcChi))
-        ## reset context menu items
-        self._reset_context_menu()
-        
-        ## set the value of the current state to the state given as parameter
-        self.state = state.clone() 
-    
-        
-    def old_reset_page_helper(self, state):
-        """
-        Use page_state and change the state of existing page
-        
-        :precondition: the page is already drawn or created
-        
-        :postcondition: the state of the underlying data change as well as the
-            state of the graphic interface
-        """
-        if state ==None:
-            #self._undo.Enable(False)
-            return 
-       
-        self.model= state.model
-        self.data = state.data
-        if self.data !=None:
-            from DataLoader.qsmearing import smear_selection
-            self.smearer= smear_selection(self.data, self.model)
-        self.enable2D= state.enable2D
-        self.engine_type = state.engine_type
-
-        self.disp_cb_dict = state.disp_cb_dict
-        self.disp_list = state.disp_list
-
-        ## set the state of the radio box
-        self.shape_rbutton.SetValue(state.shape_rbutton )
-        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
-        self.struct_rbutton.SetValue(state.struct_rbutton )
-        self.plugin_rbutton.SetValue(state.plugin_rbutton)
-        ##draw sizer containing model parameters value for the current model
-        self._set_model_sizer_selection( self.model )
-        self.set_model_param_sizer(self.model)
-
-        ## reset value of combox box
-        self.structurebox.SetSelection(state.structurecombobox )
-        self.formfactorbox.SetSelection(state.formfactorcombobox)
-        
-        
-        ## enable the view 2d button if this is a modelpage type
-        if hasattr(self,"model_view"):
-            if self.enable2D:
-                self.model_view.Disable()
-            else:
-                self.model_view.Enable()
-        ## set the select all check box to the a given state
-        if hasattr(self, "cb1"):   
-            self.cb1.SetValue(state.cb1)
-     
-        ## reset state of checkbox,textcrtl  and  regular parameters value
-            
-        self._reset_parameters_state(self.orientation_params_disp,
-                                     state.orientation_params_disp)
-        self._reset_parameters_state(self.orientation_params,
-                                     state.orientation_params)
-        self._reset_parameters_state(self.parameters,state.parameters)    
-         ## display dispersion info layer        
-        self.enable_disp.SetValue(state.enable_disp)
-        self.disable_disp.SetValue(state.disable_disp)
-        
-        if hasattr(self, "disp_box"):
-            
-            self.disp_box.SetSelection(state.disp_box) 
-            n= self.disp_box.GetCurrentSelection()
-            dispersity= self.disp_box.GetClientData(n)
-            name= dispersity.__name__     
-
-            self._set_dipers_Param(event=None)
-       
-            if name=="ArrayDispersion":
-                
-                for item in self.disp_cb_dict.keys():
-                    
-                    if hasattr(self.disp_cb_dict[item],"SetValue") :
-                        self.disp_cb_dict[item].SetValue(state.disp_cb_dict[item])
-                        # Create the dispersion objects
-                        from sans.models.dispersion_models import ArrayDispersion
-                        disp_model = ArrayDispersion()
-                        if hasattr(state,"values") and\
-                             self.disp_cb_dict[item].GetValue()==True:
-                            if len(state.values) > 0:
-                                self.values = state.values
-                                self.weights = state.weights
-                                disp_model.set_weights(self.values,
-                                                        state.weights)
-                            else:
-                                self._reset_dispersity()
-                        
-                        self._disp_obj_dict[item] = disp_model
-                        # Set the new model as the dispersion
-                        #object for the selected parameter
-                        self.model.set_dispersion(item, disp_model)
-                    
-                        self.model._persistency_dict[item] = [state.values,
-                                                               state.weights]
-                    
-            else:
-                keys = self.model.getParamList()
-                for item in keys:
-                    if item in self.disp_list and \
-                            not self.model.details.has_key(item):
-                        self.model.details[item]=["",None,None]
-                for k,v in self.state.disp_cb_dict.iteritems():
-                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
-                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
-
-        ##plotting range restore    
-        self._reset_plotting_range(state)
-
-        ## smearing info  restore
-        if hasattr(self,"enable_smearer"):
-            ## set smearing value whether or not the data 
-            #contain the smearing info
-            self.enable_smearer.SetValue(state.enable_smearer)
-            self.disable_smearer.SetValue(state.disable_smearer)
-            self.onSmear(event=None)           
-        self.pinhole_smearer.SetValue(state.pinhole_smearer)
-        self.slit_smearer.SetValue(state.slit_smearer)
-        ## we have two more options for smearing
-        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
-        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
-       
-        ## reset state of checkbox,textcrtl  and dispersity parameters value
-        self._reset_parameters_state(self.fittable_param,state.fittable_param)
-        self._reset_parameters_state(self.fixed_param,state.fixed_param)
-        
-        ## draw the model with previous parameters value
-        self._onparamEnter_helper()
-        
-        ## reset context menu items
-        self._reset_context_menu()
-    
-        ## set the value of the current state to the state given as parameter
-        self.state = state.clone() 
-        self._draw_model()
-
-    def _selectDlg(self):
-        """
-        open a dialog file to selected the customized dispersity 
-        """
-        import os
-        dlg = wx.FileDialog(self, "Choose a weight file",
-                                self._default_save_location , "", 
-                                "*.*", wx.OPEN)
-        path = None
-        if dlg.ShowModal() == wx.ID_OK:
-            path = dlg.GetPath()
-        dlg.Destroy()
-        return path
-
-    def _reset_context_menu(self):
-        """
-        reset the context menu
-        """
-        for name, state in self.state.saved_states.iteritems():
-            self.number_saved_state += 1
-            ## Add item in the context menu
-            id = wx.NewId()
-            msg = 'Save model and state %g' % self.number_saved_state
-            self.popUpMenu.Append(id, name, msg)
-            wx.EVT_MENU(self, id, self.onResetModel)
-    
-    def _reset_plotting_range(self, state):
-        """
-        Reset the plotting range to a given state
-        """
-        if self.check_invalid_panel():
-            return
-        self.qmin.SetValue(str(state.qmin))
-        self.qmax.SetValue(str(state.qmax)) 
-
-    def _save_typeOfmodel(self):
-        """
-        save radiobutton containing the type model that can be selected
-        """
-        self.state.shape_rbutton = self.shape_rbutton.GetValue()
-        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
-        self.state.struct_rbutton = self.struct_rbutton.GetValue()
-        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
-        self.state.structurebox= self.structurebox.GetCurrentSelection()
-        self.state.formfactorbox = self.formfactorbox.GetCurrentSelection()
-       
-        #self._undo.Enable(True)
-        ## post state to fit panel
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        
-    def _save_plotting_range(self ):
-        """
-        save the state of plotting range 
-        """
-        self.state.qmin = self.qmin_x
-        self.state.qmax = self.qmax_x 
-        if self.npts != None:
-            self.state.npts = self.num_points
-            
-    def _onparamEnter_helper(self):
-        """
-        check if values entered by the user are changed and valid to replot 
-        model
-        """
-        # Flag to register when a parameter has changed.   
-        is_modified = False
-        self.fitrange = True
-        is_2Ddata = False
-        #self._undo.Enable(True)
-        # check if 2d data
-        if self.data.__class__.__name__ == "Data2D":
-            is_2Ddata = True
-        if self.model !=None:
-            try:
-                is_modified = self._check_value_enter(self.fittable_param,
-                                                     is_modified)
-                is_modified = self._check_value_enter(self.fixed_param,
-                                                      is_modified)
-                is_modified = self._check_value_enter(self.parameters,
-                                                      is_modified) 
-            except:
-                pass
-            #if is_modified:
-
-            # Here we should check whether the boundaries have been modified.
-            # If qmin and qmax have been modified, update qmin and qmax and 
-            # set the is_modified flag to True
-            if self._validate_qrange(self.qmin, self.qmax):
-                tempmin = float(self.qmin.GetValue())
-                if tempmin != self.qmin_x:
-                    self.qmin_x = tempmin
-                    is_modified = True
-                tempmax = float(self.qmax.GetValue())
-                if tempmax != self.qmax_x:
-                    self.qmax_x = tempmax
-                    is_modified = True
-            
-                if is_2Ddata:
-                    # set mask   
-                    is_modified = self._validate_Npts()
-                    
-            else:
-                self.fitrange = False    
-
-            ## if any value is modify draw model with new value
-            if not self.fitrange:
-                #self.btFit.Disable()
-                if is_2Ddata: self.btEditMask.Disable()
-            else:
-                #self.btFit.Enable(True)
-                if is_2Ddata: self.btEditMask.Enable(True)
-
-            if is_modified and self.fitrange:
-                self.state_change= True
-                self._draw_model() 
-                self.Refresh()
-        return is_modified
-    
-    def _update_paramv_on_fit(self):
-        """
-        make sure that update param values just before the fitting
-        """
-        #flag for qmin qmax check values
-        flag = True
-        self.fitrange = True
-        is_modified = False
-
-        wx.PostEvent(self._manager.parent, StatusEvent(status=" \
-        updating ... ",type="update"))
-
-        ##So make sure that update param values on_Fit.
-        #self._undo.Enable(True)
-        if self.model !=None:           
-            ##Check the values
-            self._check_value_enter( self.fittable_param ,is_modified)
-            self._check_value_enter( self.fixed_param ,is_modified)
-            self._check_value_enter( self.parameters ,is_modified)
-
-            # If qmin and qmax have been modified, update qmin and qmax and 
-             # Here we should check whether the boundaries have been modified.
-            # If qmin and qmax have been modified, update qmin and qmax and 
-            # set the is_modified flag to True
-            self.fitrange = self._validate_qrange(self.qmin, self.qmax)
-            if self.fitrange:
-                tempmin = float(self.qmin.GetValue())
-                if tempmin != self.qmin_x:
-                    self.qmin_x = tempmin
-                tempmax = float(self.qmax.GetValue())
-                if tempmax != self.qmax_x:
-                    self.qmax_x = tempmax
-                if tempmax == tempmin:
-                    flag = False    
-                temp_smearer = None
-                if not self.disable_smearer.GetValue():
-                    temp_smearer= self.current_smearer
-                    if self.slit_smearer.GetValue():
-                        flag = self.update_slit_smear()
-                    elif self.pinhole_smearer.GetValue():
-                        flag = self.update_pinhole_smear()
-                    else:
-                        self._manager.set_smearer_nodraw(smearer=temp_smearer,
-                                                     qmin=float(self.qmin_x),
-                                                      qmax=float(self.qmax_x))
-                elif not self._is_2D():
-                    self._manager.set_smearer(smearer=temp_smearer,
-                                              qmin=float(self.qmin_x),
-                                                 qmax= float(self.qmax_x))
-                    index_data = ((self.qmin_x <= self.data.x)&\
-                                  (self.data.x <= self.qmax_x))
-                    val = str(len(self.data.x[index_data==True]))
-                    self.Npts_fit.SetValue(val)
-                    flag = True
-                if self._is_2D():
-                    # only 2D case set mask   
-                    flag = self._validate_Npts()
-                    if not flag:
-                        return flag
-            else: flag = False
-        else: 
-            flag = False
-
-        #For invalid q range, disable the mask editor and fit button, vs.    
-        if not self.fitrange:
-            #self.btFit.Disable()
-            if self._is_2D():self.btEditMask.Disable()
-        else:
-            #self.btFit.Enable(True)
-            if self._is_2D():self.btEditMask.Enable(True)
-
-        if not flag:
-            msg = "Cannot Plot or Fit :Must select a "
-            msg += " model or Fitting range is not valid!!!  "
-            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
-        
-        self.save_current_state()
-   
-        return flag                           
-               
-    def _is_modified(self, is_modified):
-        """
-        return to self._is_modified
-        """
-        return is_modified
-                       
-    def _reset_parameters_state(self, listtorestore, statelist):
-        """
-        Reset the parameters at the given state
-        """
-        if len(statelist) == 0 or len(listtorestore) == 0:
-            return
-        if len(statelist) !=  len(listtorestore):
-            return
-
-        for j in range(len(listtorestore)):
-            item_page = listtorestore[j]
-            item_page_info = statelist[j]
-            ##change the state of the check box for simple parameters
-            if item_page[0]!=None:   
-                item_page[0].SetValue(item_page_info[0])
-            if item_page[2]!=None:
-                item_page[2].SetValue(item_page_info[2])
-            if item_page[3]!=None:
-                ## show or hide text +/-
-                if item_page_info[2]:
-                    item_page[3].Show(True)
-                else:
-                    item_page[3].Hide()
-            if item_page[4]!=None:
-                ## show of hide the text crtl for fitting error
-                if item_page_info[4][0]:
-                    item_page[4].Show(True)
-                    item_page[4].SetValue(item_page_info[4][1])
-                else:
-                    item_page[3].Hide()
-            if item_page[5]!=None:
-                ## show of hide the text crtl for fitting error
-                if item_page_info[5][0]:
-                    item_page[5].Show(True)
-                    item_page[5].SetValue(item_page_info[5][1])
-                else:
-                    item_page[5].Hide()
-                    
-            if item_page[6]!=None:
-                ## show of hide the text crtl for fitting error
-                if item_page_info[6][0]:
-                    item_page[6].Show(True)
-                    item_page[6].SetValue(item_page_info[6][1])
-                else:
-                    item_page[6].Hide()
-                                      
-    def _copy_parameters_state(self, listtocopy, statelist):
-        """
-        copy the state of button 
-        
-        :param listtocopy: the list of check button to copy
-        :param statelist: list of state object to store the current state
-        
-        """
-        if len(listtocopy)==0:
-            return
-       
-        for item in listtocopy:
-  
-            checkbox_state = None
-            if item[0]!= None:
-                checkbox_state= item[0].GetValue()
-            parameter_name = item[1]
-            parameter_value = None
-            if item[2]!=None:
-                parameter_value = item[2].GetValue()
-            static_text = None
-            if item[3]!=None:
-                static_text = item[3].IsShown()
-            error_value = None
-            error_state = None
-            if item[4]!= None:
-                error_value = item[4].GetValue()
-                error_state = item[4].IsShown()
-                
-            min_value = None
-            min_state = None
-            if item[5]!= None:
-                min_value = item[5].GetValue()
-                min_state = item[5].IsShown()
-                
-            max_value = None
-            max_state = None
-            if item[6]!= None:
-                max_value = item[6].GetValue()
-                max_state = item[6].IsShown()
-            unit=None
-            if item[7]!=None:
-                unit = item[7].GetLabel()
-               
-            statelist.append([checkbox_state, parameter_name, parameter_value,
-                              static_text ,[error_state, error_value],
-                                [min_state, min_value],
-                                [max_state, max_value], unit])
-           
-    def _set_model_sizer_selection(self, model):
-        """
-        Display the sizer according to the type of the current model
-        """
-        if model == None:
-            return
-        if hasattr(model ,"s_model"):
-            
-            class_name = model.s_model.__class__
-            name = model.s_model.name
-            flag = (name != "NoStructure")
-            if flag and \
-                (class_name in self.model_list_box["Structure Factors"]):
-                self.structurebox.Show()
-                self.text2.Show()                
-                self.structurebox.Enable()
-                self.text2.Enable()
-                items = self.structurebox.GetItems()
-                self.sizer1.Layout()
-                
-                for i in range(len(items)):
-                    if items[i]== str(name):
-                        self.structurebox.SetSelection(i)
-                        break
-                    
-        if hasattr(model ,"p_model"):
-            class_name = model.p_model.__class__
-            name = model.p_model.name
-            self.formfactorbox.Clear()
-            
-            for k, list in self.model_list_box.iteritems():
-                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
-                    self.shape_rbutton.SetValue(True)
-                    ## fill the form factor list with new model
-                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
-                    items = self.formfactorbox.GetItems()
-                    ## set comboxbox to the selected item
-                    for i in range(len(items)):
-                        if items[i]== str(name):
-                            self.formfactorbox.SetSelection(i)
-                            break
-                    return
-                elif k == "Shape-Independent":
-                    self.shape_indep_rbutton.SetValue(True)
-                elif k == "Structure Factors":
-                     self.struct_rbutton.SetValue(True)
-                elif  k == "Multi-Functions":
-                    continue
-                else:
-                    self.plugin_rbutton.SetValue(True)
-               
-                if class_name in list:
-                    ## fill the form factor list with new model
-                    self._populate_box(self.formfactorbox, list)
-                    items = self.formfactorbox.GetItems()
-                    ## set comboxbox to the selected item
-                    for i in range(len(items)):
-                        if items[i]== str(name):
-                            self.formfactorbox.SetSelection(i)
-                            break
-                    break
-        else:
-
-            ## Select the model from the menu
-            class_name = model.__class__
-            name = model.name
-            self.formfactorbox.Clear()
-            items = self.formfactorbox.GetItems()
-    
-            for k, list in self.model_list_box.iteritems():          
-                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
-                    if class_name in self.model_list_box["P(Q)*S(Q)"]:
-                        self.structurebox.Show()
-                        self.text2.Show()
-                        self.structurebox.Enable()
-                        self.structurebox.SetSelection(0)
-                        self.text2.Enable()
-                    else:
-                        self.structurebox.Hide()
-                        self.text2.Hide()
-                        self.structurebox.Disable()
-                        self.structurebox.SetSelection(0)
-                        self.text2.Disable()
-                        
-                    self.shape_rbutton.SetValue(True)
-                    ## fill the form factor list with new model
-                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
-                    items = self.formfactorbox.GetItems()
-                    ## set comboxbox to the selected item
-                    for i in range(len(items)):
-                        if items[i]== str(name):
-                            self.formfactorbox.SetSelection(i)
-                            break
-                    return
-                elif k == "Shape-Independent":
-                    self.shape_indep_rbutton.SetValue(True)
-                elif k == "Structure Factors":
-                    self.struct_rbutton.SetValue(True)
-                elif  k == "Multi-Functions":
-                    continue
-                else:
-                    self.plugin_rbutton.SetValue(True)
-                if class_name in list:
-                    self.structurebox.SetSelection(0)
-                    self.structurebox.Disable()
-                    self.text2.Disable()                    
-                    ## fill the form factor list with new model
-                    self._populate_box(self.formfactorbox, list)
-                    items = self.formfactorbox.GetItems()
-                    ## set comboxbox to the selected item
-                    for i in range(len(items)):
-                        if items[i]== str(name):
-                            self.formfactorbox.SetSelection(i)
-                            break
-                    break
-    
-    def _draw_model(self):
-        """
-        Method to draw or refresh a plotted model.
-        The method will use the data member from the model page
-        to build a call to the fitting perspective manager.
-        """
-        if self.check_invalid_panel():
-            return
-        if self.model !=None:
-            temp_smear=None
-            if hasattr(self, "enable_smearer"):
-                if not self.disable_smearer.GetValue():
-                    temp_smear= self.current_smearer
-            
-            self._manager.draw_model(self.model, 
-                                    data=self.data,
-                                    smearer= temp_smear,
-                                    qmin=float(self.qmin_x), 
-                                    qmax=float(self.qmax_x),
-                                    qstep= float(self.num_points),
-                                    enable2D=self.enable2D)
-        
-    def _set_model_sizer(self,sizer, box_sizer, title="", object=None):
-        """
-        Use lists to fill a sizer for model info
-        """
-       
-        sizer.Clear(True)
-        ##For MAC, this should defined here.
-        if box_sizer == None:
-            box_description= wx.StaticBox(self, -1,str(title))
-            boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-        else:
-            boxsizer1 = box_sizer
-        sizer_buttons = wx.BoxSizer(wx.HORIZONTAL)    
-        #--------------------------------------------------------
-        self.shape_rbutton = wx.RadioButton(self, -1, 'Shapes', style=wx.RB_GROUP)
-        self.shape_indep_rbutton = wx.RadioButton(self, -1, "Shape-Independent")
-        self.struct_rbutton = wx.RadioButton(self, -1, "Structure Factor ")
-        self.plugin_rbutton = wx.RadioButton(self, -1, "Customized Models")
-                
-        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
-                            id= self.shape_rbutton.GetId() ) 
-        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
-                            id= self.shape_indep_rbutton.GetId() ) 
-        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
-                            id= self.struct_rbutton.GetId() ) 
-        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
-                            id= self.plugin_rbutton.GetId() )  
-        #MAC needs SetValue
-        self.shape_rbutton.SetValue(True)
-      
-        sizer_radiobutton = wx.GridSizer(2, 2,5, 5)
-        sizer_radiobutton.Add(self.shape_rbutton)
-        sizer_radiobutton.Add(self.shape_indep_rbutton)
-
-        sizer_radiobutton.Add(self.plugin_rbutton)
-        sizer_radiobutton.Add(self.struct_rbutton)
-        sizer_buttons.Add(sizer_radiobutton)
-        # detail button
-        if object !=None:
-            sizer_buttons.Add((50,0))
-            sizer_buttons.Add(object)
-        
-        sizer_selection = wx.BoxSizer(wx.HORIZONTAL)
-        mutifactor_selection = wx.BoxSizer(wx.HORIZONTAL)
-        
-        self.text1 = wx.StaticText( self,-1,"" )
-        self.text2 = wx.StaticText( self,-1,"P(Q)*S(Q)" )
-        self.mutifactor_text = wx.StaticText( self,-1,"No. of Shells: " )
-        self.mutifactor_text1 = wx.StaticText( self,-1,"" )
-        self.show_sld_button = wx.Button( self,-1,"Show SLD Profile" )
-        self.show_sld_button.Bind(wx.EVT_BUTTON,self._on_show_sld)
-
-        self.formfactorbox = wx.ComboBox(self, -1,style=wx.CB_READONLY)
-        if self.model!= None:
-            self.formfactorbox.SetValue(self.model.name)
-           
-        self.structurebox = wx.ComboBox(self, -1,style=wx.CB_READONLY)
-        self.multifactorbox = wx.ComboBox(self, -1,style=wx.CB_READONLY)
-        self.initialize_combox()
-             
-        wx.EVT_COMBOBOX(self.formfactorbox,-1, self._on_select_model)
-        wx.EVT_COMBOBOX(self.structurebox,-1, self._on_select_model)
-        wx.EVT_COMBOBOX(self.multifactorbox,-1, self._on_select_model)
-        
-        ## check model type to show sizer
-        if self.model !=None:
-            self._set_model_sizer_selection( self.model )
-        
-        sizer_selection.Add(self.text1)
-        sizer_selection.Add((5,5))
-        sizer_selection.Add(self.formfactorbox)
-        sizer_selection.Add((5,5))
-        sizer_selection.Add(self.text2)
-        sizer_selection.Add((5,5))
-        sizer_selection.Add(self.structurebox)
-        #sizer_selection.Add((5,5))
-        mutifactor_selection.Add((10,5))
-        mutifactor_selection.Add(self.mutifactor_text)
-        mutifactor_selection.Add(self.multifactorbox)
-        mutifactor_selection.Add((5,5))
-        mutifactor_selection.Add(self.mutifactor_text1)
-        mutifactor_selection.Add((10,5))
-        mutifactor_selection.Add(self.show_sld_button)
-
-        boxsizer1.Add( sizer_buttons )
-        boxsizer1.Add( (15,15))
-        boxsizer1.Add( sizer_selection )
-        boxsizer1.Add( (10,10))
-        boxsizer1.Add(mutifactor_selection)
-        
-        self._set_multfactor_combobox()
-        self.multifactorbox.SetSelection(1)
-        self.show_sld_button.Hide()
-        #--------------------------------------------------------
-        sizer.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
-        sizer.Layout()
-       
-    def _on_show_sld(self, event=None):
-        """
-        Plot SLD profile
-        """
-        # get profile data
-        x,y=self.model.getProfile()
-
-        from danse.common.plottools import Data1D
-        #from sans.perspectives.theory.profile_dialog import SLDPanel
-        from sans.guiframe.local_perspectives.plotting.profile_dialog \
-        import SLDPanel
-        sld_data = Data1D(x,y)
-        sld_data.name = 'SLD'
-        sld_data.axes = self.sld_axes
-        self.panel = SLDPanel(self, data=sld_data,axes =self.sld_axes,id =-1 )
-        self.panel.ShowModal()    
-        
-    def _set_multfactor_combobox(self, multiplicity=10):   
-        """
-        Set comboBox for muitfactor of CoreMultiShellModel
-        :param multiplicit: no. of multi-functionality
-        """
-        # build content of the combobox
-        for idx in range(0,multiplicity):
-            self.multifactorbox.Append(str(idx),int(idx))
-            #self.multifactorbox.SetSelection(1) 
-        self._hide_multfactor_combobox()
-        
-    def _show_multfactor_combobox(self):   
-        """
-        Show the comboBox of muitfactor of CoreMultiShellModel
-        """ 
-        if not self.mutifactor_text.IsShown():
-            self.mutifactor_text.Show(True)
-            self.mutifactor_text1.Show(True)
-        if not self.multifactorbox.IsShown():
-            self.multifactorbox.Show(True)  
-             
-    def _hide_multfactor_combobox(self):   
-        """
-        Hide the comboBox of muitfactor of CoreMultiShellModel
-        """ 
-        if self.mutifactor_text.IsShown():
-            self.mutifactor_text.Hide()
-            self.mutifactor_text1.Hide()
-        if self.multifactorbox.IsShown():
-            self.multifactorbox.Hide()   
-
-        
-    def _show_combox_helper(self):
-        """
-        Fill panel's combo box according to the type of model selected
-        """
-        if self.shape_rbutton.GetValue():
-            ##fill the combobox with form factor list
-            self.structurebox.SetSelection(0)
-            self.structurebox.Disable()
-            self.formfactorbox.Clear()
-            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
-        if self.shape_indep_rbutton.GetValue():
-            ##fill the combobox with shape independent  factor list
-            self.structurebox.SetSelection(0)
-            self.structurebox.Disable()
-            self.formfactorbox.Clear()
-            self._populate_box( self.formfactorbox,
-                                self.model_list_box["Shape-Independent"])
-        if self.struct_rbutton.GetValue():
-            ##fill the combobox with structure factor list
-            self.structurebox.SetSelection(0)
-            self.structurebox.Disable()
-            self.formfactorbox.Clear()
-            self._populate_box( self.formfactorbox,
-                                self.model_list_box["Structure Factors"])
-        if self.plugin_rbutton.GetValue():
-            ##fill the combobox with form factor list
-            self.structurebox.Disable()
-            self.formfactorbox.Clear()
-            self._populate_box( self.formfactorbox,
-                                self.model_list_box["Customized Models"])
-        
-    def _show_combox(self, event=None):
-        """
-        Show combox box associate with type of model selected
-        """
-        if self.check_invalid_panel():
-            self.shape_rbutton.SetValue(True)
-            return
-
-        self._show_combox_helper()
-        self._on_select_model(event=None)
-        self._save_typeOfmodel()
-        self.sizer4_4.Layout()
-        self.sizer4.Layout()
-        self.Layout()
-        self.Refresh()
-  
-    def _populate_box(self, combobox, list):
-        """
-        fill combox box with dict item
-        
-        :param list: contains item to fill the combox
-            item must model class
-        """
-        st = time.time()
-        for models in list:
-            model= models()
-            name = model.__class__.__name__
-            if models.__name__!="NoStructure":
-                if hasattr(model, "name"):
-                    name = model.name
-                combobox.Append(name,models)
-        return 0
-
-    def _onQrangeEnter(self, event):
-        """
-        Check validity of value enter in the Q range field
-        """
-        
-        tcrtl= event.GetEventObject()
-        #Clear msg if previously shown.
-        msg= ""
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        # Flag to register when a parameter has changed.
-        is_modified = False
-        if tcrtl.GetValue().lstrip().rstrip()!="":
-            try:
-                value = float(tcrtl.GetValue())
-                tcrtl.SetBackgroundColour(wx.WHITE)
-
-                # If qmin and qmax have been modified, update qmin and qmax
-                if self._validate_qrange( self.qmin, self.qmax):
-                    tempmin = float(self.qmin.GetValue())
-                    if tempmin != self.qmin_x:
-                        self.qmin_x = tempmin
-                    tempmax = float(self.qmax.GetValue())
-                    if tempmax != self.qmax_x:
-                        self.qmax_x = tempmax
-                else:
-                    tcrtl.SetBackgroundColour("pink")
-                    msg= "Model Error:wrong value entered : %s"% sys.exc_value
-                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                    return  
-            except:
-                tcrtl.SetBackgroundColour("pink")
-                msg= "Model Error:wrong value entered : %s"% sys.exc_value
-                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                return 
-            #Check if # of points for theory model are valid(>0).
-            if self.npts != None:
-                if check_float(self.npts):
-                    temp_npts = float(self.npts.GetValue())
-                    if temp_npts !=  self.num_points:
-                        self.num_points = temp_npts
-                        is_modified = True
-                else:
-                    msg= "Cannot Plot :No npts in that Qrange!!!  "
-                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        else:
-           tcrtl.SetBackgroundColour("pink")
-           msg= "Model Error:wrong value entered!!!"
-           wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
-        #self._undo.Enable(True)
-        self.save_current_state()
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        self.state_change= False
-        #Draw the model for a different range
-        self._draw_model()
-                   
-    def _on_select_model_helper(self): 
-        """
-        call back for model selection
-        """
-        ## reset dictionary containing reference to dispersion
-        self._disp_obj_dict = {}
-        self.disp_cb_dict ={}
-        
-        f_id = self.formfactorbox.GetCurrentSelection()
-        #For MAC
-        form_factor = None
-        if f_id >= 0:
-            form_factor = self.formfactorbox.GetClientData(f_id)
-
-        if not form_factor in  self.model_list_box["multiplication"]:
-            self.structurebox.Hide()
-            self.text2.Hide()           
-            self.structurebox.Disable()
-            self.structurebox.SetSelection(0)
-            self.text2.Disable()
-        else:
-            self.structurebox.Show()
-            self.text2.Show()
-            self.structurebox.Enable()
-            self.text2.Enable()
-            
-        if form_factor != None:    
-            # set multifactor for Mutifunctional models    
-            if form_factor().__class__ in self.model_list_box["Multi-Functions"]:
-                m_id = self.multifactorbox.GetCurrentSelection()
-                multiplicity = form_factor().multiplicity_info[0]
-                self.multifactorbox.Clear()
-                #self.mutifactor_text.SetLabel(form_factor().details[])
-                self._set_multfactor_combobox(multiplicity)
-                self._show_multfactor_combobox()
-                #ToDo:  this info should be called directly from the model 
-                text = form_factor().multiplicity_info[1]#'No. of Shells: '
-
-                #self.mutifactor_text.Clear()
-                self.mutifactor_text.SetLabel(text)
-                if m_id > multiplicity -1:
-                    # default value
-                    m_id = 1
-                    
-                self.multi_factor = self.multifactorbox.GetClientData(m_id)
-                if self.multi_factor == None: self.multi_factor =0
-                form_factor = form_factor(int(self.multi_factor))
-                self.multifactorbox.SetSelection(m_id)
-                # Check len of the text1 and max_multiplicity
-                text = ''
-                if form_factor.multiplicity_info[0] == len(form_factor.multiplicity_info[2]):
-                    text = form_factor.multiplicity_info[2][self.multi_factor]
-                self.mutifactor_text1.SetLabel(text)
-                # Check if model has  get sld profile.
-                if len(form_factor.multiplicity_info[3]) > 0:
-                    self.sld_axes = form_factor.multiplicity_info[3]
-                    self.show_sld_button.Show(True)
-                else:
-                    self.sld_axes = ""
-
-            else:
-                self._hide_multfactor_combobox()
-                self.show_sld_button.Hide()
-                form_factor = form_factor()
-                self.multi_factor = None
-        else:
-            self._hide_multfactor_combobox()
-            self.show_sld_button.Hide()
-            self.multi_factor = None  
-              
-        s_id = self.structurebox.GetCurrentSelection()
-        struct_factor = self.structurebox.GetClientData( s_id )
-        
-        if  struct_factor !=None:
-            from sans.models.MultiplicationModel import MultiplicationModel
-            self.model= MultiplicationModel(form_factor,struct_factor())
-            
-        else:
-            if form_factor != None:
-                self.model= form_factor
-            else:
-                self.model = None
-                return self.model
-            
-
-        ## post state to fit panel
-        self.state.parameters =[]
-        self.state.model =self.model
-        self.state.qmin = self.qmin_x
-        self.state.multi_factor = self.multi_factor
-        self.disp_list =self.model.getDispParamList()
-        self.state.disp_list = self.disp_list
-        self.Layout()     
-        
-    def _validate_qrange(self, qmin_ctrl, qmax_ctrl):
-        """
-        Verify that the Q range controls have valid values
-        and that Qmin < Qmax.
-        
-        :param qmin_ctrl: text control for Qmin
-        :param qmax_ctrl: text control for Qmax
-        
-        :return: True is the Q range is value, False otherwise 
-        
-        """
-        qmin_validity = check_float(qmin_ctrl)
-        qmax_validity = check_float(qmax_ctrl)
-        if not (qmin_validity and qmax_validity):
-            return False
-        else:
-            qmin = float(qmin_ctrl.GetValue())
-            qmax = float(qmax_ctrl.GetValue())
-            if qmin <= qmax:
-                #Make sure to set both colours white.  
-                qmin_ctrl.SetBackgroundColour(wx.WHITE)
-                qmin_ctrl.Refresh()
-                qmax_ctrl.SetBackgroundColour(wx.WHITE)
-                qmax_ctrl.Refresh()
-            else:
-                qmin_ctrl.SetBackgroundColour("pink")
-                qmin_ctrl.Refresh()
-                qmax_ctrl.SetBackgroundColour("pink")
-                qmax_ctrl.Refresh()
-                msg= "Invalid Q range: Q min must be smaller than Q max"
-                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
-                return False
-        return True
-    
-    def _validate_Npts(self):  
-        """
-        Validate the number of points for fitting is more than 10 points.
-        If valid, setvalues Npts_fit otherwise post msg.
-        """
-        #default flag
-        flag = True
-
-        # q value from qx and qy
-        radius= numpy.sqrt( self.data.qx_data * self.data.qx_data + 
-                            self.data.qy_data * self.data.qy_data )
-        #get unmasked index
-        index_data = (float(self.qmin.GetValue()) <= radius) & \
-                        (radius <= float(self.qmax.GetValue()))
-        index_data = (index_data) & (self.data.mask) 
-        index_data = (index_data) & (numpy.isfinite(self.data.data))
-
-        if len(index_data[index_data]) < 10:
-            # change the color pink.
-            self.qmin.SetBackgroundColour("pink")
-            self.qmin.Refresh()
-            self.qmax.SetBackgroundColour("pink")
-            self.qmax.Refresh()
-            msg= "Cannot Plot :No or too little npts in that data range!!!  "
-            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-            self.fitrange = False
-            flag = False
-        else:
-            self.Npts_fit.SetValue(str(len(self.data.mask[index_data==True])))
-            self.fitrange = True
-            
-        return flag
-    
-    def _check_value_enter(self, list, modified):
-        """
-        :param list: model parameter and panel info
-        :Note: each item of the list should be as follow:
-            item=[check button state, parameter's name,
-                paramater's value, string="+/-", 
-                parameter's error of fit, 
-                parameter's minimum value, 
-                parrameter's maximum value , 
-                parameter's units]
-        """  
-        is_modified =  modified
-        if len(list)==0:
-            return is_modified
-        for item in list:
-            #skip angle parameters for 1D
-            if self.data.__class__.__name__ !="Data2D":
-                if item in self.orientation_params:
-                    continue
-            #try:
-            name = str(item[1])
-            
-            if string.find(name,".npts") ==-1 and string.find(name,".nsigmas")==-1:      
-                ## check model parameters range             
-                param_min= None
-                param_max= None
-               
-                ## check minimun value
-                if item[5]!= None and item[5]!= "":
-                    if item[5].GetValue().lstrip().rstrip()!="":
-                        try:
-                            
-                            param_min = float(item[5].GetValue())
-                            if not self._validate_qrange(item[5],item[2]):
-                                if numpy.isfinite(param_min):
-                                    item[2].SetValue(format_number(param_min))
-                            
-                            item[5].SetBackgroundColour(wx.WHITE)
-                            item[2].SetBackgroundColour(wx.WHITE)
-                                           
-                        except:
-                            msg = "Wrong Fit parameter range entered "
-                            wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
-                            raise ValueError, msg
-                        is_modified = True
-                ## check maximum value
-                if item[6]!= None and item[6]!= "":
-                    if item[6].GetValue().lstrip().rstrip()!="":
-                        try:                          
-                            param_max = float(item[6].GetValue())
-                            if not self._validate_qrange(item[2],item[6]):
-                                if numpy.isfinite(param_max):
-                                    item[2].SetValue(format_number(param_max))  
-                            
-                            item[6].SetBackgroundColour(wx.WHITE)
-                            item[2].SetBackgroundColour(wx.WHITE)
-                        except:
-                            msg = "Wrong Fit parameter range entered "
-                            wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
-                            raise ValueError, msg
-                        is_modified = True
-                
-
-                if param_min != None and param_max !=None:
-                    if not self._validate_qrange(item[5], item[6]):
-                        msg= "Wrong Fit range entered for parameter "
-                        msg+= "name %s of model %s "%(name, self.model.name)
-                        wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
-                
-                if name in self.model.details.keys():   
-                        self.model.details[name][1:3]= param_min,param_max
-                        is_modified = True
-              
-                else:
-                        self.model.details [name] = ["",param_min,param_max] 
-                        is_modified = True
-            try:     
-                value= float(item[2].GetValue())
-      
-                # If the value of the parameter has changed,
-                # +update the model and set the is_modified flag
-                if value != self.model.getParam(name) and numpy.isfinite(value):
-                    self.model.setParam(name,value)
-                    is_modified = True   
-            except:
-                msg = "Wrong Fit parameter value entered "
-                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
-                
-        return is_modified 
-        
- 
-    def _set_dipers_Param(self, event):
-        """
-        respond to self.enable_disp and self.disable_disp radio box.
-        The dispersity object is reset inside the model into Gaussian. 
-        When the user select yes , this method display a combo box for more selection
-        when the user selects No,the combo box disappears.
-        Redraw the model with the default dispersity (Gaussian)
-        """
-        if self.check_invalid_panel():
-            return 
-        ## On selction if no model exists.
-        if self.model ==None:
-            self.disable_disp.SetValue(True)
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Polydispersion: %s"%msg))
-            return
-
-        self._reset_dispersity()
-    
-        if self.model ==None:
-            self.model_disp.Hide()
-            self.disp_box.Hide()
-            self.sizer4_4.Clear(True)
-            return
-
-        if self.enable_disp.GetValue():
-            self.model_disp.Show(True)
-            self.disp_box.Show(True)
-            ## layout for model containing no dispersity parameters
-            
-            self.disp_list= self.model.getDispParamList()
-             
-            if len(self.disp_list)==0 and len(self.disp_cb_dict)==0:
-                self._layout_sizer_noDipers()  
-            else:
-                ## set gaussian sizer 
-                self._on_select_Disp(event=None)
-        else:
-            self.model_disp.Hide()
-            self.disp_box.Hide()
-            self.disp_box.SetSelection(0) 
-            self.sizer4_4.Clear(True)
-            
-        ## post state to fit panel 
-        self.save_current_state()
-        if event !=None:
-            #self._undo.Enable(True)
-            event = PageInfoEvent(page = self)
-            wx.PostEvent(self.parent, event)
-        #draw the model with the current dispersity
-        self._draw_model()
-        self.sizer4_4.Layout()
-        self.sizer5.Layout()
-        self.Layout()
-        self.Refresh()      
-          
-        
-    def _layout_sizer_noDipers(self):
-        """
-        Draw a sizer with no dispersity info
-        """
-        ix=0
-        iy=1
-        self.fittable_param=[]
-        self.fixed_param=[]
-        self.orientation_params_disp=[]
-        
-        self.model_disp.Hide()
-        self.disp_box.Hide()
-        self.sizer4_4.Clear(True)
-        model_disp = wx.StaticText(self, -1, 'No PolyDispersity for this model')
-        self.sizer4_4.Add(model_disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-        self.sizer4_4.Layout()
-        self.sizer4.Layout()
-    
-    def _reset_dispersity(self):
-        """
-        put gaussian dispersity into current model
-        """
-        if len(self.param_toFit)>0:
-            for item in self.fittable_param:
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-
-            for item in self.orientation_params_disp:
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-         
-        self.fittable_param=[]
-        self.fixed_param=[]
-        self.orientation_params_disp=[]
-        self.values=[]
-        self.weights=[]
-      
-        from sans.models.dispersion_models import GaussianDispersion, ArrayDispersion
-        if len(self.disp_cb_dict)==0:
-            self.save_current_state()
-            self.sizer4_4.Clear(True)
-            self.Layout()
- 
-            return 
-        if (len(self.disp_cb_dict)>0) :
-            for p in self.disp_cb_dict:
-                # The parameter was un-selected. Go back to Gaussian model (with 0 pts)                    
-                disp_model = GaussianDispersion()
-               
-                self._disp_obj_dict[p] = disp_model
-                # Set the new model as the dispersion object for the selected parameter
-                try:
-                   self.model.set_dispersion(p, disp_model)
-                except:
-
-                    pass
-
-        ## save state into
-        self.save_current_state()
-        self.Layout()  
-        self.Refresh()
-                  
-    def _on_select_Disp(self,event):
-        """
-        allow selecting different dispersion
-        self.disp_list should change type later .now only gaussian
-        """
-        n = self.disp_box.GetCurrentSelection()
-        name = self.disp_box.GetValue()
-        dispersity= self.disp_box.GetClientData(n)
-        self.disp_name = name
-        
-        if name.lower() == "array":
-            self._set_sizer_arraydispersion()
-        else:
-            self._set_sizer_dispersion(dispersity= dispersity)
-            
-        self.state.disp_box= n
-        ## Redraw the model
-        self._draw_model() 
-        #self._undo.Enable(True)
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        
-        self.sizer4_4.Layout()
-        self.sizer4.Layout()
-    
-    def _set_sizer_arraydispersion(self):
-        """
-        draw sizer with array dispersity  parameters
-        """
-        
-        if len(self.param_toFit)>0:
-            for item in self.fittable_param:
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-            for item in self.orientation_params_disp:
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-        for item in self.model.details.keys():
-            if item in self.model.fixed:
-                del self.model.details [item]                           
-
-        self.fittable_param=[]
-        self.fixed_param=[]
-        self.orientation_params_disp=[]
-        self.sizer4_4.Clear(True) 
-        self._reset_dispersity()
-        ix=0
-        iy=1     
-        disp1 = wx.StaticText(self, -1, 'Array Dispersion')
-        self.sizer4_4.Add(disp1,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-        
-        # Look for model parameters to which we can apply an ArrayDispersion model
-        # Add a check box for each parameter.
-        self.disp_cb_dict = {}
-        ix+=1 
-        self.noDisper_rbox = wx.RadioButton(self, -1,"None", (10, 10),style= wx.RB_GROUP)
-        self.Bind(wx.EVT_RADIOBUTTON,self.select_disp_angle , id=self.noDisper_rbox.GetId())
-        #MAC needs SetValue
-        self.noDisper_rbox.SetValue(True)
-        self.sizer4_4.Add(self.noDisper_rbox, (iy, ix),
-                           (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        
-        for p in self.model.dispersion.keys():
-            if not p in self.model.orientation_params:
-                ix+=1 
-                self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10))
-                self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
-                self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId())
-                self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        
-        for p in self.model.dispersion.keys():
-            if p in self.model.orientation_params:
-                ix+=1 
-                self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10))
-                self.state.disp_cb_dict[p]=  self.disp_cb_dict[p].GetValue()
-                if not (self.enable2D or self.data.__class__.__name__ =="Data2D"):
-                    self.disp_cb_dict[p].Hide()
-                else:
-                    self.disp_cb_dict[p].Show(True)
-                self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId())
-                self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-
-
-        ix =0
-        iy +=1 
-        self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)        
-        self.Layout()
-
-        self.state.orientation_params =[]
-        self.state.orientation_params_disp =[]
-        self.state.parameters =[]
-        self.state.fittable_param =[]
-        self.state.fixed_param =[]
-        
-        ## save checkbutton state and txtcrtl values
-        
-        self._copy_parameters_state(self.orientation_params,
-                                     self.state.orientation_params)
-
-        self._copy_parameters_state(self.orientation_params_disp,
-                                     self.state.orientation_params_disp)
-        
-        self._copy_parameters_state(self.parameters, self.state.parameters)
-        self._copy_parameters_state(self.fittable_param, self.state.fittable_param)
-        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
-        
-        
-        ## post state to fit panel
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        
-    def _set_range_sizer(self, title, box_sizer=None, object1=None,object=None):
-        """
-        Fill the Q range sizer
-        """
-        #2D data? default
-        is_2Ddata = False
-        
-        #check if it is 2D data
-        if self.data.__class__.__name__ == 'Data2D':
-            is_2Ddata = True
-            
-        self.sizer5.Clear(True)
-        #--------------------------------------------------------------
-        if box_sizer == None:
-            box_description= wx.StaticBox(self, -1,str(title))
-            boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-        else:
-            #for MAC
-            boxsizer1 = box_sizer
-
-        self.qmin    = self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self._onQrangeEnter)
-        self.qmin.SetValue(str(self.qmin_x))
-        self.qmin.SetToolTipString("Minimun value of Q in linear scale.")
-     
-        self.qmax    = self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self._onQrangeEnter)
-        self.qmax.SetValue(str(self.qmax_x))
-        self.qmax.SetToolTipString("Maximum value of Q in linear scale.")
-        
-        id = wx.NewId()
-        self.reset_qrange =wx.Button(self,id,'Reset',size=(77,20))
-      
-        self.reset_qrange.Bind(wx.EVT_BUTTON, self.on_reset_clicked,id=id)
-        self.reset_qrange.SetToolTipString("Reset Q range to the default values")
-     
-        sizer_horizontal=wx.BoxSizer(wx.HORIZONTAL)
-        sizer= wx.GridSizer(2, 4,2, 6)
-
-        self.btEditMask = wx.Button(self,wx.NewId(),'Editor', size=(88,23))
-        self.btEditMask.Bind(wx.EVT_BUTTON, self._onMask,id= self.btEditMask.GetId())
-        self.btEditMask.SetToolTipString("Edit Mask.")
-        self.EditMask_title = wx.StaticText(self, -1, ' Masking(2D)')
-
-        sizer.Add(wx.StaticText(self, -1, '    Q range'))     
-        sizer.Add(wx.StaticText(self, -1, ' Min[1/A]'))
-        sizer.Add(wx.StaticText(self, -1, ' Max[1/A]'))
-        sizer.Add(self.EditMask_title)
-        sizer.Add(self.reset_qrange)   
-        
-        sizer.Add(self.qmin)
-        sizer.Add(self.qmax)
-        sizer.Add(self.btEditMask)
-       
-        if object1!=None:
-            
-            boxsizer1.Add(object1) 
-            boxsizer1.Add((10,10))
-        boxsizer1.Add(sizer)
-        if object!=None:
-            boxsizer1.Add((10,15))
-            boxsizer1.Add(object)
-        if is_2Ddata:
-            self.btEditMask.Enable()  
-            self.EditMask_title.Enable() 
-        else:
-            self.btEditMask.Disable()  
-            self.EditMask_title.Disable()
-        ## save state
-        self.save_current_state()
-        #----------------------------------------------------------------
-        self.sizer5.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
-        self.sizer5.Layout()
-
-    def _lay_out(self):
-        """
-        returns self.Layout
-        
-        :Note: Mac seems to like this better when self.
-            Layout is called after fitting.
-        """
-        self._sleep4sec()
-        self.Layout()
-        return 
-    
-    def _sleep4sec(self):
-        """
-            sleep for 1 sec only applied on Mac
-            Note: This 1sec helps for Mac not to crash on self.:ayout after self._draw_model
-        """
-        if ON_MAC == True:
-            time.sleep(1)
-            
-    def on_reset_clicked(self,event):
-        """
-        On 'Reset' button  for Q range clicked
-        """
-        flag = True
-        if self.check_invalid_panel():
-            return
-        ##For 3 different cases: Data2D, Data1D, and theory
-        if self.data.__class__.__name__ == "Data2D":
-            data_min= 0
-            x= max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
-            y= max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
-            self.qmin_x = data_min
-            self.qmax_x = math.sqrt(x*x + y*y)
-            # check smearing
-            if not self.disable_smearer.GetValue():
-                temp_smearer= self.current_smearer
-                ## set smearing value whether or not the data contain the smearing info
-                if self.pinhole_smearer.GetValue():
-                    flag = self.update_pinhole_smear()
-                else:
-                    flag = True
-        elif self.data.__class__.__name__ != "Data2D":
-            self.qmin_x = min(self.data.x)
-            self.qmax_x = max(self.data.x)
-            # check smearing
-            if not self.disable_smearer.GetValue():
-                temp_smearer= self.current_smearer
-                ## set smearing value whether or not the data contain the smearing info
-                if self.slit_smearer.GetValue():
-                    flag = self.update_slit_smear()
-                elif self.pinhole_smearer.GetValue():
-                    flag = self.update_pinhole_smear()
-                else:
-                    flag = True
-        else:
-            self.qmin_x = _QMIN_DEFAULT
-            self.qmax_x = _QMAX_DEFAULT
-            self.num_points = _NPTS_DEFAULT            
-            self.state.npts = self.num_points
-            
-        if flag == False:
-            msg= "Cannot Plot :Must enter a number!!!  "
-            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        else:
-            # set relative text ctrs.
-            self.qmin.SetValue(str(self.qmin_x))
-            self.qmax.SetValue(str(self.qmax_x))
-            self.set_npts2fit()
-            # At this point, some button and variables satatus (disabled?) should be checked 
-            # such as color that should be reset to white in case that it was pink.
-            self._onparamEnter_helper()
-
-        self.save_current_state()
-        self.state.qmin = self.qmin_x
-        self.state.qmax = self.qmax_x
-        
-        #reset the q range values
-        self._reset_plotting_range(self.state)
-        #self.compute_chisqr(smearer=self.current_smearer)
-        #Re draw plot
-        self._draw_model()
-
-    def on_model_help_clicked(self,event):
-        """
-        on 'More details' button
-        """
-        from help_panel import  HelpWindow
-        
-        if self.model == None:
-            name = 'FuncHelp'
-        else:
-            name = self.model.origin_name
-
-        frame = HelpWindow(None, -1,  pageToOpen="media/model_functions.html")    
-        frame.Show(True)
-        if frame.rhelp.HasAnchor(name):
-            frame.rhelp.ScrollToAnchor(name)
-        else:
-           msg= "Model does not contains an available description "
-           msg +="Please try searching in the Help window"
-           wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))                    
-                
Index: nsview/perspectives/fitting/Copy of fitpage.py
===================================================================
--- sansview/perspectives/fitting/Copy of fitpage.py	(revision a07e72f8fb8281178797bf691b36e56274d8580b)
+++ 	(revision )
@@ -1,2611 +1,0 @@
-
-
-import sys
-import wx
-import wx.lib.newevent
-import numpy
-import copy
-import math
-import time
-from sans.models.dispersion_models import ArrayDispersion, GaussianDispersion
-from DataLoader.data_info import Data1D
-from sans.guiframe.events import StatusEvent   
-from sans.guiframe.utils import format_number,check_float
-
-
-
-## event to know the selected fit engine
-(FitterTypeEvent, EVT_FITTER_TYPE)   = wx.lib.newevent.NewEvent()
-(FitStopEvent, EVT_FIT_STOP)   = wx.lib.newevent.NewEvent()
-(Chi2UpdateEvent, EVT_CHI2_UPDATE)   = wx.lib.newevent.NewEvent()
-_BOX_WIDTH = 76
-_DATA_BOX_WIDTH = 300
-SMEAR_SIZE_L = 0.005
-SMEAR_SIZE_H = 0.006
-
-import basepage
-from basepage import BasicPage
-from basepage import PageInfoEvent
-from DataLoader.qsmearing import smear_selection
-
-class FitPage(BasicPage):
-    """
-    FitPanel class contains fields allowing to display results when
-    fitting  a model and one data
-    
-    :note: For Fit to be performed the user should check at least one parameter
-        on fit Panel window.
-    """
-    
-    def __init__(self,parent, page_info):
-        """ 
-        Initialization of the Panel
-        """
-        BasicPage.__init__(self, parent, page_info)
- 
-        ## draw sizer
-        self._fill_datainfo_sizer()
-        # get smear info from data
-        self._get_smear_info()
-        self._fill_model_sizer( self.sizer1)
-        self._get_defult_custom_smear()
-        self._fill_range_sizer() 
-        
-        if self.data is None:
-            self.formfactorbox.Disable()
-            self.structurebox.Disable()
-        else:
-            self.smearer = smear_selection(self.data, self.model)
-            if self.smearer ==None:
-                self.enable_smearer.Disable()
-        ## to update the panel according to the fit engine type selected
-        self.Bind(EVT_FITTER_TYPE,self._on_engine_change)
-        self.Bind(EVT_FIT_STOP,self._on_fit_complete)
-        self.Bind(EVT_CHI2_UPDATE, self.on_complete_chisqr)
-        self._set_bookmark_flag(False)
-        self._set_save_flag(False)
-
-    def _on_fit_complete(self, event):
-        """
-        When fit is complete ,reset the fit button label.
-        """
-        #self.btFit.SetLabel("Fit")
-        #self.btFit.Unbind(event=wx.EVT_BUTTON, id=self.btFit.GetId())
-        #self.btFit.Bind(event=wx.EVT_BUTTON, handler=self._onFit,id=self.btFit.GetId())
-        pass
-        
-    def _is_2D(self):
-        """
-        Check if data_name is Data2D
-        
-        :return: True or False
-        
-        """
-        
-        if self.data.__class__.__name__ =="Data2D":
-            return True
-        return False
-            
-    def _on_engine_change(self, event):
-        """
-        get an event containing the current name of the fit engine type
-        
-        :param event: FitterTypeEvent containing  the name of the current engine
-        
-        """
-        self.engine_type = event.type
-        self.state.engine_type = self.engine_type
-        if len(self.parameters)==0:
-            self.Layout()
-            return
-        if event.type =="park":
-            self.btFit.SetLabel("Fit")
-
-        for item in self.parameters:
-            if event.type =="scipy" :
-                item[5].SetValue("")
-                item[5].Hide()
-                item[6].SetValue("")
-                item[6].Hide()
-                self.text2_min.Hide()
-                self.text2_max.Hide()
-
-            else:
-                item[5].Show(True)
-                item[6].Show(True)
-                self.text2_min.Show(True)
-                self.text2_max.Show(True)
-        for item in self.fittable_param:
-            if item[5]!=None and item[6]!=None and not item in self.orientation_params_disp:
-                if event.type =="scipy" and not item in self.orientation_params:
-                    item[5].SetValue("")
-                    item[5].Hide()
-                    item[6].SetValue("")
-                    item[6].Hide()
-                    self.text2_min.Hide()
-                    self.text2_max.Hide()
-                    self.text_disp_min.Hide()
-                    self.text_disp_max.Hide()
-                else:
-                    item[5].Show(True)
-                    item[6].Show(True)
-                    self.text2_min.Show(True)
-                    self.text2_max.Show(True)
-                    self.text_disp_min.Show(True)
-                    self.text_disp_max.Show(True)
-            
-        for item in self.orientation_params:
-            if item[5]!=None and item[6]!=None:
-                if event.type =="scipy" or self.data.__class__.__name__ !="Data2D":
-                    item[5].SetValue("")
-                    item[5].Hide()
-                    item[6].SetValue("")
-                    item[6].Hide()
-                else:
-                    item[5].Show(True)
-                    item[6].Show(True)
-                    
-        for item in self.orientation_params_disp:         
-            if item[5]!=None and item[6]!=None:
-                if event.type =="scipy" or self.data.__class__.__name__ !="Data2D":
-                    item[5].SetValue("")
-                    item[5].Hide()
-                    item[6].SetValue("")
-                    item[6].Hide()
-                else:
-                    item[5].Show(True)
-                    item[6].Show(True)
-        self.Layout()
-        self.Refresh()
-
-    def _fill_range_sizer(self):
-        """
-        Fill the sizer containing the plotting range
-        add  access to npts
-        """
-        is_2Ddata = False
-        
-        # Check if data is 2D
-        if self.data.__class__.__name__ == 'Data2D':
-            is_2Ddata = True
-            
-        title = "Fitting"
-        #smear messages & titles
-        smear_message_none  =  "No smearing is selected..."
-        smear_message_dqdata  =  "The dQ data is being used for smearing..."
-        smear_message_2d  =  "Higher accuracy is very time-expensive. Use it with care..."
-        smear_message_new_ssmear  =  "Please enter only the value of interest to customize smearing..."
-        smear_message_new_psmear  =  "Please enter both; the dQ will be generated by interpolation..."
-        smear_message_2d_x_title = "<dQx>[1/A]:"
-        smear_message_2d_y_title = "<dQy>[1/A]:"
-        smear_message_pinhole_min_title = "dQ_low[1/A]:"
-        smear_message_pinhole_max_title = "dQ_high[1/A]:"
-        smear_message_slit_height_title = "Slit height[1/A]:"
-        smear_message_slit_width_title = "Slit width[1/A]:"
-        
-        self._get_smear_info()
-        
-        #Sizers
-        box_description_range = wx.StaticBox(self, -1,str(title))
-        boxsizer_range = wx.StaticBoxSizer(box_description_range, wx.VERTICAL)      
-        self.sizer_set_smearer = wx.BoxSizer(wx.VERTICAL)
-        sizer_smearer = wx.BoxSizer(wx.HORIZONTAL)
-        self.sizer_new_smear= wx.BoxSizer(wx.HORIZONTAL)
-        self.sizer_set_masking = wx.BoxSizer(wx.HORIZONTAL)
-        sizer_chi2 = wx.BoxSizer(wx.VERTICAL)
-        smear_set_box= wx.StaticBox(self, -1,'Set Instrumental Smearing')
-        sizer_smearer_box = wx.StaticBoxSizer(smear_set_box, wx.HORIZONTAL)
-        sizer_smearer_box.SetMinSize((_DATA_BOX_WIDTH,85))
-        sizer_fit = wx.GridSizer(2, 4,2,6)
-        
-        # combobox for smear2d accuracy selection
-        self.smear_accuracy = wx.ComboBox(self, -1,size=(50,-1),style=wx.CB_READONLY)
-        self._set_accuracy_list()
-        self.smear_accuracy.SetValue(self.smear2d_accuracy)
-        self.smear_accuracy.SetSelection(0)
-        self.smear_accuracy.SetToolTipString("'Higher' uses more Gaussian points for smearing computation.")
-                   
-        wx.EVT_COMBOBOX(self.smear_accuracy,-1, self._on_select_accuracy)
-
-        #Fit button
-        self.btFit = wx.Button(self,wx.NewId(),'Fit', size=(88,25))
-        self.btFit.Bind(wx.EVT_BUTTON, self._onFit,id= self.btFit.GetId())
-        self.btFit.SetToolTipString("Start fitting.")
-        
-        #textcntrl for custom resolution
-        self.smear_pinhole_max = self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH-25,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self.onPinholeSmear)
-        self.smear_pinhole_min = self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH-25,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self.onPinholeSmear)
-        self.smear_slit_height= self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH-25,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self.onSlitSmear)
-        self.smear_slit_width = self.ModelTextCtrl(self, -1,size=(_BOX_WIDTH-25,20),style=wx.TE_PROCESS_ENTER,
-                                            text_enter_callback = self.onSlitSmear)
-
-        ## smear
-        self.smear_data_left= BGTextCtrl(self, -1, size=(_BOX_WIDTH-25,20), style=0)
-        self.smear_data_left.SetValue(str(self.dq_l))
-        self.smear_data_right = BGTextCtrl(self, -1, size=(_BOX_WIDTH-25,20), style=0)
-        self.smear_data_right.SetValue(str(self.dq_r))
-
-        #set default values for smear
-        self.smear_pinhole_max.SetValue(str(self.dx_max))
-        self.smear_pinhole_min.SetValue(str(self.dx_min))
-        self.smear_slit_height.SetValue(str(self.dxl))
-        self.smear_slit_width.SetValue(str(self.dxw))
-
-        #Filling the sizer containing instruments smearing info.
-        self.disable_smearer = wx.RadioButton(self, -1, 'None', style=wx.RB_GROUP)
-        self.enable_smearer = wx.RadioButton(self, -1, 'Use dQ Data')
-        #self.enable_smearer.SetToolTipString("Click to use the loaded dQ data for smearing.")
-        self.pinhole_smearer = wx.RadioButton(self, -1, 'Custom Pinhole Smear')
-        #self.pinhole_smearer.SetToolTipString("Click to input custom resolution for pinhole smearing.")
-        self.slit_smearer = wx.RadioButton(self, -1, 'Custom Slit Smear')
-        #self.slit_smearer.SetToolTipString("Click to input custom resolution for slit smearing.")
-        self.Bind(wx.EVT_RADIOBUTTON, self.onSmear, id=self.disable_smearer.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.onSmear, id=self.enable_smearer.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.onPinholeSmear, id=self.pinhole_smearer.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.onSlitSmear, id=self.slit_smearer.GetId())
-        self.disable_smearer.SetValue(True)
-        
-        # add 4 types of smearing to the sizer
-        sizer_smearer.Add( self.disable_smearer,0, wx.LEFT, 10)
-        sizer_smearer.Add((10,10))
-        sizer_smearer.Add( self.enable_smearer)
-        sizer_smearer.Add((10,10))
-        sizer_smearer.Add( self.pinhole_smearer ) 
-        sizer_smearer.Add((10,10))
-        sizer_smearer.Add( self.slit_smearer ) 
-        sizer_smearer.Add((10,10))       
-        
-        # StaticText for chi2, N(for fitting), Npts
-        self.tcChi    =  BGTextCtrl(self, -1, "-", size=(75,20), style=0)
-        self.tcChi.SetToolTipString("Chi2/Npts")
-        self.Npts_fit    =  BGTextCtrl(self, -1, "-", size=(75,20), style=0)
-        self.Npts_fit.SetToolTipString(" Npts : number of points selected for fitting")
-        self.Npts_total  =  BGTextCtrl(self, -1, "-", size=(75,20), style=0)
-        self.Npts_total.SetToolTipString(" Total Npts : total number of data points")
-        box_description_1= wx.StaticText(self, -1,'    Chi2/Npts')
-        box_description_2= wx.StaticText(self, -1,'  Npts')
-        box_description_3= wx.StaticText(self, -1,'  Total Npts')
-        box_description_4= wx.StaticText(self, -1,' ')
-        
-        
-        sizer_fit.Add(box_description_1,0,0)
-        sizer_fit.Add(box_description_2,0,0)
-        sizer_fit.Add(box_description_3,0,0)       
-        sizer_fit.Add(box_description_4,0,0)
-        sizer_fit.Add(self.tcChi,0,0)
-        sizer_fit.Add(self.Npts_fit ,0,0)
-        sizer_fit.Add(self.Npts_total,0,0)
-        sizer_fit.Add(self.btFit,0,0) 
-
-        # StaticText for smear
-        #self.tcChi    =  wx.StaticText(self, -1, "-", style=wx.ALIGN_LEFT)
-        self.smear_description_none    =  wx.StaticText(self, -1, smear_message_none , style=wx.ALIGN_LEFT)
-        self.smear_description_dqdata    =  wx.StaticText(self, -1, smear_message_dqdata , style=wx.ALIGN_LEFT)
-        self.smear_description_type    =  wx.StaticText(self, -1, "Type:" , style=wx.ALIGN_LEFT)
-        self.smear_description_accuracy_type    =  wx.StaticText(self, -1, "Accuracy:" , style=wx.ALIGN_LEFT)
-        self.smear_description_smear_type    =  BGTextCtrl(self, -1, size=(57,20), style=0)
-        self.smear_description_smear_type.SetValue(str(self.dq_l))
-        self.SetBackgroundColour(self.GetParent().GetBackgroundColour())
-        self.smear_description_2d     =  wx.StaticText(self, -1, smear_message_2d  , style=wx.ALIGN_LEFT)
-        self.smear_message_new_s = wx.StaticText(self, -1, smear_message_new_ssmear  , style=wx.ALIGN_LEFT)
-        self.smear_message_new_p = wx.StaticText(self, -1, smear_message_new_psmear  , style=wx.ALIGN_LEFT)
-        self.smear_description_2d_x     =  wx.StaticText(self, -1, smear_message_2d_x_title  , style=wx.ALIGN_LEFT)
-        self.smear_description_2d_y     =  wx.StaticText(self, -1, smear_message_2d_y_title  , style=wx.ALIGN_LEFT)
-        self.smear_description_pin_min     =  wx.StaticText(self, -1, smear_message_pinhole_min_title  , style=wx.ALIGN_LEFT)
-        self.smear_description_pin_max     =  wx.StaticText(self, -1, smear_message_pinhole_max_title  , style=wx.ALIGN_LEFT)
-        self.smear_description_slit_height    =  wx.StaticText(self, -1, smear_message_slit_height_title   , style=wx.ALIGN_LEFT)
-        self.smear_description_slit_width    =  wx.StaticText(self, -1, smear_message_slit_width_title   , style=wx.ALIGN_LEFT)
-        
-        #arrange sizers 
-        #boxsizer1.Add( self.tcChi )  
-        self.sizer_set_smearer.Add(sizer_smearer )
-        self.sizer_set_smearer.Add((10,10))
-        self.sizer_set_smearer.Add( self.smear_description_none,0, wx.CENTER, 10 ) 
-        self.sizer_set_smearer.Add( self.smear_description_dqdata,0, wx.CENTER, 10 )
-        self.sizer_set_smearer.Add( self.smear_description_2d,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_type,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_accuracy_type,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_accuracy )
-        self.sizer_new_smear.Add( self.smear_description_smear_type,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add((15,-1))
-        self.sizer_new_smear.Add( self.smear_description_2d_x,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_pin_min,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_slit_height,0, wx.CENTER, 10 )
-
-        self.sizer_new_smear.Add( self.smear_pinhole_min,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_slit_height,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_data_left,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add((20,-1))
-        self.sizer_new_smear.Add( self.smear_description_2d_y,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_pin_max,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_description_slit_width,0, wx.CENTER, 10 )
-
-        self.sizer_new_smear.Add( self.smear_pinhole_max,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_slit_width,0, wx.CENTER, 10 )
-        self.sizer_new_smear.Add( self.smear_data_right,0, wx.CENTER, 10 )
-           
-        self.sizer_set_smearer.Add( self.smear_message_new_s,0, wx.CENTER, 10)
-        self.sizer_set_smearer.Add( self.smear_message_new_p,0, wx.CENTER, 10)
-        self.sizer_set_smearer.Add((5,2))
-        self.sizer_set_smearer.Add( self.sizer_new_smear,0, wx.CENTER, 10 )
-        
-        # add all to chi2 sizer 
-        sizer_smearer_box.Add(self.sizer_set_smearer)       
-        sizer_chi2.Add(sizer_smearer_box)
-        sizer_chi2.Add((-1,5))
-
-        # hide all smear messages and textctrl
-        self._hide_all_smear_info()
-        
-        # get smear_selection
-        self.current_smearer= smear_selection( self.data, self.model )
-
-        # Show only the relevant smear messages, etc
-        if self.current_smearer == None:
-            if not is_2Ddata:
-                self.smear_description_none.Show(True)
-                self.enable_smearer.Disable()  
-            else:
-                self.smear_description_none.Show(True)
-                #self.smear_description_2d.Show(True) 
-                #self.pinhole_smearer.Disable() 
-                self.slit_smearer.Disable()   
-                #self.enable_smearer.Disable() 
-        else: self._show_smear_sizer()
-        boxsizer_range.Add(self.sizer_set_masking)
-            
-        #Set sizer for Fitting section
-        self._set_range_sizer( title=title,box_sizer=boxsizer_range, object1=sizer_chi2, object= sizer_fit)
-        
-    def _fill_datainfo_sizer(self):
-        """
-        fill sizer 0 with data info
-        """
-        ## no loaded data , don't fill the sizer
-        if self.data is None:
-            data_min = ""
-            data_max = ""
-            data_name = ""
-        else:
-            data_name = self.data.name
-            #set maximum range for x in linear scale
-            if not hasattr(self.data,"data"): #Display only for 1D data fit
-                # Minimum value of data   
-                data_min = min(self.data.x)
-                # Maximum value of data  
-                data_max = max(self.data.x)
-            else:
-                ## Minimum value of data 
-                data_min = 0
-                x = max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
-                y = max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
-                ## Maximum value of data  
-                data_max = math.sqrt(x*x + y*y)
-        
-        box_description= wx.StaticBox(self, -1, 'Data')
-        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-        #----------------------------------------------------------
-        sizer_data = wx.BoxSizer(wx.HORIZONTAL)
-        #Filling the sizer containing data related fields
-        #self.dataSource = wx.StaticText(self, -1,str(self.data.name))
-        self.dataSource = BGTextCtrl(self, -1)
-        self.dataSource.SetValue(str(data_name))
-        #self.dataSource.SetEditable(False)
-        self.dataSource.SetMinSize((_DATA_BOX_WIDTH, -1))
-        sizer_data.Add(wx.StaticText(self, -1, 'Source Name : '))
-        sizer_data.Add(self.dataSource )
-        sizer_data.Add( (0,5) )
-        
-        #---------sizer 2 draw--------------------------------
-        text4_3 = wx.StaticText(self, -1, 'Total Q Range (1/A)',
-                                 style=wx.ALIGN_LEFT)
-        sizer_range = wx.BoxSizer(wx.HORIZONTAL)
-        sizer_range.Add( text4_3 ,0, wx.RIGHT, 10)
-        self.minimum_q = BGTextCtrl(self, -1, size=(_BOX_WIDTH,20))
-        self.minimum_q.SetValue(str(data_min))
-        #self.minimum_q.SetEditable(False)
-        self.maximum_q = BGTextCtrl(self, -1,size=(_BOX_WIDTH,20))
-        self.maximum_q.SetValue(str(data_max))
-        #self.maximum_q.SetEditable(False)
-        sizer_range.Add(wx.StaticText(self, -1, "Min: "),0, wx.LEFT, 10)
-        sizer_range.Add(self.minimum_q,0, wx.LEFT, 10)
-        sizer_range.Add(wx.StaticText(self, -1, "Max: "),0, wx.LEFT, 10)
-        sizer_range.Add(self.maximum_q,0, wx.LEFT, 10)
-
-        ## set q range to plot
-        self.qmin_x = data_min
-        self.qmax_x = data_max
-
-        boxsizer1.Add(sizer_data,0, wx.ALL, 10)
-        boxsizer1.Add(sizer_range, 0 , wx.LEFT, 10)
-        #------------------------------------------------------------
-        self.sizer0.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
-        self.sizer0.Layout()
-       
-    def _fill_model_sizer(self, sizer):
-        """
-        fill sizer containing model info
-        """
-        ##Add model function Details button in fitpanel.
-        ##The following 3 lines are for Mac. Let JHC know before modifying... 
-        title = "Model"
-        box_description= wx.StaticBox(self, -1,str(title))
-        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-         
-        id = wx.NewId()
-        self.model_help =wx.Button(self,id,'Details', size=(80,23))
-        self.model_help.Bind(wx.EVT_BUTTON, self.on_model_help_clicked,id=id)
-        self.model_help.SetToolTipString("Model Function Help")
-        
-        ## class base method  to add view 2d button    
-        self._set_model_sizer(sizer=sizer, box_sizer=boxsizer1, 
-                              title="Model",object=self.model_help )   
-        
-    def _set_sizer_dispersion(self, dispersity):
-        """
-        draw sizer with gaussian dispersity parameters
-        """
-        self.fittable_param=[]
-        self.fixed_param=[]
-        self.orientation_params_disp=[]
-
-        self.sizer4_4.Clear(True)
-        if self.model==None:
-            ##no model is selected
-            return
-        if not self.enable_disp.GetValue():
-            ## the user didn't select dispersity display
-            return 
-            
-        self._reset_dispersity()
-        
-        # Create the dispersion objects
-        for item in self.model.dispersion.keys():
-            #disp_model =  GaussianDispersion()
-            disp_model = dispersity()
-            self._disp_obj_dict[item] = disp_model
-            self.model.set_dispersion(item, disp_model)
-            self.state._disp_obj_dict[item]= disp_model
-
-
-        ix=0
-        iy=1
-        disp = wx.StaticText(self, -1, ' ')
-        self.sizer4_4.Add(disp,( iy, ix),(1,1), 
-                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-        ix += 1 
-        values = wx.StaticText(self, -1, 'Sigma [A]')
-        values.SetToolTipString(\
-        "Sigma(STD) in the A unit; the standard deviation from the mean value.")
-
-        self.sizer4_4.Add(values,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 
-                          0)
-        ix +=2 
-        self.text_disp_1 = wx.StaticText(self, -1, '')
-        self.sizer4_4.Add( self.text_disp_1,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text_disp_1.Hide()
-        
-        
-        ix +=1 
-        self.text_disp_min = wx.StaticText(self, -1, 'Min')
-        self.sizer4_4.Add(self.text_disp_min,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text_disp_min.Hide()
-        ix +=1 
-        self.text_disp_max = wx.StaticText(self, -1, 'Max')
-        self.sizer4_4.Add(self.text_disp_max,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text_disp_max.Hide()
-                        
-        
-        ix += 1 
-        npts = wx.StaticText(self, -1, 'Npts')
-        npts.SetToolTipString("Number of sampling points for the numerical\n\
-        integration over the distribution function.")
-        self.sizer4_4.Add(npts,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        ix += 1 
-        nsigmas = wx.StaticText(self, -1, 'Nsigmas')
-        nsigmas.SetToolTipString("   Number of sigmas between which the range\n\
-         of the distribution function will be used for weighting. \n\
-        The value '3' covers 99.5% for Gaussian distribution \n\
-        function.")
-        self.sizer4_4.Add(nsigmas,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE,
-                           0)
-        
-        if self.engine_type=="park":
-            self.text_disp_max.Show(True)
-            self.text_disp_min.Show(True)
-
-        for item in self.model.dispersion.keys():
-            if not item in self.model.orientation_params:
-                if not self.disp_cb_dict.has_key(item):
-                    self.disp_cb_dict[item]= None
-                name0="Distribution of " + item
-                name1=item+".width"
-                name2=item+".npts"
-                name3=item+".nsigmas"
-                if not self.model.details.has_key(name1):
-                    self.model.details [name1] = ["",None,None] 
-
-                iy += 1
-                for p in self.model.dispersion[item].keys(): 
-        
-                    if p=="width":
-                        ix = 0
-                        cb = wx.CheckBox(self, -1, name0, (10, 10))
-                        cb.SetToolTipString("Check for fitting")
-                        wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
-                        self.sizer4_4.Add( cb,( iy, ix),(1,1),  
-                                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 
-                                           15)
-                        ix = 1
-                        value= self.model.getParam(name1)
-                        ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH,20)
-                                                  ,style=wx.TE_PROCESS_ENTER)
-                        ctl1.SetToolTipString("Absolute Sigma: \n\
-                        1) It is the STD (ratio*mean) of '%s' distribution.\n \
-                        2) It should not exceed Mean/(2*Nsigmas)." %item)
-                        ctl1.SetValue(str (format_number(value)))
-                        self.sizer4_4.Add(ctl1, (iy,ix),(1,1),wx.EXPAND)
-                        ## text to show error sign
-                        ix = 2
-                        text2=wx.StaticText(self, -1, '+/-')
-                        self.sizer4_4.Add(text2,(iy, ix),(1,1),
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        text2.Hide() 
-
-                        ix = 3
-                        ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), 
-                                           style=0)
-                  
-                        self.sizer4_4.Add(ctl2, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                     
-                        ctl2.Hide()
-
-                        ix = 4
-                        ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,
-                                            20), style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-                        
-                        self.sizer4_4.Add(ctl3, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        ctl3.Hide()
-                
-                        ix = 5
-                        ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,
-                                            20), style=wx.TE_PROCESS_ENTER,
-                            text_enter_callback = self._onparamRangeEnter)
-                        
-                        self.sizer4_4.Add(ctl4, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-
-                        ctl4.Hide()
-                        
-                        if self.engine_type=="park":
-                            ctl3.Show(True)
-                            ctl4.Show(True)
-                                          
-                        self.fittable_param.append([cb,name1,ctl1,text2,
-                                                    ctl2, ctl3, ctl4,None])                    
-                    
-                    elif p=="npts":
-                            ix = 6
-                            value= self.model.getParam(name2)
-                            Tctl = self.ModelTextCtrl(self, -1, 
-                                                      size=(_BOX_WIDTH/2,20),
-                                                style=wx.TE_PROCESS_ENTER)
-                            
-                            Tctl.SetValue(str (format_number(value)))
-                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
-                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                            self.fixed_param.append([None,name2, Tctl,None,None,
-                                                      None, None,None])
-                    elif p=="nsigmas":
-                            ix = 7
-                            value= self.model.getParam(name3)
-                            Tct2 = self.ModelTextCtrl(self, -1, 
-                                                      size=(_BOX_WIDTH/2,20),
-                                                style=wx.TE_PROCESS_ENTER)
-                            
-                            Tct2.SetValue(str (format_number(value)))
-                            self.sizer4_4.Add(Tct2, (iy,ix),(1,1),
-                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                            ix +=1
-                            self.sizer4_4.Add((20,20), (iy,ix),(1,1),
-                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                            
-                            self.fixed_param.append([None,name3, Tct2
-                                                     ,None,None,None, 
-                                                     None,None])
-                            
-        ix =0
-        iy +=1 
-        self.sizer4_4.Add((20,20),(iy,ix),(1,1), 
-                          wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)  
-        first_orient  = True
-        for item in self.model.dispersion.keys():
-            if  item in self.model.orientation_params:
-                if not self.disp_cb_dict.has_key(item):
-                    self.disp_cb_dict[item]= None
-                name0="Distribution of " + item
-                name1=item+".width"
-                name2=item+".npts"
-                name3=item+".nsigmas"
-                
-                if not self.model.details.has_key(name1):
-                    self.model.details [name1] = ["",None,None]                  
- 
-
-                iy += 1
-                for p in self.model.dispersion[item].keys(): 
-        
-                    if p=="width":
-                        ix = 0
-                        cb = wx.CheckBox(self, -1, name0, (10, 10))
-                        cb.SetToolTipString("Check for fitting")
-                        wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
-                        self.sizer4_4.Add( cb,( iy, ix),(1,1),  
-                                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 
-                                           15)
-                        if self.data.__class__.__name__ =="Data2D":
-                            cb.Show(True)
-                        elif cb.IsShown():
-                            cb.Hide()
-                        ix = 1
-                        value= self.model.getParam(name1)
-                        ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH,
-                                        20),style=wx.TE_PROCESS_ENTER)
-                        ctl1.SetToolTipString("Absolute Sigma: \n\
-                        1) It is the STD (ratio*mean) of '%s' distribution."% \
-                        item)
-                        ctl1.SetValue(str (format_number(value)))
-                        if self.data.__class__.__name__ =="Data2D":
-                            if first_orient:
-                                values.SetLabel('Sigma [A (or deg)]')
-                                values.SetToolTipString(\
-                                "Sigma(STD) in the A or deg(for angles) unit;\n\
-                                the standard deviation from the mean value.")
-                                first_orient = False
-                            ctl1.Show(True)
-                        elif ctl1.IsShown():
-                            ctl1.Hide()
-                        
-                        self.sizer4_4.Add(ctl1, (iy,ix),(1,1),wx.EXPAND)
-                        ## text to show error sign
-                        ix = 2
-                        text2=wx.StaticText(self, -1, '+/-')
-                        self.sizer4_4.Add(text2,(iy, ix),(1,1),
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        text2.Hide() 
-
-                        ix = 3
-                        ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), 
-                                           style=0)
-                    
-                        self.sizer4_4.Add(ctl2, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        ctl2.Hide()
-                            
-                        ix = 4
-                        ctl3 = self.ModelTextCtrl(self, -1, 
-                                                  size=(_BOX_WIDTH/2,20), 
-                                                  style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-
-                        self.sizer4_4.Add(ctl3, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-
-                        ctl3.Hide()
-                
-                        ix = 5
-                        ctl4 = self.ModelTextCtrl(self, -1, 
-                            size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-                        self.sizer4_4.Add(ctl4, (iy,ix),(1,1), 
-                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        ctl4.Hide()
-                        #if self.data.__class__.__name__ =="Data2D":
-                            #ctl4.Enable(True)
-                        #elif ctl4.Shown():
-                            #ctl4.Hide()
-                        
-                        if self.engine_type=="park" and \
-                                    self.data.__class__.__name__ =="Data2D":
-                            ctl3.Show(True)
-                            ctl4.Show(True) 
-                            
-                            
-                            
-                            
-                        self.fittable_param.append([cb,name1,ctl1,text2,
-                                                    ctl2, ctl3, ctl4,None])
-                        self.orientation_params_disp.append([cb,name1,ctl1,
-                                                  text2, ctl2, ctl3, ctl4,None])
-                    elif p=="npts":
-                            ix = 6
-                            value= self.model.getParam(name2)
-                            Tctl = self.ModelTextCtrl(self, -1, 
-                                                      size=(_BOX_WIDTH/2,20),
-                                                style=wx.TE_PROCESS_ENTER)
-                            
-                            Tctl.SetValue(str (format_number(value)))
-                            if self.data.__class__.__name__ =="Data2D":
-                                Tctl.Show(True)
-                            else:
-                                Tctl.Hide()
-                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
-                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                            self.fixed_param.append([None,name2, Tctl,None,None,
-                                                      None, None,None])
-                            self.orientation_params_disp.append([None,name2, 
-                                                    Tctl,None,None,
-                                                      None, None,None])
-                    elif p=="nsigmas":
-                            ix = 7
-                            value= self.model.getParam(name3)
-                            Tct2 = self.ModelTextCtrl(self, -1, 
-                                                      size=(_BOX_WIDTH/2,20),
-                                                style=wx.TE_PROCESS_ENTER)
-                            
-                            Tct2.SetValue(str (format_number(value)))
-                            if self.data.__class__.__name__ =="Data2D":
-                                Tct2.Show(True)
-                            else:
-                                Tct2.Hide()
-                            self.sizer4_4.Add(Tct2, (iy,ix),(1,1),
-                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                            ix +=1
-
-                            self.fixed_param.append([None,name3, Tct2
-                                                 ,None,None, None, None,None])    
-                                                       
-                            self.orientation_params_disp.append([None,name3, 
-                                            Tct2 ,None,None, None, None,None])
-        
-        self.state.disp_cb_dict = copy.deepcopy(self.disp_cb_dict)  
-          
-        self.state.model = self.model.clone()  
-         ## save state into
-        self.state.cb1 = self.cb1.GetValue()
-        self._copy_parameters_state(self.parameters, self.state.parameters)
-        self._copy_parameters_state(self.orientation_params_disp,
-                                     self.state.orientation_params_disp)
-        self._copy_parameters_state(self.fittable_param, 
-                                    self.state.fittable_param)
-        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
-
-
-        wx.PostEvent(self.parent, StatusEvent(status=\
-                        " Selected Distribution: Gaussian"))   
-        #Fill the list of fittable parameters
-        self.select_all_param(event=None)
-        
-        self.Layout()
-
-    def _onFit(self, event):     
-        """
-        Allow to fit
-        """
-        #make sure all parameter values are updated.
-        if self.check_invalid_panel():
-            return
-        if self.model ==None:
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Fit: %s"%msg))
-            return
-
-        flag = self._update_paramv_on_fit() 
-                
-        if not flag:
-            msg= "Fitting range or parameters are invalid"
-            wx.PostEvent(self.parent.parent, StatusEvent(status= msg ))
-            return 
-        
-        if len(self.param_toFit) <= 0:
-            msg= "Select at least one parameter to fit"
-            wx.PostEvent(self.parent.parent, StatusEvent(status= msg ))
-            return 
-      
-        self.select_param(event =None)
-        
-        #Clear errors if exist from previous fitting
-        #self._clear_Err_on_Fit() 
-
-        # Remove or do not allow fitting on the Q=0 point, especially 
-        # when y(q=0)=None at x[0].         
-        self.qmin_x = float(self.qmin.GetValue())
-        self.qmax_x = float( self.qmax.GetValue())
-        self._manager._reset_schedule_problem( value=0)
-        self._manager.schedule_for_fit( value=1,page=self,fitproblem =None) 
-        self._manager.set_fit_range(page= self,qmin= self.qmin_x, 
-                                   qmax= self.qmax_x)
-        
-        #single fit 
-        self._manager.onFit()
-        ## allow stopping the fit 
-        #if self.engine_type=="scipy":
-        #    self.btFit.SetLabel("Stop")
-        #    self.btFit.Unbind(event=wx.EVT_BUTTON, id= self.btFit.GetId())
-        #    self.btFit.Bind(event= wx.EVT_BUTTON, 
-        #            handler=self._StopFit, id=self.btFit.GetId())
-        #else:
-        #    self.btFit.SetLabel("Fit")
-        #    self.btFit.Bind(event= wx.EVT_BUTTON, 
-        #                handler=self._onFit, id=self.btFit.GetId())
-           
-    def _StopFit(self, event):
-        """
-        Stop fit 
-        """
-        self.btFit.SetLabel("Fit")
-        if self.engine_type=="scipy":
-            self._manager.stop_fit()
-        self.btFit.Unbind(event=wx.EVT_BUTTON, id=self.btFit.GetId())
-        self.btFit.Bind(event=wx.EVT_BUTTON, handler=self._onFit,
-                        id=self.btFit.GetId())
-        
-            
-    def _on_select_model(self, event=None): 
-        """
-        call back for model selection
-        """  
-        self._on_select_model_helper() 
-        self.set_model_param_sizer(self.model)                   
-        
-        if self.model is None:
-            self._set_bookmark_flag(False)
-            self._set_save_flag(False)
-        self.enable_disp.SetValue(False)
-        self.disable_disp.SetValue(True)
-        try:
-            self.set_dispers_sizer()
-        except:
-            pass
-        self.btFit.SetFocus() 
-        self.state.enable_disp = self.enable_disp.GetValue()
-        self.state.disable_disp = self.disable_disp.GetValue()
-        self.state.pinhole_smearer = self.pinhole_smearer.GetValue()
-        self.state.slit_smearer = self.slit_smearer.GetValue()
-    
-        self.state.structurecombobox = self.structurebox.GetCurrentSelection()
-        self.state.formfactorcombobox = self.formfactorbox.GetCurrentSelection()
-      
-        if self.model != None:
-            self._set_bookmark_flag(True)
-            self._set_save_flag(True)
-            # Reset smearer, model and data
-            self.set_data(self.data)
-            # update smearer sizer
-            self.onSmear(None)
-            try:
-                temp_smear = None
-                if self.enable_smearer.GetValue():
-                    # Set the smearer environments
-                    temp_smear= self.smearer
-                #self.compute_chisqr(temp_smear)
-            except:
-                ## error occured on chisqr computation
-                pass
-            ## event to post model to fit to fitting plugins
-            (ModelEventbox, EVT_MODEL_BOX) = wx.lib.newevent.NewEvent()
-            if self.data is not None and \
-                    self.data.__class__.__name__ !="Data2D":
-                ## set smearing value whether or not 
-                #    the data contain the smearing info
-                evt = ModelEventbox(model = self.model, 
-                                        smearer = temp_smear, 
-                                        qmin = float(self.qmin_x),
-                                     qmax = float(self.qmax_x)) 
-            else:   
-                 evt = ModelEventbox(model = self.model)
-          
-            self._manager._on_model_panel(evt = evt)
-            self.state.model = self.model.clone()
-            self.state.model.name = self.model.name
-            if event is not None:
-                self._draw_model()
-        if event !=None:
-            #self._undo.Enable(True)
-            ## post state to fit panel
-            event = PageInfoEvent(page = self)
-            wx.PostEvent(self.parent, event) 
-      
-      
-    def _onparamEnter(self,event):
-        """ 
-        when enter value on panel redraw model according to changed
-        """
-        if self.model ==None:
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            #wx.PostEvent(self._manager.parent, StatusEvent(status=\
-            #                "Parameters: %s"%msg))
-            return
-
-        #default flag
-        flag = False
-        self.fitrange = True
-        #get event object
-        tcrtl= event.GetEventObject()
-        wx.PostEvent(self._manager.parent, StatusEvent(status=" \
-                                updating ... ",type="update"))
-        #Clear msg if previously shown.
-        msg= ""
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-
-        if check_float(tcrtl):
-            flag = self._onparamEnter_helper() 
-            self.set_npts2fit() 
-            if self.fitrange:             
-                temp_smearer = None
-                if not self.disable_smearer.GetValue():
-                    temp_smearer= self.current_smearer
-                    ## set smearing value whether or not 
-                    #        the data contain the smearing info
-                    if self.slit_smearer.GetValue():
-                        flag1 = self.update_slit_smear()
-                        flag = flag or flag1
-                    elif self.pinhole_smearer.GetValue():
-                        flag1 = self.update_pinhole_smear()
-                        flag = flag or flag1
-                elif self.data.__class__.__name__ !="Data2D":
-                    self._manager.set_smearer(smearer=temp_smearer, 
-                                             qmin= float(self.qmin_x),
-                                            qmax= float(self.qmax_x)) 
-                if flag:   
-                    #self.compute_chisqr(smearer= temp_smearer)
-        
-                    ## new state posted
-                    if self.state_change:
-                        #self._undo.Enable(True)
-                        event = PageInfoEvent(page = self)
-                        wx.PostEvent(self.parent, event)
-                    self.state_change= False 
-            else: 
-                # invalid fit range: do nothing here: 
-                # msg already displayed in validate 
-                return      
-        else:
-            self.save_current_state()
-            msg= "Cannot Plot :Must enter a number!!!  "
-            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-             
-        self.save_current_state() 
-        return 
-   
-    def _onparamRangeEnter(self, event):
-        """
-        Check validity of value enter in the parameters range field
-        """
-        if self.check_invalid_panel():
-            return
-        tcrtl= event.GetEventObject()
-        #Clear msg if previously shown.
-        msg= ""
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        # Flag to register when a parameter has changed.
-        is_modified = False
-        if tcrtl.GetValue().lstrip().rstrip()!="":
-            try:
-                value = float(tcrtl.GetValue())
-                tcrtl.SetBackgroundColour(wx.WHITE)
-                self._check_value_enter(self.fittable_param ,is_modified)
-                self._check_value_enter(self.parameters ,is_modified) 
-            except:
-                tcrtl.SetBackgroundColour("pink")
-                msg= "Model Error:wrong value entered : %s"% sys.exc_value
-                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                return 
-        else:
-           tcrtl.SetBackgroundColour(wx.WHITE)
-           
-        #self._undo.Enable(True)
-        self.save_current_state()
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        self.state_change= False
-
-                    
-    def _onQrangeEnter(self, event):
-        """
-        Check validity of value enter in the Q range field
-        """
-        if self.check_invalid_panel():
-            return
-        tcrtl= event.GetEventObject()
-        #Clear msg if previously shown.
-        msg= ""
-        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        # Flag to register when a parameter has changed.
-        is_modified = False
-        if tcrtl.GetValue().lstrip().rstrip()!="":
-            try:
-                value = float(tcrtl.GetValue())
-                tcrtl.SetBackgroundColour(wx.WHITE)
-
-                # If qmin and qmax have been modified, update qmin and qmax
-                if self._validate_qrange( self.qmin, self.qmax):
-                    tempmin = float(self.qmin.GetValue())
-                    if tempmin != self.qmin_x:
-                        self.qmin_x = tempmin
-                    tempmax = float(self.qmax.GetValue())
-                    if tempmax != self.qmax_x:
-                        self.qmax_x = tempmax
-                else:
-                    tcrtl.SetBackgroundColour("pink")
-                    msg= "Model Error:wrong value entered : %s"% sys.exc_value
-                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                    return 
-                
-            except:
-                tcrtl.SetBackgroundColour("pink")
-                msg= "Model Error:wrong value entered : %s"% sys.exc_value
-                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                return 
-            #Check if # of points for theory model are valid(>0).
-            # check for 2d
-            if self.data.__class__.__name__ =="Data2D":
-                # set mask   
-                radius= numpy.sqrt( self.data.qx_data*self.data.qx_data + 
-                                    self.data.qy_data*self.data.qy_data )
-                index_data = ((self.qmin_x <= radius)& \
-                                (radius<= self.qmax_x))
-                index_data = (index_data)&(self.data.mask)
-                index_data = (index_data)&(numpy.isfinite(self.data.data))
-                if len(index_data[index_data]) < 10:
-                    msg = "Cannot Plot :No or too little npts in"
-                    msg += " that data range!!!  "
-                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-                    return
-                else:
-                    self.data.mask = index_data
-                    #self.Npts_fit.SetValue(str(len(self.data.mask)))
-                    self.set_npts2fit() 
-            else:
-                index_data = ((self.qmin_x <= self.data.x)& \
-                              (self.data.x <= self.qmax_x))
-                self.Npts_fit.SetValue(str(len(self.data.x[index_data])))
-
-           
-        else:
-           tcrtl.SetBackgroundColour("pink")
-           msg= "Model Error:wrong value entered!!!"
-           wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        
-        self._draw_model()
-        ##update chi2
-        #self.compute_chisqr(smearer= temp_smearer)
-        #self._undo.Enable(True)
-        self.save_current_state()
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        self.state_change= False
-        return
-    
-    def _clear_Err_on_Fit(self):
-        """
-        hide the error text control shown 
-        after fitting
-        """
-        
-        if hasattr(self,"text2_3"):
-            self.text2_3.Hide()
-
-        if len(self.parameters)>0:
-            for item in self.parameters:
-                #Skip t ifhe angle parameters if 1D data
-                if self.data.__class__.__name__ !="Data2D":
-                    if item in self.orientation_params:
-                        continue
-                if item in self.param_toFit:
-                    continue
-                ## hide statictext +/-    
-                if item[3]!=None and item[3].IsShown():
-                    item[3].Hide()
-                ## hide textcrtl  for error after fit
-                if item[4]!=None and item[4].IsShown():                   
-                    item[4].Hide()
-  
-        if len(self.fittable_param)>0:
-            for item in self.fittable_param:
-                #Skip t ifhe angle parameters if 1D data
-                if self.data.__class__.__name__ !="Data2D":
-                    if item in self.orientation_params:
-                        continue
-                if item in self.param_toFit:
-                    continue
-                ## hide statictext +/-    
-                if item[3]!=None and item[3].IsShown():
-                    item[3].Hide()
-                ## hide textcrtl  for error after fit
-                if item[4]!=None and item[4].IsShown():
-                    item[4].Hide()
-        return        
-                
-    def _get_defult_custom_smear(self):
-        """
-        Get the defult values for custum smearing.
-        """
-        # get the default values
-        if self.dxl == None: self.dxl = 0.0
-        if self.dxw == None: self.dxw = ""
-        if self.dx_min == None: self.dx_min = SMEAR_SIZE_L
-        if self.dx_max == None: self.dx_max = SMEAR_SIZE_H
-        
-    def _get_smear_info(self):
-        """
-        Get the smear info from data.
-       
-        :return: self.smear_type, self.dq_l and self.dq_r, 
-            respectively the type of the smear, dq_min and 
-            dq_max for pinhole smear data 
-            while dxl and dxw for slit smear
-            
-        """
-
-        # default
-        self.smear_type = None
-        self.dq_l = None
-        self.dq_r = None
-        data = self.data
-        if self.data is None:
-            return
-        elif self.data.__class__.__name__ == 'Data2D':  
-            if data.dqx_data == None or  data.dqy_data ==None: 
-                return
-            elif self.smearer != None and (data.dqx_data.any()!=0) and \
-                            (data.dqx_data.any()!=0): 
-                self.smear_type = "Pinhole2d"
-                self.dq_l = format_number(numpy.average(data.dqx_data)) 
-                self.dq_r = format_number(numpy.average(data.dqy_data))  
-                return 
-            else: 
-                return
-        # check if it is pinhole smear and get min max if it is.
-        if data.dx != None and all(data.dx !=0): 
-            self.smear_type = "Pinhole" 
-            self.dq_l = data.dx[0]
-            self.dq_r = data.dx[-1]
-            
-        # check if it is slit smear and get min max if it is.
-        elif data.dxl != None or data.dxw != None: 
-            self.smear_type = "Slit" 
-            if data.dxl != None and all(data.dxl !=0):
-                self.dq_l = data.dxl[0]
-            if data.dxw != None and all(data.dxw !=0): 
-                self.dq_r = data.dxw[0]    
-        #return self.smear_type,self.dq_l,self.dq_r       
-    
-    def _show_smear_sizer(self):    
-        """
-        Show only the sizers depending on smear selection
-        """
-        # smear disabled
-        if self.disable_smearer.GetValue():
-            self.smear_description_none.Show(True)
-        # 2Dsmear
-        elif self._is_2D():
-            self.smear_description_accuracy_type.Show(True)
-            self.smear_accuracy.Show(True)
-            self.smear_description_accuracy_type.Show(True)
-            self.smear_description_2d.Show(True)
-            self.smear_description_2d_x.Show(True)
-            self.smear_description_2d_y.Show(True)
-            if self.pinhole_smearer.GetValue():
-                self.smear_pinhole_min.Show(True)
-                self.smear_pinhole_max.Show(True)
-        # smear from data
-        elif self.enable_smearer.GetValue():
-
-            self.smear_description_dqdata.Show(True)
-            if self.smear_type != None:
-                self.smear_description_smear_type.Show(True)
-                if self.smear_type == 'Slit':
-                    self.smear_description_slit_height.Show(True)
-                    self.smear_description_slit_width.Show(True)                
-                elif self.smear_type == 'Pinhole':
-                    self.smear_description_pin_min.Show(True)
-                    self.smear_description_pin_max.Show(True)
-                self.smear_description_smear_type.Show(True)
-                self.smear_description_type.Show(True)
-                self.smear_data_left.Show(True)
-                self.smear_data_right.Show(True)
-        # custom pinhole smear
-        elif self.pinhole_smearer.GetValue():
-            if self.smear_type == 'Pinhole':
-                self.smear_message_new_p.Show(True)
-                self.smear_description_pin_min.Show(True)
-                self.smear_description_pin_max.Show(True)
-
-            self.smear_pinhole_min.Show(True)
-            self.smear_pinhole_max.Show(True)
-        # custom slit smear
-        elif self.slit_smearer.GetValue():
-            self.smear_message_new_s.Show(True)
-            self.smear_description_slit_height.Show(True)
-            self.smear_slit_height.Show(True)
-            self.smear_description_slit_width.Show(True)
-            self.smear_slit_width.Show(True)
-
-    def _hide_all_smear_info(self):
-        """
-        Hide all smearing messages in the set_smearer sizer
-        """
-        self.smear_description_none.Hide()
-        self.smear_description_dqdata.Hide()
-        self.smear_description_type.Hide()
-        self.smear_description_smear_type.Hide()
-        self.smear_description_accuracy_type.Hide()
-        self.smear_description_2d_x.Hide()
-        self.smear_description_2d_y.Hide()
-        self.smear_description_2d.Hide()
-        
-        self.smear_accuracy.Hide()
-        self.smear_data_left.Hide()
-        self.smear_data_right.Hide()
-        self.smear_description_pin_min.Hide()
-        self.smear_pinhole_min.Hide()
-        self.smear_description_pin_max.Hide()
-        self.smear_pinhole_max.Hide()
-        self.smear_description_slit_height.Hide()
-        self.smear_slit_height.Hide()
-        self.smear_description_slit_width.Hide()
-        self.smear_slit_width.Hide()
-        self.smear_message_new_p.Hide()
-        self.smear_message_new_s.Hide()
-    
-    def _set_accuracy_list(self):
-        """
-        Set the list of an accuracy in 2D custum smear: Xhigh, High, Med, or Low
-        """
-        # list of accuracy choices
-        list = ['Low','Med','High','Xhigh']
-        for idx in range(len(list)):
-            self.smear_accuracy.Append(list[idx],idx)
-            
-    def _set_fun_box_list(self,fun_box):
-        """
-        Set the list of func for multifunctional models
-        """
-        # Check if it is multi_functional model
-        if self.model.__class__ not in self.model_list_box["Multi-Functions"]:
-            return None
-        # Get the func name list
-        list = self.model.fun_list
-        if len(list) == 0:
-            return None
-        # build function (combo)box
-        ind = 0
-        while(ind < len(list)):
-            for key, val in list.iteritems():
-                if (val == ind):
-                    fun_box.Append(key,val)
-                    break
-            ind += 1
-        
-    def _on_select_accuracy(self,event):
-        """
-        Select an accuracy in 2D custom smear: Xhigh, High, Med, or Low
-        """
-        #event.Skip()
-        # Check if the accuracy is same as before
-        #self.smear2d_accuracy = event.GetEventObject().GetValue()
-        self.smear2d_accuracy = self.smear_accuracy.GetValue()
-        if self.pinhole_smearer.GetValue():
-            self.onPinholeSmear(event=None)
-        else:    
-            self.onSmear(event=None)
-            if self.current_smearer != None:
-                self.current_smearer.set_accuracy(accuracy = 
-                                                  self.smear2d_accuracy) 
-        event.Skip()
-
-    def _on_fun_box(self,event):
-        """
-        Select an func: Erf,Rparabola,LParabola
-        """
-        fun_val = None
-        fun_box = event.GetEventObject()
-        name = fun_box.Name
-        value = fun_box.GetValue()
-        if self.model.fun_list.has_key(value):
-            fun_val = self.model.fun_list[value]
-
-        self.model.setParam(name,fun_val)
-        # save state
-        self._copy_parameters_state(self.str_parameters, 
-                                    self.state.str_parameters)
-        # update params
-        self._update_paramv_on_fit() 
-        # draw
-        self._draw_model()
-        self.Refresh()
-        # get ready for new event
-        event.Skip()
-        
-    def _onMask(self, event):     
-        """
-        Build a panel to allow to edit Mask
-        """
-        
-        from sans.guiframe.local_perspectives.plotting.masking \
-        import MaskPanel as MaskDialog
-        
-        self.panel = MaskDialog(self, data=self.data,id =-1 )
-        self.panel.Bind(wx.EVT_CLOSE, self._draw_masked_model)
-        self.panel.ShowModal()
-        #wx.PostEvent(self.parent, event)
-        
-    def _draw_masked_model(self,event):
-        """
-        Draw model image w/mask
-        """
-        event.Skip()
-
-        is_valid_qrange = self._update_paramv_on_fit()
-
-        if is_valid_qrange:
-            # try re draw the model plot if it exists
-            self._draw_model()
-            self.panel.Destroy() # frame
-            self.set_npts2fit()
-        elif self.model == None:
-            self.panel.Destroy()
-            self.set_npts2fit()
-            msg= "No model is found on updating MASK in the model plot... "
-            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
-        else:
-            msg = ' Please consider your Q range, too.'
-            self.panel.ShowMessage(msg)
-        
-    def set_data(self, data):
-        """
-        reset the current data 
-        """
-        self.data = data
-        if self.data is None:
-            data_min = ""
-            data_max = ""
-            data_name = ""
-            self.formfactorbox.Disable()
-            self.structurebox.Disable()
-            self._set_bookmark_flag(False)
-            self._set_save_flag(False)
-        else:
-            self._set_bookmark_flag(True)
-            self._set_save_flag(True)
-            self.smearer = smear_selection(self.data, self.model)
-            self.disable_smearer.SetValue(True)
-            if self.smearer == None:
-                self.enable_smearer.Disable()
-            else:
-                self.enable_smearer.Enable()
-            
-            # more disables for 2D
-            if self.data.__class__.__name__ =="Data2D":
-                self.slit_smearer.Disable()
-                self.default_mask = copy.deepcopy(self.data.mask)
-                
-            self.formfactorbox.Enable()
-            self.structurebox.Enable()
-            data_name = self.data.name
-            #set maximum range for x in linear scale
-            if not hasattr(self.data,"data"): #Display only for 1D data fit
-                # Minimum value of data   
-                data_min = min(self.data.x)
-                # Maximum value of data  
-                data_max = max(self.data.x)
-                #number of total data points
-                self.Npts_total.SetValue(str(len(self.data.x)))
-                #default:number of data points selected to fit
-                self.Npts_fit.SetValue(str(len(self.data.x)))
-                self.btEditMask.Disable()  
-                self.EditMask_title.Disable()
-            else:
-                ## Minimum value of data 
-                data_min = 0
-                x = max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
-                y = max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
-                ## Maximum value of data  
-                data_max = math.sqrt(x*x + y*y)
-                #number of total data points
-                self.Npts_total.SetValue(str(len(self.data.data)))
-                #default:number of data points selected to fit
-                self.Npts_fit.SetValue(str(len(self.data.data)))
-                self.btEditMask.Enable()  
-                self.EditMask_title.Enable() 
-        self.dataSource.SetValue(data_name)
-        self.qmin_x = data_min
-        self.qmax_x = data_max
-        self.minimum_q.SetValue(str(data_min))
-        self.maximum_q.SetValue(str(data_max))
-        self.qmin.SetValue(str(data_min))
-        self.qmax.SetValue(str(data_max))
-        self.qmin.SetBackgroundColour("white")
-        self.qmax.SetBackgroundColour("white")
-        self.state.data = data
-        self.state.qmin = self.qmin_x
-        self.state.qmax = self.qmax_x
-        
-    def reset_page(self, state,first=False):
-        """
-        reset the state
-        """
-        self.reset_page_helper(state)
-        #import sans.guiframe.gui_manager
-        #evt = ModelEventbox(model=state.model)
-        #wx.PostEvent(self.event_owner, evt)  
-   
-        if self.engine_type != None:
-            self._manager._on_change_engine(engine=self.engine_type)
-
-        self.select_param(event = None) 
-        #Save state_fit
-        self.save_current_state_fit()
-        self._lay_out()
-        self.Refresh()
-        
-    def get_range(self):
-        """
-        return the fitting range
-        """
-        return float(self.qmin_x) , float(self.qmax_x)
-    
-    def get_npts2fit(self):
-        """
-        return numbers of data points within qrange
-        
-        :Note: This is for Park where chi2 is not normalized by Npts of fit
-        
-        """
-        npts2fit = 0
-        qmin,qmax = self.get_range()
-        if self.data.__class__.__name__ =="Data2D": 
-            radius= numpy.sqrt( self.data.qx_data*self.data.qx_data + 
-                                self.data.qy_data*self.data.qy_data )
-            index_data = (self.qmin_x <= radius)&(radius<= self.qmax_x)
-            index_data= (index_data)&(self.data.mask)
-            index_data = (index_data)&(numpy.isfinite(self.data.data))
-            npts2fit = len(self.data.data[index_data])
-        else:
-            for qx in self.data.x:
-                   if qx >= qmin and qx <= qmax:
-                       npts2fit += 1
-        return npts2fit
-
-    def set_npts2fit(self):
-        """
-        setValue Npts for fitting 
-        """
-        self.Npts_fit.SetValue(str(self.get_npts2fit()))
-        
-    def get_chi2(self):
-        """
-        return the current chi2
-        """
-        return self.tcChi.GetValue()
-        
-    def get_param_list(self):
-        """
-        :return self.param_toFit: list containing  references to TextCtrl
-            checked.Theses TextCtrl will allow reference to parameters to fit.
-        
-        :raise: if return an empty list of parameter fit will nnote work 
-            properly so raise ValueError,"missing parameter to fit"
-        """
-        if self.param_toFit !=[]:
-            return self.param_toFit
-        else:
-            raise ValueError,"missing parameter to fit"    
-      
-    def onsetValues(self,chisqr,p_name, out,cov):
-        """
-        Build the panel from the fit result
-        
-        :param chisqr: Value of the goodness of fit metric
-        :param p_name: the name of parameters
-        :param out: list of parameter with the best value found during fitting
-        :param cov: Covariance matrix
-   
-        """
-        if out == None or not numpy.isfinite(chisqr):
-            raise ValueError,"Fit error occured..." 
-        
-        is_modified = False
-        has_error = False    
-        
-        #Hide textctrl boxes of errors.
-        self._clear_Err_on_Fit()    
-        
-        #Check if chi2 is finite
-        if chisqr != None or numpy.isfinite(chisqr):
-        #format chi2  
-            if self.engine_type == "park":  
-                npt_fit = float(self.get_npts2fit()) 
-                if npt_fit > 0:
-                    chisqr =chisqr/npt_fit    
-            chi2 = format_number(chisqr)    
-            self.tcChi.SetValue(chi2)    
-            self.tcChi.Refresh()    
-        else:
-            self.tcChi.SetValue("-")
-        
-        #Hide error title
-        if self.text2_3.IsShown():
-            self.text2_3.Hide()
-      
-        try:
-            n = self.disp_box.GetCurrentSelection()
-            dispersity= self.disp_box.GetClientData(n)
-            if dispersity !=None and self.enable_disp.GetValue():
-                name= dispersity.__name__
-                if name == "GaussianDispersion":
-                    if hasattr(self,"text_disp_1" ):
-                        if self.text_disp_1 !=None:
-                            self.text_disp_1.Hide()
-        except:
-            dispersty = None
-            pass
-        #set the panel when fit result are float not list
-        if out.__class__== numpy.float64:
-            self.param_toFit[0][2].SetValue(format_number(out))
-            
-            if self.param_toFit[0][4].IsShown:
-                self.param_toFit[0][4].Hide()
-            if cov !=None :
-                self.text2_3.Show(True)
-                try:
-                    if dispersity !=None:
-                        name= dispersity.__name__
-                        if name == "GaussianDispersion" and \
-                        self.enable_disp.GetValue():
-                            if hasattr(self,"text_disp_1" ):
-                                if self.text_disp_1 !=None:
-                                    self.text_disp_1.Show(True)
-                except:
-                    pass
-
-                if cov[0]==None or  not numpy.isfinite(cov[0]): 
-                    if self.param_toFit[0][3].IsShown:
-                        self.param_toFit[0][3].Hide()
-                else:                    
-                    self.param_toFit[0][3].Show(True)               
-                    self.param_toFit[0][4].Show(True)
-                    self.param_toFit[0][4].SetValue(format_number(cov[0]))
-                    has_error = True
-        else:
-
-            i = 0
-            #Set the panel when fit result are list
-            for item in self.param_toFit:     
-                if len(item)>5 and item != None:     
-                    ## reset error value to initial state
-                    item[3].Hide()
-                    item[4].Hide()
-                    
-                    for ind in range(len(out)):
-                        
-                        if item[1] == p_name[ind]:
-                            break        
-                    if len(out)<=len(self.param_toFit) and out[ind] !=None:   
-                        val_out = format_number(out[ind])                  
-                        item[2].SetValue(val_out)
-
-                    if(cov !=None):
-                        
-                        try:
-                            if dispersity !=None:
-                                name= dispersity.__name__
-                                if name == "GaussianDispersion" and \
-                                                self.enable_disp.GetValue():
-                                    if hasattr(self,"text_disp_1" ):
-                                        if self.text_disp_1!=None:
-                                            if not self.text_disp_1.IsShown():
-                                                self.text_disp_1.Show(True)
-                        except:
-                            pass    
-                   
-                        if cov[ind]!=None :
-                            if numpy.isfinite(float(cov[ind])):
-                                val_err = format_number(cov[ind])
-                                item[3].Show(True)
-                                item[4].Show(True)
-                                item[4].SetValue(val_err)
-
-                                has_error = True
-                    i += 1         
-        #Show error title when any errors displayed
-        if has_error: 
-            if not self.text2_3.IsShown():
-                self.text2_3.Show(True) 
-                
-        ## save current state  
-        self.save_current_state()          
-        #plot model
-        self._draw_model()   
-        self._lay_out()      
-        #PostStatusEvent     
-        msg = "Fit completed! "
-        wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
-
-    def onPinholeSmear(self, event):
-        """
-        Create a custom pinhole smear object that will change the way residuals
-        are compute when fitting
-        
-        :Note: accuracy is given by strings'High','Med', 'Low' FOR 2d,
-                     None for 1D
-                     
-        """
-
-        if self.check_invalid_panel():
-            return
-        if self.model ==None:
-            self.disable_smearer.SetValue(True)
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Smear: %s"%msg))
-            return
-
-        # Need update param values
-        self._update_paramv_on_fit()     
-
-        # msg default
-        msg = None
-        if event != None:
-            tcrtl= event.GetEventObject()
-            # event case of radio button
-            if tcrtl.GetValue()== True:
-                self.dx_min = 0.0
-                self.dx_max = 0.0
-                is_new_pinhole = True
-            else:
-                is_new_pinhole = self._is_changed_pinhole()
-        else:
-            is_new_pinhole = True 
-        # if any value is changed
-        if is_new_pinhole:
-            msg = self._set_pinhole_smear()
-        # hide all silt sizer    
-        self._hide_all_smear_info()
-        
-        ##Calculate chi2
-        temp_smearer = self.current_smearer
-        #self.compute_chisqr(smearer= temp_smearer)
-            
-        # show relevant slit sizers 
-        self._show_smear_sizer()
-
-        self.sizer_set_smearer.Layout()
-        self.Layout()   
-        
-        if event != None: 
-            event.Skip()                  
-        #self._undo.Enable(True)
-        self.save_current_state()
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        
-    def _is_changed_pinhole(self):  
-        """
-        check if any of pinhole smear is changed
-        
-        :return: True or False
-        
-        """
-        # get the values
-        pin_min = self.smear_pinhole_min.GetValue()
-        pin_max = self.smear_pinhole_max.GetValue()
-                    
-        # Check changes in slit width    
-        try:
-            dx_min = float(pin_min)
-        except:
-            return True
-        if self.dx_min != dx_min:
-            return True
-        
-        # Check changes in slit heigth
-        try:
-            dx_max = float(pin_max)
-        except:
-            return True
-        if self.dx_max != dx_max:
-            return True
-        return False
-    
-    def _set_pinhole_smear(self):
-        """
-        Set custom pinhole smear
-        
-        :return: msg
-        
-        """
-        # copy data
-        data = copy.deepcopy(self.data)
-        if self._is_2D():
-            self.smear_type = 'Pinhole2d'
-            len_data = len(data.data)
-            data.dqx_data = numpy.zeros(len_data)
-            data.dqy_data = numpy.zeros(len_data)
-        else:
-            self.smear_type = 'Pinhole'
-            len_data = len(data.x)
-            data.dx = numpy.zeros(len_data)
-            data.dxl = None
-            data.dxw = None
-        msg = None
-   
-        get_pin_min = self.smear_pinhole_min
-        get_pin_max = self.smear_pinhole_max        
-
-        if not check_float(get_pin_min):
-            get_pin_min.SetBackgroundColour("pink")
-            msg= "Model Error:wrong value entered!!!"
-        elif not check_float(get_pin_max ):
-            get_pin_max.SetBackgroundColour("pink")
-            msg= "Model Error:wrong value entered!!!"
-        else:
-            if len_data < 2: len_data = 2     
-            self.dx_min = float(get_pin_min.GetValue())
-            self.dx_max = float(get_pin_max.GetValue())
-            if self.dx_min < 0:
-                get_pin_min.SetBackgroundColour("pink")
-                msg= "Model Error:This value can not be negative!!!"
-            elif self.dx_max <0:
-                get_pin_max.SetBackgroundColour("pink")
-                msg= "Model Error:This value can not be negative!!!"
-            elif self.dx_min != None and self.dx_max != None:   
-                if self._is_2D():
-                    data.dqx_data[data.dqx_data==0] = self.dx_min
-                    data.dqy_data[data.dqy_data==0] = self.dx_max          
-                elif self.dx_min == self.dx_max:
-                    data.dx[data.dx==0] = self.dx_min
-                else:
-                    step = (self.dx_max - self.dx_min)/(len_data-1)    
-                    data.dx = numpy.arange(self.dx_min,self.dx_max+step/1.1,
-                                           step)            
-            elif self.dx_min != None: 
-                if self._is_2D(): data.dqx_data[data.dqx_data==0] = self.dx_min
-                else: data.dx[data.dx==0] = self.dx_min 
-            elif self.dx_max != None:
-                if self._is_2D(): data.dqy_data[data.dqy_data==0] = self.dx_max
-                else: data.dx[data.dx==0] = self.dx_max          
-            self.current_smearer = smear_selection(data, self.model)
-            # 2D need to set accuracy
-            if self._is_2D(): 
-                self.current_smearer.set_accuracy(accuracy = \
-                                                  self.smear2d_accuracy)
-
-        if msg != None:
-            wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
-        else:
-            get_pin_min.SetBackgroundColour("white")
-            get_pin_max.SetBackgroundColour("white")
-        ## set smearing value whether or not the data contain the smearing info
-        self._manager.set_smearer(smearer=self.current_smearer, qmin= \
-                                 float(self.qmin_x),qmax= float(self.qmax_x))
-        return msg
-        
-    def update_pinhole_smear(self):
-        """
-        called by kill_focus on pinhole TextCntrl
-        to update the changes 
-        
-        :return: False when wrong value was entered
-        
-        """
-        # msg default
-        msg = None
-        # check if any value is changed
-        if self._is_changed_pinhole():
-            msg = self._set_pinhole_smear()           
-        #self._undo.Enable(True)
-        self.save_current_state()
-
-        if msg != None:
-            return False   
-        else:
-            return True
-                     
-    def onSlitSmear(self, event):
-        """
-        Create a custom slit smear object that will change the way residuals
-        are compute when fitting
-        """
- 
-        if self.check_invalid_panel():
-            return
-
-        if self.model ==None:
-            self.disable_smearer.SetValue(True)
-            
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Smear: %s"%msg))
-            return
-
-        # Need update param values
-        self._update_paramv_on_fit()
-
-        # msg default
-        msg = None
-        # for event given
-        if event != None:
-            tcrtl= event.GetEventObject()
-            # event case of radio button
-            if tcrtl.GetValue():
-                self.dxl = 0.0
-                self.dxw = 0.0
-                is_new_slit = True
-            else:
-                is_new_slit = self._is_changed_slit()
-        else:
-            is_new_slit = True 
-        
-        # if any value is changed
-        if is_new_slit:
-            msg = self._set_slit_smear()
-            
-        # hide all silt sizer
-        self._hide_all_smear_info()        
-        ##Calculate chi2
-        #self.compute_chisqr(smearer= self.current_smearer)  
-        # show relevant slit sizers       
-        self._show_smear_sizer()
-        self.sizer_set_smearer.Layout()
-        self.Layout()
-
-        if event != None:
-            event.Skip()     
-        #self._undo.Enable(True)
-        self.save_current_state()
-        event = PageInfoEvent(page = self)
-        wx.PostEvent(self.parent, event)
-        if msg != None:
-            wx.PostEvent(self._manager.parent, StatusEvent(status = msg))
-
-    def _is_changed_slit(self):  
-        """
-        check if any of slit lengths is changed
-        
-        :return: True or False
-        
-        """
-        # get the values
-        width = self.smear_slit_width.GetValue()
-        height = self.smear_slit_height.GetValue()
-        
-        # check and change the box bg color if it was pink 
-        #    but it should be white now
-        # because this is the case that _set_slit_smear() will not handle
-        if height.lstrip().rstrip()=="":
-            self.smear_slit_height.SetBackgroundColour(wx.WHITE)
-        if width.lstrip().rstrip()=="":
-            self.smear_slit_width.SetBackgroundColour(wx.WHITE)
-            
-        # Check changes in slit width    
-        if width == "": 
-            dxw = 0.0
-        else:
-            try:
-                dxw = float(width)
-            except:
-                return True
-        if self.dxw != dxw:
-            return True
-        
-        # Check changes in slit heigth
-        if height == "": 
-            dxl = 0.0
-        else:
-            try:
-                dxl = float(height)
-            except:
-                return True
-        if self.dxl != dxl:
-            return True
-
-        return False
-    
-    def _set_slit_smear(self):
-        """
-        Set custom slit smear
-        
-        :return: message to inform the user about the validity
-            of the values entered for slit smear
-        """
-        if self.data.__class__.__name__ == "Data2D":
-            return
-        temp_smearer = None
-        # make sure once more if it is smearer
-        data = copy.deepcopy(self.data)
-        data_len = len(data.x)
-        data.dx = None
-        data.dxl = None
-        data.dxw = None
-        msg = None
-   
-        try:
-            self.dxl = float(self.smear_slit_height.GetValue())
-            data.dxl = self.dxl* numpy.ones(data_len)
-            self.smear_slit_height.SetBackgroundColour(wx.WHITE)
-        except: 
-            data.dxl = numpy.zeros(data_len)
-            if self.smear_slit_height.GetValue().lstrip().rstrip()!="":
-                self.smear_slit_height.SetBackgroundColour("pink")
-                msg = "Wrong value entered... "  
-            else:
-                self.smear_slit_height.SetBackgroundColour(wx.WHITE)
-        try:
-            self.dxw = float(self.smear_slit_width.GetValue())
-            self.smear_slit_width.SetBackgroundColour(wx.WHITE)
-            data.dxw = self.dxw* numpy.ones(data_len)
-        except: 
-            data.dxw = numpy.zeros(data_len)
-            if self.smear_slit_width.GetValue().lstrip().rstrip()!="":
-                self.smear_slit_width.SetBackgroundColour("pink")
-                msg = "Wrong Fit value entered... "
-            else:
-                self.smear_slit_width.SetBackgroundColour(wx.WHITE)
-              
-        self.current_smearer = smear_selection(data, self.model)
-        #temp_smearer = self.current_smearer
-        ## set smearing value whether or not the data contain the smearing info
-        self._manager.set_smearer(smearer=self.current_smearer, qmin= \
-                                 float(self.qmin_x), qmax= float(self.qmax_x)) 
-        return msg
-    
-    def update_slit_smear(self):
-        """
-        called by kill_focus on pinhole TextCntrl
-        to update the changes 
-        
-        :return: False when wrong value was entered
-        
-        """             
-        # msg default
-        msg = None
-        # check if any value is changed
-        if self._is_changed_slit():
-            msg = self._set_slit_smear()           
-        #self._undo.Enable(True)
-        self.save_current_state()
-
-        if msg != None:
-            return False   
-        else:
-            return True
-                            
-    def onSmear(self, event):
-        """
-        Create a smear object that will change the way residuals
-        are compute when fitting
-        """
-        if event != None: 
-            event.Skip()    
-        if self.check_invalid_panel():
-            return
-        if self.model == None:
-            self.disable_smearer.SetValue(True)
-            msg="Please select a Model first..."
-            wx.MessageBox(msg, 'Info')
-            wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Smear: %s"%msg))
-            return
-        
-        # Need update param values
-        self._update_paramv_on_fit()
-              
-        temp_smearer = None
-        self._get_smear_info()
-        
-        #renew smear sizer
-        if self.smear_type != None:
-            self.smear_description_smear_type.SetValue(str(self.smear_type))
-            self.smear_data_left.SetValue(str(self.dq_l))   
-            self.smear_data_right.SetValue(str(self.dq_r))       
-
-        self._hide_all_smear_info()
-        
-        data = copy.deepcopy(self.data)
-        # make sure once more if it is smearer
-        self.current_smearer = smear_selection(data, self.model)
-        
-        if self.enable_smearer.GetValue():
-            if hasattr(self.data,"dxl"):
-                
-                msg= ": Resolution smearing parameters"
-            if hasattr(self.data,"dxw"):
-                msg= ": Slit smearing parameters"
-            if self.smearer ==None:
-                wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Data contains no smearing information"))
-            else:
-                wx.PostEvent(self._manager.parent, StatusEvent(status=\
-                            "Data contains smearing information"))
-
-            #self.smear_description_dqdata.Show(True)
-            self.smear_data_left.Show(True)
-            self.smear_data_right.Show(True)
-            temp_smearer= self.current_smearer
-        elif self.disable_smearer.GetValue():
-            self.smear_description_none.Show(True)
-            
-        self._show_smear_sizer()
-        
-        self.sizer_set_smearer.Layout()
-        self.Layout()
-        ## set smearing value whether or not the data contain the smearing info
-        self._manager.set_smearer(smearer=temp_smearer, qmin= float(self.qmin_x),
-                                     qmax= float(self.qmax_x)) 
-
-        ##Calculate chi2
-        #self.compute_chisqr(smearer= temp_smearer)
-        
-        self.state.enable_smearer=  self.enable_smearer.GetValue()
-        self.state.disable_smearer=self.disable_smearer.GetValue()
-        self.state.pinhole_smearer = self.pinhole_smearer.GetValue()
-        self.state.slit_smearer = self.slit_smearer.GetValue()
-      
-    def on_complete_chisqr(self, event):  
-        """
-        print result chisqr 
-        
-        :event: activated by fitting/ complete after draw
-        
-        """
-        try:
-            if event ==None:
-                output= "-"
-            else:
-                output = event.output
-            self.tcChi.SetValue(str(format_number(output)))
-
-            self.state.tcChi = self.tcChi.GetValue()
-        except:
-            pass  
-            
-
-    def select_all_param(self,event): 
-        """
-        set to true or false all checkBox given the main checkbox value cb1
-        """            
-        self.param_toFit=[]
-        if  self.parameters !=[]:
-            if  self.cb1.GetValue():
-                for item in self.parameters:
-                    ## for data2D select all to fit
-                    if self.data.__class__.__name__=="Data2D":
-                        item[0].SetValue(True)
-                        self.param_toFit.append(item )
-                    else:
-                        ## for 1D all parameters except orientation
-                        if not item in self.orientation_params:
-                            item[0].SetValue(True)
-                            self.param_toFit.append(item )
-                #if len(self.fittable_param)>0:
-                for item in self.fittable_param:
-                    if self.data.__class__.__name__=="Data2D":
-                        item[0].SetValue(True)
-                        self.param_toFit.append(item )
-                    else:
-                        ## for 1D all parameters except orientation
-                        if not item in self.orientation_params_disp:
-                            item[0].SetValue(True)
-                            self.param_toFit.append(item )
-            else:
-                for item in self.parameters:
-                    item[0].SetValue(False)
-                for item in self.fittable_param:
-                    item[0].SetValue(False)
-                self.param_toFit=[]
-           
-        self.save_current_state_fit()  
-       
-        if event !=None:
-            #self._undo.Enable(True)
-            ## post state to fit panel
-            event = PageInfoEvent(page = self)
-            wx.PostEvent(self.parent, event) 
-     
-    def select_param(self,event):
-        """ 
-        Select TextCtrl  checked for fitting purpose and stores them
-        in  self.param_toFit=[] list
-        """
-        self.param_toFit=[]
-        for item in self.parameters:
-            #Skip t ifhe angle parameters if 1D data
-            if self.data.__class__.__name__ !="Data2D":
-                if item in self.orientation_params:
-                    continue
-            #Select parameters to fit for list of primary parameters
-            if item[0].GetValue():
-                if not (item in self.param_toFit):
-                    self.param_toFit.append(item )  
-            else:
-                #remove parameters from the fitting list
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-
-        #Select parameters to fit for list of fittable parameters 
-        #        with dispersion          
-        for item in self.fittable_param:
-            #Skip t ifhe angle parameters if 1D data
-            if self.data.__class__.__name__ !="Data2D":
-                if item in self.orientation_params:
-                    continue
-            if item[0].GetValue():
-                if not (item in self.param_toFit):
-                    self.param_toFit.append(item)  
-            else:
-                #remove parameters from the fitting list
-                if item in self.param_toFit:
-                    self.param_toFit.remove(item)
-
-        #Calculate num. of angle parameters 
-        if self.data.__class__.__name__ =="Data2D":  
-            len_orient_para = 0
-        else:
-            len_orient_para = len(self.orientation_params)  #assume even len 
-        #Total num. of angle parameters
-        if len(self.fittable_param) > 0:
-            len_orient_para *= 2
-        #Set the value of checkbox that selected every checkbox or not            
-        if len(self.parameters)+len(self.fittable_param)-len_orient_para ==\
-                len(self.param_toFit):
-            self.cb1.SetValue(True)
-        else:
-            self.cb1.SetValue(False)
-        self.save_current_state_fit()
-        if event !=None:
-            #self._undo.Enable(True)
-            ## post state to fit panel
-            event = PageInfoEvent(page = self)
-            wx.PostEvent(self.parent, event) 
-    
-    def set_model_param_sizer(self, model):
-        """
-        Build the panel from the model content
-        
-        :param model: the model selected in combo box for fitting purpose
-        
-        """
-        self.sizer3.Clear(True)
-        self.parameters = []
-        self.str_parameters = []
-        self.param_toFit=[]
-        self.fittable_param=[]
-        self.fixed_param=[]
-        self.orientation_params=[]
-        self.orientation_params_disp=[]
-        
-        if model ==None:
-            self.sizer3.Layout()
-            self.SetupScrolling()
-            return
-        ## the panel is drawn using the current value of the fit engine
-        if self.engine_type==None and self._manager !=None:
-            self.engine_type= self._manager._return_engine_type()
-
-        box_description= wx.StaticBox(self, -1,str("Model Parameters"))
-        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
-        sizer = wx.GridBagSizer(5,5)
-        ## save the current model
-        self.model = model
-           
-        keys = self.model.getParamList()
-        #list of dispersion paramaters
-        self.disp_list=self.model.getDispParamList()
-
-        def custom_compare(a,b):
-            """
-            Custom compare to order, first by alphabets then second by number.
-            """ 
-            # number at the last digit
-            a_last = a[len(a)-1]
-            b_last = b[len(b)-1]
-            # default
-            num_a = None
-            num_b = None
-            # split the names
-            a2 = a.lower().split('_')
-            b2 = b.lower().split('_')
-            # check length of a2, b2
-            len_a2 = len(a2)
-            len_b2 = len(b2)
-            # check if it contains a int number(<10)
-            try: 
-                num_a = int(a_last)
-            except: pass
-            try:
-                num_b = int(b_last)
-            except: pass
-            # Put 'scale' near the top; happens 
-            # when numbered param name exists
-            if a == 'scale':
-                return -1
-            # both have a number    
-            if num_a != None and num_b != None:
-                if num_a > num_b: return -1
-                # same number
-                elif num_a == num_b: 
-                    # different last names
-                    if a2[len_a2-1] != b2[len_b2-1] and num_a != 0:
-                        return -cmp(a2[len_a2-1], b2[len_b2-1])
-                    else: 
-                        return cmp(a, b) 
-                else: return 1
-            # one of them has a number
-            elif num_a != None: return 1
-            elif num_b != None: return -1
-            # no numbers
-            else: return cmp(a.lower(), b.lower())
-
-                        
-        keys.sort(custom_compare)
-    
-        iy = 0
-        ix = 0
-        select_text = "Select All"
-        self.cb1 = wx.CheckBox(self, -1,str(select_text), (10, 10))
-        wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param)
-        self.cb1.SetToolTipString("To check/uncheck all the boxes below.")
-        #self.cb1.SetValue(True)
-        
-        sizer.Add(self.cb1,(iy, ix),(1,1),\
-                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 5)
-        ix +=1
-        self.text2_2 = wx.StaticText(self, -1, 'Values')
-        sizer.Add(self.text2_2,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        ix +=2 
-        self.text2_3 = wx.StaticText(self, -1, 'Errors')
-        sizer.Add(self.text2_3,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text2_3.Hide()
-        ix +=1 
-        self.text2_min = wx.StaticText(self, -1, 'Min')
-        sizer.Add(self.text2_min,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text2_min.Hide()
-        ix +=1 
-        self.text2_max = wx.StaticText(self, -1, 'Max')
-        sizer.Add(self.text2_max,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text2_max.Hide()
-        ix += 1
-        self.text2_4 = wx.StaticText(self, -1, '[Units]')
-        sizer.Add(self.text2_4,(iy, ix),(1,1),\
-                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-        self.text2_4.Hide()
-        if self.engine_type=="park":
-            self.text2_max.Show(True)
-            self.text2_min.Show(True)
-        
-        for item in keys:
-            if not item in self.disp_list and not item in \
-                    self.model.orientation_params:
-                
-                ##prepare a spot to store errors
-                if not self.model.details.has_key(item):
-                    self.model.details [item] = ["",None,None] 
-         
-                iy += 1
-                ix = 0
-                if self.model.__class__ in \
-                    self.model_list_box["Multi-Functions"] \
-                    and item in self.model.non_fittable:
-                    non_fittable_name = wx.StaticText(self, -1, item )
-                    sizer.Add(non_fittable_name,(iy, ix),(1,1),\
-                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 21)
-                    ## add parameter value
-                    ix += 1
-                    value= self.model.getParam(item)
-                    if len(self.model.fun_list) > 0:
-                        num = item.split('_')[1][5:7]
-                        fun_box = wx.ComboBox(self, -1,size=(100,-1),
-                                    style=wx.CB_READONLY, name = '%s'% item)
-                        self._set_fun_box_list(fun_box)
-                        fun_box.SetSelection(0)
-                        #self.fun_box.SetToolTipString("A function 
-                        #    describing the interface")
-                        wx.EVT_COMBOBOX(fun_box,-1, self._on_fun_box)
-                    else:
-                        fun_box = self.ModelTextCtrl(self, -1, 
-                                                     size=(_BOX_WIDTH,20),
-                                style=wx.TE_PROCESS_ENTER, name ='%s'% item)
-                        fun_box.SetToolTipString("Hit 'Enter' after typing.")
-                        fun_box.SetValue(format_number(value))
-                    sizer.Add(fun_box, (iy,ix),(1,1), wx.EXPAND)
-                    self.str_parameters.append([None,item, fun_box,
-                                                None,None,None,None,None])
-
-                    
-                else:
-                    ## add parameters name with checkbox for selecting to fit
-                    cb = wx.CheckBox(self, -1, item )              
-                    cb.SetToolTipString(" Check for fitting.")
-                    #cb.SetValue(True)
-                    wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
-                    
-                    sizer.Add( cb,( iy, ix),(1,1),
-                                 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 5)
-
-                    ## add parameter value
-                    ix += 1
-                    value= self.model.getParam(item)
-                    ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH,20),
-                                        style=wx.TE_PROCESS_ENTER)
-                    ctl1.SetToolTipString("Hit 'Enter' after typing.")
-                    ctl1.SetValue(format_number(value))
-                    sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
-                    ## text to show error sign
-                    ix += 1
-                    text2=wx.StaticText(self, -1, '+/-')
-                    sizer.Add(text2,(iy, ix),(1,1),\
-                                    wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-                    text2.Hide() 
-                    ix += 1
-                    ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=0)
-                    sizer.Add(ctl2, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                    ctl2.Hide()
-                    
-                    ix += 1
-                    ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
-                                               style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-         
-                    sizer.Add(ctl3, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                    ctl3.Hide()
-            
-                    ix += 1
-                    ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
-                                               style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-                    sizer.Add(ctl4, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-          
-                    ctl4.Hide()
-    
-                    if self.engine_type=="park":
-                        ctl3.Show(True)
-                        ctl4.Show(True)
-                    ix +=1
-                    # Units
-                    if self.model.details.has_key(item):
-                        units = wx.StaticText(self, -1, 
-                            self.model.details[item][0], style=wx.ALIGN_LEFT)
-                    else:
-                        units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
-                    sizer.Add(units, (iy,ix),(1,1), 
-                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                        
-                    ##[cb state, name, value, "+/-", error of fit, min, max , units]
-                    self.parameters.append([cb,item, ctl1,
-                                            text2,ctl2, ctl3, ctl4,units])
-                                  
-        iy+=1
-        sizer.Add((10,10),(iy,ix),(1,1), 
-                  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-        
-        # type can be either Guassian or Array
-        if len(self.model.dispersion.values())>0:
-            type= self.model.dispersion.values()[0]["type"]
-        else:
-            type = "Gaussian"
-            
-        iy += 1
-        ix = 0
-        #Add tile for orientational angle
-        for item in keys:
-            if item in self.model.orientation_params:       
-                orient_angle = wx.StaticText(self, -1, '[For 2D only]:')
-                sizer.Add(orient_angle,(iy, ix),(1,1), 
-                          wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
-                if not self.data.__class__.__name__ =="Data2D":
-                    orient_angle.Hide()
-                else:
-                    orient_angle.Show(True)
-                break
-      
-        #For Gaussian only
-        if type.lower() != "array":
-            for item in self.model.orientation_params:
-                if not item in self.disp_list:
-                    ##prepare a spot to store min max
-                    if not self.model.details.has_key(item):
-                        self.model.details [item] = ["",None,None] 
-                          
-                    iy += 1
-                    ix = 0
-                    ## add parameters name with checkbox for selecting to fit
-                    cb = wx.CheckBox(self, -1, item )
-                    cb.SetValue(False)
-                    cb.SetToolTipString("Check for fitting")
-                    wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
-                    if self.data.__class__.__name__ =="Data2D":
-                        cb.Show(True)
-                    else:
-                        cb.Hide()
-                    sizer.Add( cb,( iy, ix),(1,1),
-                                 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 5)
-    
-                    ## add parameter value
-                    ix += 1
-                    value= self.model.getParam(item)
-                    ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH,20),
-                                        style=wx.TE_PROCESS_ENTER)
-                    ctl1.SetToolTipString("Hit 'Enter' after typing.")
-                    ctl1.SetValue(format_number(value))
-                    if self.data.__class__.__name__ =="Data2D":
-                        ctl1.Show(True)
-                    else:
-                        ctl1.Hide()
-                    sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
-                    ## text to show error sign
-                    ix += 1
-                    text2=wx.StaticText(self, -1, '+/-')
-                    sizer.Add(text2,(iy, ix),(1,1),\
-                                    wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
-                    text2.Hide() 
-                    ix += 1
-                    ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=0)
-                    sizer.Add(ctl2, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                    ctl2.Hide()
-                    
-                    
-                    ix += 1
-                    ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,20), 
-                                              style=wx.TE_PROCESS_ENTER,
-                                text_enter_callback = self._onparamRangeEnter)
-                    
-                    sizer.Add(ctl3, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                    ctl3.Hide()
-                 
-                    ix += 1
-                    ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
-                                               style=wx.TE_PROCESS_ENTER,
-                            text_enter_callback = self._onparamRangeEnter)
-                    sizer.Add(ctl4, (iy,ix),(1,1), 
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                   
-                    ctl4.Hide()
-                    
-                    if self.engine_type =="park" and \
-                            self.data.__class__.__name__ =="Data2D":                      
-                        ctl3.Show(True)
-                        ctl4.Show(True)
-                    
-                    ix +=1
-                    # Units
-                    if self.model.details.has_key(item):
-                        units = wx.StaticText(self, -1, 
-                                              self.model.details[item][0], 
-                                              style=wx.ALIGN_LEFT)
-                    else:
-                        units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
-                    if self.data.__class__.__name__ =="Data2D":
-                        units.Show(True)
-                    
-                    else:
-                        units.Hide()
-                    
-                    sizer.Add(units, (iy,ix),(1,1),  
-                              wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-                                          
-                    ##[cb state, name, value, "+/-", error of fit,min,max,units]
-                    self.parameters.append([cb,item, ctl1,
-                                            text2,ctl2, ctl3, ctl4,units])
-                    self.orientation_params.append([cb,item, ctl1,
-                                            text2,ctl2, ctl3, ctl4,units])
-              
-        iy+=1
-        
-        #Display units text on panel
-        for item in keys:   
-            if self.model.details.has_key(item):
-                self.text2_4.Show()
-        #Fill the list of fittable parameters
-        self.select_all_param(event=None)
-
-        self.save_current_state_fit()
-        boxsizer1.Add(sizer)
-        self.sizer3.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
-        self.sizer3.Layout()
-        self.Layout()
-        self.Refresh()
-        self.SetupScrolling()
-        
-
-class BGTextCtrl(wx.TextCtrl):
-    """
-    Text control used to display outputs.
-    No editing allowed. The background is 
-    grayed out. User can't select text.
-    """
-    def __init__(self, *args, **kwds):
-        wx.TextCtrl.__init__(self, *args, **kwds)
-        self.SetEditable(False)
-        self.SetBackgroundColour(self.GetParent().GetBackgroundColour())
-        
-        # Bind to mouse event to avoid text highlighting
-        # The event will be skipped once the call-back
-        # is called.
-        self.Bind(wx.EVT_MOUSE_EVENTS, self._click)
-        
-    def _click(self, event):
-        """
-        Prevent further handling of the mouse event
-        by not calling Skip().
-        """ 
-        pass
- 
-"""
-Example: ::   
-    
-    class HelpWindow(wx.Frame):
-        def __init__(self, parent, id, title):
-            wx.Frame.__init__(self, parent, id, title, size=(570, 400))
-           
-            from sans.models.CylinderModel import CylinderModel
-            model = CylinderModel()
-           
-            from danse.common.plottools.plottables import Data1D
-            data= Data1D(x=[1,2], y=[3,4], dy=[0.1, 0,1])
-        
-            from fitpanel import PageInfo
-            myinfo = PageInfo(self,  model, data=data )
-            
-            ## add data
-            
-            from models import ModelList
-            mylist= ModelList()
-    
-            from sans.models.SphereModel import SphereModel
-            from sans.models.SquareWellStructure import SquareWellStructure
-            from sans.models.DebyeModel import DebyeModel
-            from sans.models.LineModel import LineModel
-            name= "shapes"
-            list1= [SphereModel]
-            mylist.set_list( name, list1)
-            
-            name= "Shape-independent"
-            list1= [DebyeModel]
-            mylist.set_list( name, list1)
-            
-            name= "Structure Factors"
-            list1= [SquareWellStructure]
-            mylist.set_list( name, list1)
-            
-            name= "Added models"
-            list1= [LineModel]
-            mylist.set_list( name, list1)
-            
-            myinfo.model_list_box = mylist.get_list()
-            
-            self.page = FitPage(self, myinfo) 
-            
-            self.Centre()
-            self.Show(True)
-     
-    if __name__=="__main__":
-        app = wx.App()
-        HelpWindow(None, -1, 'HelpWindow')
-        app.MainLoop()
-"""
-            
Index: nsview/perspectives/fitting/Copy of models.py
===================================================================
--- sansview/perspectives/fitting/Copy of models.py	(revision a07e72f8fb8281178797bf691b36e56274d8580b)
+++ 	(revision )
@@ -1,562 +1,0 @@
-
-import wx
-import wx.lib.newevent
-import imp
-import os,sys,math
-import os.path
-
-(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
-from sans.guiframe.events import StatusEvent  
-# Time is needed by the log method
-import time
-
-# Explicitly import from the pluginmodel module so that py2exe
-# places it in the distribution. The Model1DPlugin class is used
-# as the base class of plug-in models.
-from sans.models.pluginmodel import Model1DPlugin
-    
-def log(message):
-    """
-    """
-    out = open("plugins.log", 'a')
-    out.write("%10g:  %s\n" % (time.clock(), message))
-    out.close()
-
-def findModels():
-    """
-    """
-    log("looking for models in: %s/plugins" % os.getcwd())
-    if os.path.isdir('plugins'):
-        return _findModels('plugins')
-    return []
-    
-def _check_plugin(model, name):
-    """
-    Do some checking before model adding plugins in the list
-    
-    :param model: class model to add into the plugin list
-    :param name:name of the module plugin
-    
-    :return model: model if valid model or None if not valid
-    
-    """
-    #Check is the plugin is of type Model1DPlugin
-    if not issubclass(model, Model1DPlugin):
-        msg= "Plugin %s must be of type Model1DPlugin \n"%str(name)
-        log(msg)
-        return None
-    if model.__name__!="Model":
-        msg= "Plugin %s class name must be Model \n"%str(name)
-        log(msg)
-        return None
-    try:
-        new_instance= model()
-    except:
-        msg="Plugin %s error in __init__ \n\t: %s %s\n"%(str(name),
-                                    str(sys.exc_type),sys.exc_value)
-        log(msg)
-        return None
-   
-    new_instance= model() 
-    if hasattr(new_instance,"function"):
-        try:
-           value=new_instance.function()
-        except:
-           msg="Plugin %s: error writing function \n\t :%s %s\n "%(str(name),
-                                    str(sys.exc_type),sys.exc_value)
-           log(msg)
-           return None
-    else:
-       msg="Plugin  %s needs a method called function \n"%str(name)
-       log(msg)
-       return None
-    return model
-  
-  
-def _findModels(dir):
-    """
-    """
-    # List of plugin objects
-    plugins = []
-    # Go through files in plug-in directory
-    try:
-        list = os.listdir(dir)
-        for item in list:
-            toks = os.path.splitext(os.path.basename(item))
-            if toks[1]=='.py' and not toks[0]=='__init__':
-                name = toks[0]
-            
-                path = [os.path.abspath(dir)]
-                file = None
-                try:
-                    (file, path, info) = imp.find_module(name, path)
-                    module = imp.load_module( name, file, item, info )
-                    if hasattr(module, "Model"):
-                        try:
-                            if _check_plugin(module.Model, name)!=None:
-                                plugins.append(module.Model)
-                        except:
-                            msg="Error accessing Model"
-                            msg+="in %s\n  %s %s\n" % (name,
-                                    str(sys.exc_type), sys.exc_value)
-                            log(msg)
-                except:
-                    msg="Error accessing Model"
-                    msg +=" in %s\n  %s %s \n" %(name,
-                                    str(sys.exc_type), sys.exc_value)
-                    log(msg)
-                finally:
-              
-                    if not file==None:
-                        file.close()
-    except:
-        # Don't deal with bad plug-in imports. Just skip.
-        pass
-    return plugins
-
-class ModelList(object):
-    """
-    Contains dictionary of model and their type
-    """
-    def __init__(self):
-        """
-        """
-        self.mydict = {}
-        
-    def set_list(self, name, mylist):
-        """
-        :param name: the type of the list
-        :param mylist: the list to add
-        
-        """
-        if name not in self.mydict.keys():
-            self.mydict[name] = mylist
-            
-            
-    def get_list(self):
-        """
-        return all the list stored in a dictionary object
-        """
-        return self.mydict
-        
-class ModelManager:
-    """
-    """
-    ## external dict for models
-    model_combobox = ModelList()
-    ## Dictionary of form models
-    form_factor_dict = {}
-    ## dictionary of other
-    struct_factor_dict = {}
-    ##list of form factors
-    shape_list =[]
-    ## independent shape model list
-    shape_indep_list = []
-    ##list of structure factors 
-    struct_list= []
-    ##list of model allowing multiplication
-    multiplication_factor=[]
-    ##list of multifunctional shapes
-    multi_func_list =[]
-    ## list of added models
-    plugins=[]
-    ## Event owner (guiframe)
-    event_owner = None
-    
-    def _getModelList(self):
-        """
-        List of models we want to make available by default
-        for this application
-    
-        :return: the next free event ID following the new menu events
-        
-        """
-        from sans.models.SphereModel import SphereModel
-        self.shape_list.append(SphereModel)
-        self.multiplication_factor.append(SphereModel)
-        
-        from sans.models.BinaryHSModel import BinaryHSModel
-        self.shape_list.append(BinaryHSModel)
-                        
-        from sans.models.FuzzySphereModel import FuzzySphereModel
-        self.shape_list.append(FuzzySphereModel)
-        self.multiplication_factor.append(FuzzySphereModel)
-           
-        from sans.models.CoreShellModel import CoreShellModel
-        self.shape_list.append(CoreShellModel)
-        self.multiplication_factor.append(CoreShellModel)
-        
-        from sans.models.CoreMultiShellModel import CoreMultiShellModel
-        self.shape_list.append(CoreMultiShellModel)
-        self.multiplication_factor.append(CoreMultiShellModel)
-        self.multi_func_list.append(CoreMultiShellModel)
-
-        from sans.models.VesicleModel import VesicleModel
-        self.shape_list.append(VesicleModel)
-        self.multiplication_factor.append(VesicleModel)
-        
-        from sans.models.MultiShellModel import MultiShellModel
-        self.shape_list.append(MultiShellModel)
-        self.multiplication_factor.append(MultiShellModel)
-        
-        from sans.models.OnionExpShellModel import OnionExpShellModel
-        self.shape_list.append(OnionExpShellModel)
-        self.multiplication_factor.append(OnionExpShellModel)
-        self.multi_func_list.append(OnionExpShellModel)
-                        
-        from sans.models.SphericalSLDModel import SphericalSLDModel
-        self.shape_list.append(SphericalSLDModel)
-        self.multiplication_factor.append(SphericalSLDModel)
-        self.multi_func_list.append(SphericalSLDModel)
-        
-        from sans.models.CylinderModel import CylinderModel
-        self.shape_list.append(CylinderModel)
-        self.multiplication_factor.append(CylinderModel)
-        
-        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
-        self.shape_list.append(CoreShellCylinderModel)
-        self.multiplication_factor.append(CoreShellCylinderModel)
-        
-        from sans.models.HollowCylinderModel import HollowCylinderModel
-        self.shape_list.append(HollowCylinderModel)
-        self.multiplication_factor.append(HollowCylinderModel)
-              
-        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
-        self.shape_list.append(FlexibleCylinderModel)
-
-        from sans.models.FlexCylEllipXModel import FlexCylEllipXModel
-        self.shape_list.append(FlexCylEllipXModel)
-        
-        from sans.models.StackedDisksModel import StackedDisksModel
-        self.shape_list.append(StackedDisksModel)
-        self.multiplication_factor.append(StackedDisksModel)
-        
-        from sans.models.ParallelepipedModel import ParallelepipedModel
-        self.shape_list.append(ParallelepipedModel)
-        self.multiplication_factor.append(ParallelepipedModel)
-        
-        from sans.models.CSParallelepipedModel import CSParallelepipedModel
-        self.shape_list.append(CSParallelepipedModel)
-        self.multiplication_factor.append(CSParallelepipedModel)
-        
-        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
-        self.shape_list.append(EllipticalCylinderModel)
-        self.multiplication_factor.append(EllipticalCylinderModel)
-        
-        from sans.models.BarBellModel import BarBellModel
-        self.shape_list.append(BarBellModel)
-        # not implemeted yet!
-        #self.multiplication_factor.append(BarBellModel)
-        
-        from sans.models.CappedCylinderModel import CappedCylinderModel
-        self.shape_list.append(CappedCylinderModel)
-        # not implemeted yet!
-        #self.multiplication_factor.append(CappedCylinderModel)
-        
-        from sans.models.EllipsoidModel import EllipsoidModel
-        self.shape_list.append(EllipsoidModel)
-        self.multiplication_factor.append(EllipsoidModel)
-      
-        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
-        self.shape_list.append(CoreShellEllipsoidModel)
-        self.multiplication_factor.append(CoreShellEllipsoidModel)
-         
-        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
-        self.shape_list.append(TriaxialEllipsoidModel)
-        self.multiplication_factor.append(TriaxialEllipsoidModel)
-        
-        from sans.models.LamellarModel import LamellarModel
-        self.shape_list.append(LamellarModel)
-        
-        from sans.models.LamellarFFHGModel import LamellarFFHGModel
-        self.shape_list.append(LamellarFFHGModel)
-        
-        from sans.models.LamellarPSModel import LamellarPSModel
-        self.shape_list.append(LamellarPSModel)
-     
-        from sans.models.LamellarPSHGModel import LamellarPSHGModel
-        self.shape_list.append(LamellarPSHGModel)
-        
-        from sans.models.LamellarPCrystalModel import LamellarPCrystalModel
-        self.shape_list.append(LamellarPCrystalModel)
-        
-        from sans.models.SCCrystalModel import SCCrystalModel
-        self.shape_list.append(SCCrystalModel)
-        
-        from sans.models.FCCrystalModel import FCCrystalModel
-        self.shape_list.append(FCCrystalModel)
-        
-        from sans.models.BCCrystalModel import BCCrystalModel
-        self.shape_list.append(BCCrystalModel)
-      
-        ## Structure factor 
-        from sans.models.SquareWellStructure import SquareWellStructure
-        self.struct_list.append(SquareWellStructure)
-        
-        from sans.models.HardsphereStructure import HardsphereStructure
-        self.struct_list.append(HardsphereStructure)
-         
-        from sans.models.StickyHSStructure import StickyHSStructure
-        self.struct_list.append(StickyHSStructure)
-        
-        from sans.models.HayterMSAStructure import HayterMSAStructure
-        self.struct_list.append(HayterMSAStructure)
-        
-        ##shape-independent models
-        from sans.models.PowerLawAbsModel import PowerLawAbsModel
-        self.shape_indep_list.append( PowerLawAbsModel )
-        
-        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
-        self.shape_indep_list.append(BEPolyelectrolyte )
-        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
-        
-        from sans.models.BroadPeakModel import BroadPeakModel
-        self.shape_indep_list.append(BroadPeakModel)
-        
-        from sans.models.CorrLengthModel import CorrLengthModel
-        self.shape_indep_list.append(CorrLengthModel)
-        
-        from sans.models.DABModel import DABModel
-        self.shape_indep_list.append(DABModel )
-        
-        from sans.models.DebyeModel import DebyeModel
-        self.shape_indep_list.append(DebyeModel )
-        
-        #FractalModel (a c-model)is now being used instead of FractalAbsModel.
-        from sans.models.FractalModel import FractalModel
-        self.shape_indep_list.append(FractalModel )
-        
-        from sans.models.FractalCoreShellModel import FractalCoreShellModel
-        self.shape_indep_list.append(FractalCoreShellModel )
-        
-        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
-        self.shape_indep_list.append(GaussLorentzGelModel) 
-                
-        from sans.models.GuinierModel import GuinierModel
-        self.shape_indep_list.append(GuinierModel )
-        
-        from sans.models.GuinierPorodModel import GuinierPorodModel
-        self.shape_indep_list.append(GuinierPorodModel )
-
-        from sans.models.LorentzModel import LorentzModel
-        self.shape_indep_list.append( LorentzModel) 
-        
-        from sans.models.PeakGaussModel import PeakGaussModel
-        self.shape_indep_list.append(PeakGaussModel)
-        
-        from sans.models.PeakLorentzModel import PeakLorentzModel
-        self.shape_indep_list.append(PeakLorentzModel)
-        
-        from sans.models.Poly_GaussCoil import Poly_GaussCoil
-        self.shape_indep_list.append(Poly_GaussCoil)
-        
-        from sans.models.PolymerExclVolume import PolymerExclVolume
-        self.shape_indep_list.append(PolymerExclVolume)
-        
-        from sans.models.PorodModel import PorodModel
-        self.shape_indep_list.append(PorodModel )      
-        
-        from sans.models.RPA10Model import RPA10Model
-        self.shape_indep_list.append(RPA10Model)
-        self.multi_func_list.append(RPA10Model)
-        
-        from sans.models.TeubnerStreyModel import TeubnerStreyModel
-        self.shape_indep_list.append(TeubnerStreyModel )
-        
-        from sans.models.TwoLorentzianModel import TwoLorentzianModel
-        self.shape_indep_list.append(TwoLorentzianModel )
-        
-        from sans.models.TwoPowerLawModel import TwoPowerLawModel
-        self.shape_indep_list.append(TwoPowerLawModel )
-        
-        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
-        self.shape_indep_list.append(UnifiedPowerRgModel )
-        self.multi_func_list.append(UnifiedPowerRgModel)
-        
-        from sans.models.LineModel import LineModel
-        self.shape_indep_list.append(LineModel)
-        
-        from sans.models.ReflectivityModel import ReflectivityModel
-        self.multi_func_list.append(ReflectivityModel)
-        
-        from sans.models.ReflectivityIIModel import ReflectivityIIModel
-        self.multi_func_list.append(ReflectivityIIModel)
-    
-        #Looking for plugins
-        self.plugins = findModels()
-        self._get_multifunc_models()
-        self.plugins.append(ReflectivityModel)
-        self.plugins.append(ReflectivityIIModel)
-        return 0
-
-    
-    def populate_menu(self, modelmenu, event_owner):
-        """
-        Populate a menu with our models
-        
-        :param id: first menu event ID to use when binding the menu events
-        :param modelmenu: wx.Menu object to populate
-        :param event_owner: wx object to bind the menu events to
-        
-        :return: the next free event ID following the new menu events
-        
-        """
-        ## Fill model lists
-        self._getModelList()
-        ## store reference to model menu of guiframe
-        self.modelmenu = modelmenu
-        ## guiframe reference
-        self.event_owner = event_owner
-        
-        shape_submenu = wx.Menu()
-        shape_indep_submenu = wx.Menu()
-        structure_factor = wx.Menu()
-        added_models = wx.Menu()
-        multip_models = wx.Menu()
-        ## create menu with shape
-        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
-                         list1=self.shape_list)
-        
-        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
-                                    "List of shape-independent models"],
-                         list1=self.shape_indep_list )
-        
-        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
-                                          "List of Structure factors models" ],
-                                list1=self.struct_list)
-        
-        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
-                                            "List of additional models"],
-                                 list1=self.plugins)
-        
-        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
-                                  "mulplication of 2 models"],
-                                   list1=self.multiplication_factor ,
-                                   list2= self.struct_list)
-        return 0
-    
-    def _fill_plugin_menu(self, menuinfo, list1):
-        """
-        fill the plugin menu with costumized models
-        """
-        if len(list1)==0:
-            id = wx.NewId() 
-            msg= "No model available check plugins.log for errors to fix problem"
-            menuinfo[1].Append(int(id),"Empty",msg)
-        self._fill_simple_menu( menuinfo,list1)
-        
-    def _fill_simple_menu(self, menuinfo, list1):
-        """
-        Fill the menu with list item
-        
-        :param modelmenu: the menu to fill
-        :param menuinfo: submenu item for the first column of this modelmenu
-                         with info.Should be a list :
-                         [name(string) , menu(wx.menu), help(string)]
-        :param list1: contains item (form factor )to fill modelmenu second column
-        
-        """
-        if len(list1)>0:
-            self.model_combobox.set_list(menuinfo[0],list1)
-            
-            for item in list1:
-                try:
-                    id = wx.NewId() 
-                    struct_factor=item()
-                    struct_name = struct_factor.__class__.__name__
-                    if hasattr(struct_factor, "name"):
-                        struct_name = struct_factor.name
-                        
-                    menuinfo[1].Append(int(id),struct_name,struct_name)
-                    if not  item in self.struct_factor_dict.itervalues():
-                        self.struct_factor_dict[str(id)]= item
-                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
-                except:
-                    msg= "Error Occured: %s"%sys.exc_value
-                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
-                
-        id = wx.NewId()         
-        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
-        
-    def _fill_menu(self, menuinfo, list1, list2):
-        """
-        Fill the menu with list item
-        
-        :param menuinfo: submenu item for the first column of this modelmenu
-                         with info.Should be a list :
-                         [name(string) , menu(wx.menu), help(string)]
-        :param list1: contains item (form factor )to fill modelmenu second column
-        :param list2: contains item (Structure factor )to fill modelmenu 
-                third column
-                
-        """
-        if len(list1)>0:
-            self.model_combobox.set_list(menuinfo[0],list1)
-            
-            for item in list1:   
-                form_factor= item()
-                form_name = form_factor.__class__.__name__
-                if hasattr(form_factor, "name"):
-                    form_name = form_factor.name
-                ### store form factor to return to other users   
-                newmenu= wx.Menu()
-                if len(list2)>0:
-                    for model  in list2:
-                        id = wx.NewId()
-                        struct_factor = model()
-                        name = struct_factor.__class__.__name__
-                        if hasattr(struct_factor, "name"):
-                            name = struct_factor.name
-                        newmenu.Append(id,name, name)
-                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
-                        ## save form_fact and struct_fact
-                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
-                        
-                form_id= wx.NewId()    
-                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
-        id=wx.NewId()
-        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
-        
-    def _on_model(self, evt):
-        """
-        React to a model menu event
-        
-        :param event: wx menu event
-        
-        """
-        if int(evt.GetId()) in self.form_factor_dict.keys():
-            from sans.models.MultiplicationModel import MultiplicationModel
-            model1, model2 = self.form_factor_dict[int(evt.GetId())]
-            model = MultiplicationModel(model1, model2)    
-        else:
-            model= self.struct_factor_dict[str(evt.GetId())]()
-        evt = ModelEvent(model=model)
-        wx.PostEvent(self.event_owner, evt)
-        
-    def _get_multifunc_models(self):
-        """
-        Get the multifunctional models
-        """
-        for item in self.plugins:
-            try:
-                # check the multiplicity if any
-                if item.multiplicity_info[0] > 1:
-                    self.multi_func_list.append(item)
-            except:
-                # pass to other items
-                pass
-                    
-    def get_model_list(self):    
-        """
-        return dictionary of models for fitpanel use 
-        
-        """
-        self.model_combobox.set_list("multiplication", self.multiplication_factor)
-        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
-        return self.model_combobox
-    
-  
-        
-    
-    
-  
