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

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

working on saving page status

  • Property mode set to 100644
File size: 48.0 KB
Line 
1
2import sys
3import wx
4import numpy
5
6from sans.guiframe.utils import format_number
7from sans.guicomm.events import StatusEvent   
8import pagestate
9from pagestate import PageState
10(PageInfoEvent, EVT_PAGE_INFO)   = wx.lib.newevent.NewEvent()
11_BOX_WIDTH = 80
12
13class BasicPage(wx.ScrolledWindow):
14    """
15        This class provide general structure of  fitpanel page
16    """
17   
18    def __init__(self,parent, page_info):
19        wx.ScrolledWindow.__init__(self, parent)
20        ## store name
21        self.name = page_info.name
22        ##window_name
23        self.window_name = page_info.window_name
24        ##window_caption
25        self.window_caption = page_info.window_caption
26        ## parent of the page
27        self.parent = parent
28        ## manager is the fitting plugin
29        self.manager= page_info.manager
30        ## owner of the page (fitting plugin)
31        self.event_owner= page_info.event_owner
32         ## current model
33        self.model = page_info.model
34        ## data
35        self.data = page_info.data
36        ## dictionary containing list of models
37        self.model_list_box = page_info.model_list_box
38        ## Data member to store the dispersion object created
39        self._disp_obj_dict = {}
40        ## selected parameters to apply dispersion
41        self.disp_cb_dict ={}
42        ##list of model parameters. each item must have same length
43        ## each item related to a given parameters
44        ##[cb state, name, value, "+/-", error of fit, min, max , units]
45        self.parameters=[]
46        ## list of parameters to fit , must be like self.parameters
47        self.param_toFit=[]
48        ## list of looking like parameters but with non fittable parameters info
49        self.fixed_param=[]
50        ## list of looking like parameters but with  fittable parameters info
51        self.fittable_param=[]
52        ##list of dispersion parameters
53        self.disp_list=[]
54        if self.model !=None:
55            self.disp_list= self.model.getDispParamList()
56        ##enable model 2D draw
57        self.enable2D= False
58        ## check that the fit range is correct to plot the model again
59        self.fitrange= True
60        ## Q range
61        self.qmin_x= 0.001
62        self.qmax_x= 0.1
63        self.num_points= 100
64        ## Create memento to save the current state
65       
66        self.state= PageState(parent= self.parent,model=self.model, data=self.data)
67        ## create the basic structure of the panel with empty sizer
68        self.define_page_structure()
69        ## drawing Initial dispersion parameters sizer
70        self.set_dispers_sizer()
71        self._fill_save_sizer()
72       
73        ## layout
74        self.set_layout()
75       
76       
77    def define_page_structure(self):
78        """
79            Create empty sizer for a panel
80        """
81        self.vbox  = wx.BoxSizer(wx.VERTICAL)
82        self.sizer0 = wx.BoxSizer(wx.VERTICAL)
83        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
84        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
85        self.sizer3 = wx.BoxSizer(wx.VERTICAL)
86        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
87        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
88        self.sizer6 = wx.BoxSizer(wx.VERTICAL)
89       
90        self.sizer0.SetMinSize((375,-1))
91        self.sizer1.SetMinSize((375,-1))
92        self.sizer2.SetMinSize((375,-1))
93        self.sizer3.SetMinSize((375,-1))
94        self.sizer4.SetMinSize((375,-1))
95        self.sizer5.SetMinSize((375,-1))
96        self.sizer6.SetMinSize((375,-1))
97       
98        self.vbox.Add(self.sizer0)
99        self.vbox.Add(self.sizer1)
100        self.vbox.Add(self.sizer2)
101        self.vbox.Add(self.sizer3)
102        self.vbox.Add(self.sizer4)
103        self.vbox.Add(self.sizer5)
104        self.vbox.Add(self.sizer6)
105       
106    def set_layout(self):
107        """
108             layout
109        """
110        self.vbox.Layout()
111        self.vbox.Fit(self) 
112        self.SetSizer(self.vbox)
113       
114        self.set_scroll()
115        self.Centre()
116       
117    def set_scroll(self):
118        self.SetScrollbars(20,20,200,100)
119        self.Layout()   
120        self.SetAutoLayout(True)
121         
122    def set_owner(self,owner):
123        """
124            set owner of fitpage
125            @param owner: the class responsible of plotting
126        """
127        self.event_owner = owner   
128        self.state.event_owner = owner
129 
130    def set_manager(self, manager):
131        """
132             set panel manager
133             @param manager: instance of plugin fitting
134        """
135        self.manager = manager 
136        self.state.manager = manager
137       
138    def populate_box(self, dict):
139        """
140             Store list of model
141             @param dict: dictionary containing list of models
142        """
143        self.model_list_box = dict
144        self.state.model_list_box = self.model_list_box
145           
146   
147       
148    def set_dispers_sizer(self):
149        """
150            fill sizer containing dispersity info
151        """
152        self.sizer4.Clear(True)
153        box_description= wx.StaticBox(self, -1,"PolyDispersity")
154        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
155        #----------------------------------------------------
156        self.disable_disp = wx.RadioButton(self, -1, 'No', (10, 10), style=wx.RB_GROUP)
157        self.enable_disp = wx.RadioButton(self, -1, 'Yes', (10, 30))
158        ## saving the state of enable dispersity button
159        self.state.enable_disp= self.enable_disp.GetValue()
160       
161        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param, id=self.disable_disp.GetId())
162        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param, id=self.enable_disp.GetId())
163       
164        sizer_dispersion = wx.BoxSizer(wx.HORIZONTAL)
165        sizer_dispersion.Add((20,20))
166        sizer_dispersion.Add(wx.StaticText(self,-1,'Polydispersity: '))
167        sizer_dispersion.Add(self.enable_disp )
168        sizer_dispersion.Add((20,20))
169        sizer_dispersion.Add(self.disable_disp )
170        sizer_dispersion.Add((10,10))
171       
172        ## fill a sizer with the combobox to select dispersion type
173        sizer_select_dispers = wx.BoxSizer(wx.HORIZONTAL) 
174        self.model_disp = wx.StaticText(self, -1, 'Model Disp')
175           
176        import sans.models.dispersion_models 
177        self.polydisp= sans.models.dispersion_models.models
178        self.disp_box = wx.ComboBox(self, -1)
179        self.disp_box.SetValue("GaussianModel")
180       
181        for key in self.polydisp.iterkeys():
182            name = str(key.__name__)
183            if name=="ArrayDispersion":
184                # Remove the option until the rest of the code is ready for it
185                self.disp_box.Append("Select customized Model",key)
186                pass 
187            else:
188                self.disp_box.Append(name,key) 
189        wx.EVT_COMBOBOX(self.disp_box,-1, self._on_select_Disp) 
190             
191        sizer_select_dispers.Add((10,10)) 
192        sizer_select_dispers.Add(self.model_disp) 
193        sizer_select_dispers.Add(self.disp_box) 
194        sizer_select_dispers.Add((10,10)) 
195        self.model_disp.Hide()
196        self.disp_box.Hide()
197       
198        boxsizer1.Add( sizer_dispersion )
199        boxsizer1.Add( (10,10) )
200        boxsizer1.Add( sizer_select_dispers )
201        self.sizer4_4 = wx.GridBagSizer(5,5)
202        boxsizer1.Add( self.sizer4_4  )
203        #-----------------------------------------------------
204        self.sizer4.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
205        self.sizer4.Layout()
206       
207        self.SetScrollbars(20,20,200,100)
208       
209   
210    def select_disp_angle(self, event): 
211        """
212            Event for when a user select a parameter to average over.
213            @param event: check box event
214        """
215       
216       
217        # Go through the list of dispersion check boxes to identify which one has changed
218        for p in self.disp_cb_dict:
219            # Catch which one of the box was just checked or unchecked.
220            if event.GetEventObject() == self.disp_cb_dict[p]:             
221
222               
223                if self.disp_cb_dict[p].GetValue() == True:
224                    # The user wants this parameter to be averaged.
225                    # Pop up the file selection dialog.
226                    path = self._selectDlg()
227                   
228                    # If nothing was selected, just return
229                    if path is None:
230                        self.disp_cb_dict[p].SetValue(False)
231                        return
232                   
233                    try:
234                        values,weights = self.read_file(path)
235                    except:
236                        msg="Could not read input file"
237                        wx.PostEvent(self.parent.parent, StatusEvent(status= msg))
238                        return
239                   
240                    # If any of the two arrays is empty, notify the user that we won't
241                    # proceed
242                    if values is None or weights is None:
243                        wx.PostEvent(self.parent.parent, StatusEvent(status=\
244                            "The loaded %s distrubtion is corrupted or empty" % p))
245                        return
246                       
247                    # Tell the user that we are about to apply the distribution
248                    wx.PostEvent(self.parent.parent, StatusEvent(status=\
249                            "Applying loaded %s distribution: %s" % (p, path))) 
250                   
251                    # Create the dispersion objects
252                    from sans.models.dispersion_models import ArrayDispersion
253                    disp_model = ArrayDispersion()
254                    disp_model.set_weights(values, weights)
255                    # Store the object to make it persist outside the scope of this method
256                    #TODO: refactor model to clean this up?
257                    self._disp_obj_dict[p] = disp_model
258                   
259                    # Set the new model as the dispersion object for the selected parameter
260                    self.model.set_dispersion(p, disp_model)
261                         
262                else:
263                    # The parameter was un-selected. Go back to Gaussian model (with 0 pts)
264                    self._reset_dispersity()
265                   
266                ## Redraw the model
267                self._draw_model()
268        return
269   
270    def onSave(self, event):
271        """
272            save history of the data and model
273        """
274        self.state.model= self.model
275        self.state.data = self.data
276        import os
277                 
278           
279        path = None
280        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt", wx.SAVE)
281        if dlg.ShowModal() == wx.ID_OK:
282            path = dlg.GetPath()
283            mypath = os.path.basename(path)
284           
285        dlg.Destroy()
286           
287        if not path == None:
288            out = open(path, 'w')
289            has_data = self.data !=None
290            has_model = self.model!=None
291            import time
292            year, month, day,hour,minute,second,tda,ty,tm_isdst= time.gmtime()
293            import os.path
294            out.write("Title: State for %s\n"%os.path.basename(path))
295            out.write("Date: %g\%g\%g \n"%(year, month, day))
296            out.write("GMT Time: %g:%g:%g \n\n"%(hour,minute, second))
297            # Sanity check
298            if has_data:
299                out.write("Fit Data name: %s\n\n"%self.data.name)
300   
301            if has_model:
302                out.write("Model name: %s\n"%self.model.name)
303                if len(self.parameters)>0: 
304                    out.write("Parameters Info:\n")
305                    msg= "Name\t\tValues\t\t+\-\tErrors\t\tMin\t\tMax\t\tUnits\t\tstate\n"
306                    out.write(msg)
307                    ##self.parameters=
308                    ##[cb state, name, value, "+/-", error of fit, min, max , units]
309                    for item in self.parameters:
310                        if item[1]!=None:
311                            name= item[1]
312                        else:
313                            name=""
314                        if item[2]!=None:
315                            value= str(item[2].GetValue().rstrip().lstrip())
316                        else:
317                            value=""
318                        if item[3]!=None:
319                            sign= str(item[3].GetLabelText().rstrip().lstrip())
320                        else:
321                            sign=""
322                        if item[4]!=None:
323                            error= str(item[4].GetValue().rstrip().lstrip())
324                        else:
325                            error=""
326                        if item[5]!=None:
327                            min= str(item[5].GetValue().rstrip().lstrip())
328                        else:
329                            min=""
330                        if item[6]!=None:
331                            max= str(item[6].GetValue().rstrip().lstrip())
332                        else:
333                            max=""
334                        if item[7]!=None:
335                            unit= str(item[7].GetLabelText().rstrip().lstrip())
336                        else:
337                            unit=""
338                        if item[0]!=None:
339                            if item[0].GetValue():
340                                state= "Fitted"
341                            else:
342                                state= "Not Fitted"
343                        else:
344                            state="Not Fitted"
345   
346                        msg= "%s\t\t%s\t\t%s\t%s\t\t%s\t\t%s\t\t%s\t\t%s\n"\
347                         %(name,value,sign,error,min,max,unit,state)
348                        out.write(msg)
349                       
350               
351            out.close()
352
353     
354    def onSetFocus(self, evt):
355        """
356            highlight the current textcrtl and hide the error text control shown
357            after fitting
358        """
359       
360        if hasattr(self,"text2_3"):
361            self.text2_3.Hide()
362        if len(self.parameters)>0:
363            for item in self.parameters:
364                ## hide statictext +/-   
365                if item[3]!=None:
366                    item[3].Hide()
367                ## hide textcrtl  for error after fit
368                if item[4]!=None:
369                    item[4].Clear()
370                    item[4].Hide()
371        if len(self.fittable_param)>0:
372            for item in self.fittable_param:
373                ## hide statictext +/-   
374                if item[3]!=None:
375                    item[3].Hide()
376                ## hide textcrtl  for error after fit
377                if item[4]!=None:
378                    item[4].Clear()
379                    item[4].Hide()
380        self.Layout()
381        # Get a handle to the TextCtrl
382        widget = evt.GetEventObject()
383        # Select the whole control, after this event resolves
384        wx.CallAfter(widget.SetSelection, -1,-1)
385        return
386   
387    def read_file(self, path):
388        """
389            Read two columns file
390            @param path: the path to the file to read
391        """
392        try:
393            if path==None:
394                wx.PostEvent(self.parent.parent, StatusEvent(status=\
395                            " Selected Distribution was not loaded: %s"%path))
396                return None, None
397            input_f = open(path, 'r')
398            buff = input_f.read()
399            lines = buff.split('\n')
400           
401            angles = []
402            weights=[]
403            for line in lines:
404                toks = line.split()
405                if len(toks)==2:
406                    try:
407                        angle = float(toks[0])
408                        weight = float(toks[1])
409                    except:
410                        # Skip non-data lines
411                        pass
412                    angles.append(angle)
413                    weights.append(weight)
414            return numpy.array(angles), numpy.array(weights)
415        except:
416            raise 
417   
418   
419    def createMemento(self):
420        """
421            return the current state of the page
422        """
423        return self.state.clone()
424   
425   
426    def save_current_state(self):
427        """
428            Store current state
429        """
430        self.state.model = self.model.clone()
431        self.state.save_data(self.data)
432   
433        if hasattr(self,"cb1"):
434            self.state.cb1= self.cb1.GetValue()
435           
436        if hasattr(self,"enable_disp"):
437            self.state.enable_disp= self.enable_disp.GetValue()
438           
439        if hasattr(self,"enable_smearer"):
440            self.state.enable_smearer = self.enable_smearer.GetValue()   
441     
442        ## save checkbutton state and txtcrtl values
443        self.state.parameters=[]
444        self.state.fittable_param=[]
445        self.state.fixed_param=[]
446        self._copy_parameters_state(self.parameters, self.state.parameters)
447        self._copy_parameters_state(self.fittable_param, self.state.fittable_param)
448        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
449       
450        ## post state to fit panel
451        event = PageInfoEvent(page = self)
452        wx.PostEvent(self.parent, event)
453   
454    def reset_page(self, state):
455        """
456            Use page_info and change the state of existing button
457        """
458        self.state = state.clone()
459        self.model= self.state.model
460        self.data = self.state.data
461        self._set_model_sizer_selection( self.model )
462        self.set_model_param_sizer(self.model)
463        self._reset_plotting_range()
464       
465        self.enable_disp.SetValue(self.state.enable_disp)
466        self._set_dipers_Param(event=None)
467       
468        if hasattr(self,"enable_smearer"):
469            self.enable_smearer= self.state.enable_smearer
470        if hasattr(self, "cb1"):   
471            self.cb1.SetValue(self.state.cb1)
472        self._reset_parameters_state(self.parameters,state.parameters)
473        self._reset_parameters_state(self.fittable_param,state.fittable_param)
474        self._reset_parameters_state(self.fixed_param,state.fixed_param)
475        self._draw_model()
476       
477       
478    def _selectDlg(self):
479        """
480            open a dialog file to selected the customized dispersity
481        """
482        import os
483        dlg = wx.FileDialog(self, "Choose a weight file", os.getcwd(), "", "*.*", wx.OPEN)
484        path = None
485        if dlg.ShowModal() == wx.ID_OK:
486            path = dlg.GetPath()
487        dlg.Destroy()
488        return path
489   
490   
491    def _reset_plotting_range(self):
492        """
493            Reset the plotting range to a given state
494        """
495       
496        self.qmin.SetValue(format_number(self.state.qmin))
497        self.qmax.SetValue(format_number(self.state.qmax)) 
498        if self.state.npts!=None:
499            self.npts= self.state.npts
500           
501        self.qmin_x = float(self.qmin.GetValue())
502        self.qmax_x = float(self.qmax.GetValue())
503       
504       
505    def _save_plotting_range(self ):
506        """
507            save the state of plotting range
508        """
509        self.state.qmin = self.qmin.GetValue()   
510        self.state.qmax = self.qmax.GetValue()   
511        if self.npts!=None:
512            self.state.npts= self.npts.GetValue()
513           
514           
515    def _onparamEnter_helper(self):
516        """
517             check if values entered by the user are changed and valid to replot
518             model
519             use : _check_value_enter
520        """
521        if self.model !=None:
522            self.save_current_state()
523            # Flag to register when a parameter has changed.
524            is_modified = False
525            is_modified =self._check_value_enter( self.fittable_param ,is_modified)
526            is_modified =self._check_value_enter( self.fixed_param ,is_modified)
527            is_modified =self._check_value_enter( self.parameters ,is_modified)       
528           
529           
530            self.Layout()
531            # Here we should check whether the boundaries have been modified.
532            # If qmin and qmax have been modified, update qmin and qmax and
533            # set the is_modified flag to True
534            from sans.guiframe.utils import check_value
535            if check_value( self.qmin, self.qmax):
536                if float(self.qmin.GetValue()) != self.qmin_x:
537                    self.qmin_x = float(self.qmin.GetValue())
538                    is_modified = True
539                if float(self.qmax.GetValue()) != self.qmax_x:
540                    self.qmax_x = float(self.qmax.GetValue())
541                    is_modified = True
542                self.fitrange = True
543            else:
544                self.fitrange = False
545            if self.npts != None:
546                if float(self.npts.GetValue()) !=  self.num_points:
547                    self.num_points = float(self.npts.GetValue())
548                    is_modified = True
549            ## if any value is modify draw model with new value
550            if is_modified:
551                self._draw_model() 
552               
553               
554    def _reset_parameters_state(self, listtorestore,statelist):
555        """
556            Reset the parameters at the given state
557        """
558        if len(self.state.parameters)!=  len(listtorestore) :
559            return
560        for j in range(len(listtorestore)):
561            item_page = listtorestore[j]
562            item_page_info = statelist[j]
563            ##change the state of the check box for simple parameters
564            if item_page[0]!=None:
565                item_page[0].SetValue(item_page_info[0])
566   
567            if item_page[2]!=None:
568                item_page[2].SetValue(item_page_info[2])
569               
570            if item_page[3]!=None:
571                ## show or hide text +/-
572                if item_page_info[2]:
573                    item_page[3].Show(True)
574                else:
575                    item_page[3].Hide()
576            if item_page[4]!=None:
577                ## show of hide the text crtl for fitting error
578                if item_page_info[4][0]:
579                    item_page[4].Show(True)
580                    item_page[4].SetValue(item_page_info[4][1])
581                else:
582                    item_page[3].Hide()
583            if item_page[5]!=None:
584                ## show of hide the text crtl for fitting error
585                if item_page_info[5][0]:
586                    item_page[5].Show(True)
587                    item_page[5].SetValue(item_page_info[4][1])
588                else:
589                    item_page[5].Hide()
590                   
591            if item_page[6]!=None:
592                ## show of hide the text crtl for fitting error
593                if item_page_info[6][0]:
594                    item_page[6].Show(True)
595                    item_page[6].SetValue(item_page_info[6][1])
596                else:
597                    item_page[6].Hide()
598                           
599    def _copy_parameters_state(self, listtocopy, statelist):
600        """
601            copy the state of button
602            @param listtocopy: the list of check button to copy
603            @param statelist: list of state object to store the current state
604        """
605        if len(listtocopy)==0:
606            return
607       
608        for item in listtocopy:
609            checkbox_state = None
610            if item[0]!= None:
611                checkbox_state= item[0].GetValue()
612            parameter_name = item[1]
613            parameter_value = None
614            if item[2]!=None:
615                parameter_value = item[2].GetValue()
616            static_text = None
617            if item[3]!=None:
618                static_text = item[3].IsShown()
619            error_value = None
620            error_state = None
621            if item[4]!= None:
622                error_value = item[4].GetValue()
623                error_state = item[4].IsShown()
624               
625            min_value = None
626            min_state = None
627            if item[5]!= None:
628                min_value = item[5].GetValue()
629                min_state = item[5].IsShown()
630               
631            max_value = None
632            max_state = None
633            if item[6]!= None:
634                max_value = item[6].GetValue()
635                max_state = item[6].IsShown()
636               
637            statelist.append([checkbox_state, parameter_name, parameter_value,
638                              static_text ,[error_state,error_value],
639                                [min_state,min_value],[max_state , max_value],None])
640           
641       
642   
643    def _set_model_sizer_selection(self, model):
644        """
645            Display the sizer according to the type of the current model
646        """
647        if hasattr(model ,"model2"):
648           
649            class_name= model.model2.__class__
650            name= model.model2.name
651            flag= name != "NoStructure"
652            if flag and (class_name in self.model_list_box["Structure Factors"]):
653                self.structurebox.Show(True)
654                self.text2.Show(True)
655                self.multip_cb.SetValue(True)
656                items = self.structurebox.GetItems()
657                self.sizer1.Layout()
658                self.SetScrollbars(20,20,200,100)
659                for i in range(len(items)):
660                    if items[i]== str(name):
661                        self.structurebox.SetSelection(i)
662                        break
663                   
664        if hasattr(model ,"model1"):
665            class_name = model.model1.__class__
666            name = model.model1.name
667            self.formfactorbox.Clear()
668           
669            for k, list in self.model_list_box.iteritems():
670                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
671                    self.shape_rbutton.SetValue(True)
672                    ## fill the form factor list with new model
673                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
674                    items = self.formfactorbox.GetItems()
675                    ## set comboxbox to the selected item
676                    for i in range(len(items)):
677                        if items[i]== str(name):
678                            self.formfactorbox.SetSelection(i)
679                            break
680                    return
681                elif k == "Shape-Independent":
682                    self.shape_indep_rbutton.SetValue(True)
683                elif k == "Structure Factors":
684                     self.struct_rbutton.SetValue(True)
685                else:
686                    self.plugin_rbutton.SetValue(True)
687               
688                if class_name in list:
689                    ## fill the form factor list with new model
690                    self._populate_box(self.formfactorbox, list)
691                    items = self.formfactorbox.GetItems()
692                    ## set comboxbox to the selected item
693                    for i in range(len(items)):
694                        if items[i]== str(name):
695                            self.formfactorbox.SetSelection(i)
696                            break
697                    break
698        else:
699            ## Select the model from the combobox
700            class_name = model.__class__
701            name = model.name
702            self.formfactorbox.Clear()
703            items = self.formfactorbox.GetItems()
704   
705            for k, list in self.model_list_box.iteritems():
706                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
707                    self.shape_rbutton.SetValue(True)
708                    ## fill the form factor list with new model
709                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
710                    items = self.formfactorbox.GetItems()
711                    ## set comboxbox to the selected item
712                    for i in range(len(items)):
713                        if items[i]== str(name):
714                            self.formfactorbox.SetSelection(i)
715                            break
716                    return
717                elif k == "Shape-Independent":
718                    self.shape_indep_rbutton.SetValue(True)
719                elif k == "Structure Factors":
720                     self.struct_rbutton.SetValue(True)
721                else:
722                    self.plugin_rbutton.SetValue(True)
723                if class_name in list:
724                    ## fill the form factor list with new model
725                    self._populate_box(self.formfactorbox, list)
726                    items = self.formfactorbox.GetItems()
727                    ## set comboxbox to the selected item
728                    for i in range(len(items)):
729                        if items[i]== str(name):
730                            self.formfactorbox.SetSelection(i)
731                            break
732                    break
733                   
734       
735    def _draw_model(self):
736        """
737            Method to draw or refresh a plotted model.
738            The method will use the data member from the model page
739            to build a call to the fitting perspective manager.
740           
741            [Note to coder: This way future changes will be done in only one place.]
742        """
743        if self.model !=None:
744            self.manager.draw_model(self.model, data=self.data,
745                                    qmin=float(self.qmin_x), qmax=float(self.qmax_x),
746                                    qstep= float(self.num_points),
747                                    enable2D=self.enable2D) 
748       
749    def _set_model_sizer(self, sizer, title="", object=None):
750        """
751            Use lists to fill a sizer for model info
752        """
753       
754        sizer.Clear(True)
755        box_description= wx.StaticBox(self, -1,str(title))
756        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
757        #--------------------------------------------------------
758        self.shape_rbutton = wx.RadioButton(self, -1, 'Shapes', style=wx.RB_GROUP)
759        self.shape_indep_rbutton = wx.RadioButton(self, -1, "Shape-Independent")
760        self.struct_rbutton = wx.RadioButton(self, -1, "Structure Factor ")
761        self.plugin_rbutton = wx.RadioButton(self, -1, "Customized Models")
762        self.multip_cb = wx.CheckBox(self, -1,"P(Q)*S(Q)")
763       
764       
765       
766        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
767                            id= self.shape_rbutton.GetId() ) 
768        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
769                            id= self.shape_indep_rbutton.GetId() ) 
770        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
771                            id= self.struct_rbutton.GetId() ) 
772        self.Bind( wx.EVT_RADIOBUTTON, self._show_combox,
773                            id= self.plugin_rbutton.GetId() ) 
774        wx.EVT_CHECKBOX(self, self.multip_cb.GetId() , self._show_combox )             
775     
776        sizer_radiobutton = wx.GridSizer(3, 3,5, 5)
777        sizer_radiobutton.Add(self.shape_rbutton)
778        sizer_radiobutton.Add(self.shape_indep_rbutton)
779        sizer_radiobutton.Add(self.multip_cb)
780        sizer_radiobutton.Add(self.plugin_rbutton)
781        sizer_radiobutton.Add(self.struct_rbutton)
782       
783        sizer_selection = wx.BoxSizer(wx.HORIZONTAL)
784       
785        self.text1 = wx.StaticText( self,-1,"P(Q)" )
786        self.text2 = wx.StaticText( self,-1,"* S(Q)" )
787       
788        self.text2.Hide()
789       
790        self.formfactorbox = wx.ComboBox(self, -1,style=wx.CB_READONLY)
791        if self.model!=None:
792            self.formfactorbox.SetValue(self.model.name)
793           
794           
795        self.structurebox = wx.ComboBox(self, -1,style=wx.CB_READONLY)
796        wx.EVT_COMBOBOX(self.formfactorbox,-1, self._on_select_model)
797        wx.EVT_COMBOBOX(self.structurebox,-1, self._on_select_model)
798        self.structurebox.Hide()
799       
800        ## fill combox box
801        if len(self.model_list_box)>0:
802            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
803       
804        if len(self.model_list_box)>0:
805            self._populate_box( self.structurebox,
806                                self.model_list_box["Structure Factors"])
807       
808        ## check model type to show sizer
809        if self.model !=None:
810            self._set_model_sizer_selection( self.model )
811       
812        sizer_selection.Add(self.text1)
813        sizer_selection.Add((5,5))
814        sizer_selection.Add(self.formfactorbox)
815        sizer_selection.Add((5,5))
816        sizer_selection.Add(self.text2)
817        sizer_selection.Add((5,5))
818        sizer_selection.Add(self.structurebox)
819        sizer_selection.Add((5,5))
820       
821        boxsizer1.Add( sizer_radiobutton )
822        boxsizer1.Add( (20,20))
823        boxsizer1.Add( sizer_selection )
824        if object !=None:
825            boxsizer1.Add( (20,20))
826            boxsizer1.Add( object )
827        #--------------------------------------------------------
828        sizer.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
829        sizer.Layout()
830        self.SetScrollbars(20,20,200,100)
831       
832       
833    def _show_combox(self, event):
834        """
835            Show combox box associate with type of model selected
836        """
837        ## Don't want to populate combo box again if the event comes from check box
838        if self.shape_rbutton.GetValue()and\
839             event.GetEventObject()==self.shape_rbutton:
840            ##fill the combobox with form factor list
841            self.structurebox.Hide()
842            self.text2.Hide()
843            self.formfactorbox.Clear()
844            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
845           
846        if self.shape_indep_rbutton.GetValue()and\
847             event.GetEventObject()==self.shape_indep_rbutton:
848            ##fill the combobox with shape independent  factor list
849            self.structurebox.Hide()
850            self.text2.Hide()
851            self.formfactorbox.Clear()
852            self._populate_box( self.formfactorbox,
853                                self.model_list_box["Shape-Independent"])
854           
855        if self.struct_rbutton.GetValue() and\
856             event.GetEventObject()==self.struct_rbutton:
857            ##fill the combobox with structure factor list
858            self.structurebox.Hide()
859            self.text2.Hide()
860            self.formfactorbox.Clear()
861            self._populate_box( self.formfactorbox,
862                                self.model_list_box["Structure Factors"])
863           
864        if self.plugin_rbutton.GetValue()and\
865             event.GetEventObject()==self.plugin_rbutton:
866           
867            ##fill the combobox with form factor list
868            self.structurebox.Hide()
869            self.text2.Hide()
870            self.formfactorbox.Clear()
871            self._populate_box( self.formfactorbox,
872                                self.model_list_box["Customized Models"])
873       
874        if not self.multip_cb.GetValue(): 
875            self.structurebox.Hide()
876            self.text2.Hide()
877            n = self.formfactorbox.GetCurrentSelection()
878            model = self.formfactorbox.GetClientData(n)
879            self.model = model()
880        ## user check multiplication option       
881        else:
882            ##for this release
883            flag1= self.plugin_rbutton.GetValue()or self.struct_rbutton.GetValue()\
884                    or self.shape_indep_rbutton.GetValue()
885            flag2= False   
886             
887            n = self.formfactorbox.GetCurrentSelection()
888            form_factor = self.formfactorbox.GetClientData(n)   
889            ## selecting only multiplication model
890            if self.shape_rbutton.GetValue():
891               if not form_factor in  self.model_list_box["multiplication"]:
892                   flag2 = True
893            ## multiplication not available for structure factor
894            if flag1 or  flag2:
895                self.multip_cb.SetValue(False)
896                self.structurebox.Hide()
897                self.text2.Hide()
898                return
899            ## allow only some to have multiplication
900           
901            self.structurebox.Show(True)
902            self.text2.Show(True)
903            ## draw multiplication  model
904            n = self.structurebox.GetCurrentSelection()
905            struct_factor = self.structurebox.GetClientData(n)
906           
907            from sans.models.MultiplicationModel import MultiplicationModel
908            self.model= MultiplicationModel(form_factor(),struct_factor())
909
910        self._on_select_model(event=None)
911        self.sizer4_4.Clear()
912        self.sizer4.Layout()
913           
914       
915        self.set_scroll()
916   
917           
918    def _populate_box(self, combobox, list):
919        """
920            fill combox box with dict item
921            @param list: contains item to fill the combox
922            item must model class
923        """
924        for models in list:
925            model= models()
926            name = model.__class__.__name__
927            if models.__name__!="NoStructure":
928                if hasattr(model, "name"):
929                    name = model.name
930                combobox.Append(name,models)
931        try:
932
933            combobox.SetSelection(0)
934           
935        except:
936            pass
937   
938        return 0
939   
940   
941    def _on_select_model_helper(self): 
942        """
943             call back for model selection
944        """
945        ## reset dictionary containing reference to dispersion
946        self._disp_obj_dict = {}
947        self.disp_cb_dict ={}
948       
949        f_id = self.formfactorbox.GetCurrentSelection()
950        s_id = self.structurebox.GetCurrentSelection()
951        form_factor = self.formfactorbox.GetClientData( f_id )
952        struct_factor = self.structurebox.GetClientData( s_id )
953       
954        if not form_factor in  self.model_list_box["multiplication"]:
955            self.multip_cb.SetValue(False)
956            self.structurebox.Hide()
957            self.text2.Hide()
958            self.sizer4_4.Clear()
959            self.sizer4.Layout()
960           
961        if self.multip_cb.GetValue():
962            from sans.models.MultiplicationModel import MultiplicationModel
963            self.model= MultiplicationModel(form_factor(),struct_factor())
964           
965        else:
966            self.model= form_factor()
967       
968        ## post state to fit panel
969        self.save_current_state()
970       
971       
972    def _onparamEnter(self,event):
973        """
974            when enter value on panel redraw model according to changed
975        """
976        self._onparamEnter_helper()
977       
978       
979    def _check_value_enter(self, list, modified):
980        """
981            @param list: model parameter and panel info
982            each item of the list should be as follow:
983            item=[cb state, name, value, "+/-", error of fit, min, max , units]
984        """ 
985        is_modified =  modified
986        if len(list)==0:
987            return is_modified
988        for item in list:
989            try:
990                name = str(item[1])
991                if hasattr(self,"text2_3"):
992                    self.text2_3.Hide()
993                ## check model parameters range
994                ## check minimun value
995                param_min= None
996                param_max= None
997                if item[5]!= None:
998                    if format_number(item[5].GetValue())!="NaN":
999                        param_min = float(item[5].GetValue())
1000                   
1001                ## check maximum value
1002                if item[6]!= None:
1003                    if format_number(item[6].GetValue())!="NaN":
1004                        param_max = float(item[6].GetValue())
1005                       
1006                from sans.guiframe.utils import check_value
1007                if param_min != None and param_max !=None:
1008                    if not check_value(item[5], item[6]):
1009                        msg= "Wrong Fit range entered for parameter "
1010                        msg+= "name %s of model %s "%(name, self.model.name)
1011                        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
1012                if name in self.model.details.keys():   
1013                    self.model.details[name][1:]= param_min,param_max
1014               
1015                ## hide statictext +/-   
1016                if item[3]!=None:
1017                    item[3].Hide()
1018                ## hide textcrtl  for error after fit
1019                if item[4]!=None:
1020                    item[4].Clear()
1021                    item[4].Hide()
1022               
1023                value= float(item[2].GetValue())
1024                # If the value of the parameter has changed,
1025                # +update the model and set the is_modified flag
1026                if value != self.model.getParam(name):
1027                    self.model.setParam(name,value)
1028                    is_modified = True   
1029            except:
1030                msg= "Model Drawing  Error:wrong value entered : %s"% sys.exc_value
1031                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
1032                return 
1033       
1034        return is_modified
1035       
1036 
1037    def _set_dipers_Param(self, event):
1038        """
1039            Add more item to select user dispersity
1040        """
1041        if self.model == None:
1042            msg= " Select non - model value:%s !"%self.model
1043            wx.PostEvent(self.parent.parent, StatusEvent(status= msg))
1044            return 
1045        else:
1046           
1047            if self.enable_disp.GetValue():
1048                self.model_disp.Show(True)
1049                self.disp_box.Show(True)
1050                ## layout for model containing no dispersity parameters
1051                if len(self.disp_list)==0:
1052                    self._layout_sizer_noDipers() 
1053                else:
1054                    ## set gaussian sizer
1055                    self._set_sizer_gaussian() 
1056            else:
1057                self.model_disp.Hide()
1058                self.disp_box.Hide()
1059                self.sizer4_4.Clear(True)
1060                self._reset_dispersity()
1061               
1062         
1063            ## post state to fit panel
1064            self.save_current_state()
1065           
1066            self.sizer4.Layout()
1067            self.Layout()
1068            self.SetScrollbars(20,20,200,100)
1069           
1070       
1071    def _layout_sizer_noDipers(self):
1072        """
1073            Draw a sizer with no dispersity info
1074        """
1075        ix=0
1076        iy=1
1077        self.fittable_param=[]
1078        self.fixed_param=[]
1079        self.model_disp.Hide()
1080        self.disp_box.Hide()
1081        self.sizer4_4.Clear(True)
1082        model_disp = wx.StaticText(self, -1, 'No PolyDispersity for this model')
1083        self.sizer4_4.Add(model_disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1084        self.sizer4_4.Layout()
1085        self.sizer4.Layout()
1086       
1087        self.SetScrollbars(20,20,200,100)
1088        return 
1089   
1090           
1091    def _reset_dispersity(self):
1092        """
1093             put gaussian dispersity into current model
1094        """
1095        self.fittable_param=[]
1096        self.fixed_param=[]
1097       
1098        from sans.models.dispersion_models import GaussianDispersion
1099        if len(self.disp_cb_dict)==0:
1100            return 
1101       
1102        for p in self.disp_cb_dict:
1103            # The parameter was un-selected. Go back to Gaussian model (with 0 pts)
1104            disp_model = GaussianDispersion()
1105            # Store the object to make it persist outside the scope of this method
1106            #TODO: refactor model to clean this up?
1107            self._disp_obj_dict[p] = disp_model
1108            # Set the new model as the dispersion object for the selected parameter
1109            self.model.set_dispersion(p, disp_model)
1110            # Redraw the model
1111            self._draw_model()
1112           
1113           
1114    def _on_select_Disp(self,event):
1115        """
1116             allow selecting different dispersion
1117             self.disp_list should change type later .now only gaussian
1118        """
1119        dispersity  =event.GetClientData()
1120        name= dispersity.__name__
1121        if name == "GaussianDispersion":
1122            self._set_sizer_gaussian()
1123           
1124        if  name=="ArrayDispersion":
1125            self._set_sizer_arraydispersion()
1126       
1127           
1128   
1129    def _set_sizer_arraydispersion(self):
1130        """
1131            draw sizer with array dispersity  parameters
1132        """
1133        self.sizer4_4.Clear(True) 
1134        ix=0
1135        iy=1     
1136        disp1 = wx.StaticText(self, -1, 'Array Dispersion')
1137        self.sizer4_4.Add(disp1,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1138       
1139        # Look for model parameters to which we can apply an ArrayDispersion model
1140        # Add a check box for each parameter.
1141        self.disp_cb_dict = {}
1142        for p in self.model.dispersion.keys():
1143            ix+=1 
1144            self.disp_cb_dict[p] = wx.CheckBox(self, -1, p, (10, 10))
1145           
1146            wx.EVT_CHECKBOX(self, self.disp_cb_dict[p].GetId(), self.select_disp_angle)
1147            self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1148       
1149        ix =0
1150        iy +=1 
1151        self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)       
1152        self.sizer4_4.Layout()
1153        self.sizer4.Layout()
1154        self.SetScrollbars(20,20,200,100)
1155       
1156       
1157    def _set_range_sizer(self, title, object1=None,object=None):
1158        """
1159            Fill the
1160        """
1161        self.sizer5.Clear(True)
1162        box_description= wx.StaticBox(self, -1,str(title))
1163        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
1164        #--------------------------------------------------------------
1165        self.qmin    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
1166        self.qmin.SetValue(format_number(self.qmin_x))
1167        self.qmin.SetToolTipString("Minimun value of Q in linear scale.")
1168        self.qmin.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
1169        self.qmin.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
1170        self.qmin.Bind(wx.EVT_TEXT_ENTER, self._onparamEnter)
1171     
1172        self.qmax    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
1173        self.qmax.SetValue(format_number(self.qmax_x))
1174        self.qmax.SetToolTipString("Maximum value of Q in linear scale.")
1175        self.qmax.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
1176        self.qmax.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
1177        self.qmax.Bind(wx.EVT_TEXT_ENTER, self._onparamEnter)
1178     
1179        sizer_horizontal=wx.BoxSizer(wx.HORIZONTAL)
1180        sizer= wx.GridSizer(3, 3,5, 5)
1181       
1182        sizer.Add((5,5))
1183        sizer.Add(wx.StaticText(self, -1, 'Min'))
1184        sizer.Add(wx.StaticText(self, -1, 'Max'))
1185        sizer.Add(wx.StaticText(self, -1, 'Q range'))
1186             
1187        sizer.Add(self.qmin)
1188        sizer.Add(self.qmax)
1189        sizer_horizontal.Add(sizer)
1190        if object!=None:
1191            sizer_horizontal.Add(object)
1192       
1193        if object1!=None:
1194           boxsizer1.Add(object1) 
1195           boxsizer1.Add((10,10))
1196        boxsizer1.Add(sizer_horizontal)
1197        ## save state
1198        self.save_current_state()
1199        #----------------------------------------------------------------
1200        self.sizer5.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
1201        self.sizer5.Layout()
1202        self.Layout()
1203        self.SetScrollbars(20,20,200,100)
1204   
1205   
1206    def _fill_save_sizer(self):
1207        """
1208            Draw the layout for saving option
1209        """
1210        self.sizer6.Clear(True)
1211        box_description= wx.StaticBox(self, -1,"Save Options")
1212        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
1213        sizer_save = wx.BoxSizer(wx.HORIZONTAL)
1214       
1215        self.btSave = wx.Button(self,wx.NewId(),'Save')
1216        self.btSave.Bind(wx.EVT_BUTTON, self.onSave,id= self.btSave.GetId())
1217        self.btSave.SetToolTipString("Save current state")
1218         
1219        sizer_save.Add((20,20),0, wx.LEFT|wx.RIGHT|wx.EXPAND,120)       
1220        sizer_save.Add(self.btSave)     
1221       
1222        boxsizer1.Add(sizer_save)
1223        self.sizer6.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
1224        self.sizer6.Layout()
1225        self.SetScrollbars(20,20,200,100)
1226       
1227       
1228               
Note: See TracBrowser for help on using the repository browser.