source: sasview/sansview/perspectives/fitting/basepage.py @ 852354c8

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 852354c8 was 66ff250, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on fit stop

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