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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since da9ac4e6 was da9ac4e6, checked in by Jae Cho <jhjcho@…>, 14 years ago

moved sldprofile to guiframe

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