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

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

working on fitting page

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