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

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

working on toggle1d \2d view

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