source: sasview/sansview/perspectives/fitting/fitpage1D.py @ bcd6d51

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

working on data2D panel

  • Property mode set to 100644
File size: 23.1 KB
Line 
1import sys
2import wx
3import wx.lib
4import numpy,math
5import copy
6
7from sans.guicomm.events import StatusEvent   
8(ModelEventbox, EVT_MODEL_BOX) = wx.lib.newevent.NewEvent()
9_BOX_WIDTH = 80
10
11def format_number(value, high=False):
12    """
13        Return a float in a standardized, human-readable formatted string
14    """
15    try: 
16        value = float(value)
17    except:
18        print "returning 0"
19        return "0"
20   
21    if high:
22        return "%-6.4g" % value
23    else:
24        return "%-5.3g" % value
25
26   
27class FitPage1D(wx.Panel):
28    """
29        FitPanel class contains fields allowing to display results when
30        fitting  a model and one data
31        @note: For Fit to be performed the user should check at least one parameter
32        on fit Panel window.
33 
34    """
35    ## Internal name for the AUI manager
36    window_name = "Fit page"
37    ## Title to appear on top of the window
38    window_caption = "Fit Page"
39   
40   
41    def __init__(self, parent, *args, **kwargs):
42        wx.Panel.__init__(self, parent, *args, **kwargs)
43        """
44            Initialization of the Panel
45        """
46        self.manager = None
47        self.parent  = parent
48        self.event_owner=None
49        #panel interface
50        self.vbox  = wx.BoxSizer(wx.VERTICAL)
51        self.sizer4 = wx.GridBagSizer(5,5)
52        self.sizer3 = wx.GridBagSizer(5,5)
53        self.sizer2 = wx.GridBagSizer(5,5)
54        self.sizer1 = wx.GridBagSizer(5,5)
55        self.DataSource      = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
56        self.DataSource.SetToolTipString("name of data to fit")
57        self.modelbox = wx.ComboBox(self, -1)
58        id = wx.NewId()
59        self.btFit =wx.Button(self,id,'Fit')
60        self.btFit.Bind(wx.EVT_BUTTON, self.onFit,id=id)
61        self.btFit.SetToolTipString("Perform fit.")
62        self.vbox.Add(self.sizer3)
63        self.vbox.Add(self.sizer2)
64        self.vbox.Add(self.sizer4)
65        self.vbox.Add(self.sizer1)
66       
67        id = wx.NewId()
68        self.btClose =wx.Button(self,id,'Close')
69        self.btClose.Bind(wx.EVT_BUTTON, self.onClose,id=id)
70        self.btClose.SetToolTipString("Close page.")
71        ix = 0
72        iy = 1
73        self.sizer3.Add(wx.StaticText(self, -1, 'Data Source'),(iy,ix),\
74                 (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
75        ix += 1
76        self.sizer3.Add(self.DataSource,(iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
77        ix += 1
78        self.sizer3.Add((20,20),(iy,ix),(1,1),wx.RIGHT|wx.EXPAND|wx.ADJUST_MINSIZE,0)
79        ix = 0
80        iy += 1
81        self.sizer3.Add(wx.StaticText(self,-1,'Model'),(iy,ix),(1,1)\
82                  , wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
83        ix += 1
84        self.sizer3.Add(self.modelbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
85        ix = 1
86        iy = 1
87        self.text4_1 = wx.StaticText(self, -1, 'Min')
88        self.sizer4.Add(self.text4_1,(iy, ix),(1,1),\
89                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
90        self.text4_1.Hide()
91        ix += 2
92        self.text4_2 = wx.StaticText(self, -1, 'Max')
93        self.sizer4.Add(self.text4_2,(iy, ix),(1,1),\
94                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
95        self.text4_2.Hide()
96        ix = 0
97        iy += 1
98        #set maximum range for x in linear scale
99        self.text4_3 = wx.StaticText(self, -1, 'Maximum Data\n Range (Linear)', style=wx.ALIGN_LEFT)
100        self.sizer4.Add(self.text4_3,(iy,ix),(1,1),\
101                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
102        self.text4_3.Hide()
103        ix += 1
104        self.xmin    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
105        self.xmin.SetToolTipString("Minimun value of x in linear scale.")
106        self.sizer4.Add(self.xmin,(iy, ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
107        self.xmin.Bind(wx.EVT_KILL_FOCUS, self._onTextEnter)
108        self.xmin.Bind(wx.EVT_TEXT_ENTER, self._onTextEnter)
109        self.xmin.Hide()
110        ix += 2
111        self.xmax    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
112        self.xmax.SetToolTipString("Maximum value of x in linear scale.")
113        self.sizer4.Add(self.xmax,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
114        self.xmax.Bind(wx.EVT_KILL_FOCUS, self._onTextEnter)
115        self.xmax.Bind(wx.EVT_TEXT_ENTER, self._onTextEnter)
116        self.xmax.Hide()
117        #Set chisqr  result into TextCtrl
118        ix = 0
119        iy = 1
120        self.text1_1 = wx.StaticText(self, -1, 'Chi2/dof', style=wx.ALIGN_LEFT)
121        self.sizer1.Add(self.text1_1,(iy,ix),(1,1),\
122                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
123        ix += 1
124        self.tcChi    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
125        self.tcChi.SetToolTipString("Chi^2 over degrees of freedom.")
126        self.sizer1.Add(self.tcChi,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
127        ix +=2
128        self.sizer1.Add(self.btFit,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
129        iy+= 1
130        ix = 3
131        self.sizer1.Add( self.btClose,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
132        # contains link between  model ,all its parameters, and panel organization
133        self.parameters=[]
134        #contains link between a model and selected parameters to fit
135        self.param_toFit=[]
136        # model on which the fit would be performed
137        self.model=None
138        # preview selected model name
139        self.prevmodel_name=None
140        # flag to check if the user has selected a new model in the combox box
141        self.model_hasChanged=False
142       
143        #dictionary of model name and model class
144        self.model_list_box={}
145        #  comparison between 2 group_id for checking data changes
146        self.prev_group_id= None
147       
148        self.data=None
149        self.vbox.Layout()
150        self.vbox.Fit(self) 
151        self.SetSizer(self.vbox)
152        self.Centre()
153       
154       
155    def set_owner(self,owner):
156        """
157            set owner of fitpage
158            @param owner: the class responsible of plotting
159        """
160        self.event_owner=owner   
161   
162 
163    def set_manager(self, manager):
164        """
165             set panel manager
166             @param manager: instance of plugin fitting
167        """
168        self.manager = manager
169 
170         
171    def _DataNameEnter(self):
172        """
173            reset the panel when a new data is selected
174        """
175        if len(self.parameters )>0:
176            for item in self.parameters:
177                item[0].SetValue(False)
178                wx.EVT_CHECKBOX(self, item[0].GetId(), self.select_param)
179                item[2].Hide()
180                item[3].Clear()
181                item[3].Hide()
182                self.xmax.Disable()
183                self.xmin.Disable()
184                self.text1_1.Hide()
185                self.tcChi.Clear()
186                self.vbox.Layout() 
187                self.GrandParent.GetSizer().Layout()
188               
189 
190       
191    def onClose(self,event):
192        """ close the page associated with this panel"""
193        self.GrandParent.onClose()
194       
195       
196    def compute_chisqr(self):
197        """ @param fn: function that return model value
198            @return residuals
199        """
200        flag=self.checkFitRange()
201        if flag== True:
202            try:
203                qmin = float(self.xmin.GetValue())
204                qmax = float(self.xmax.GetValue())
205                x,y,dy = [numpy.asarray(v) for v in (self.data.x,self.data.y,self.data.dy)]
206                if qmin==None and qmax==None: 
207                    fx =numpy.asarray([self.model.run(v) for v in x])
208                    res=(y - fx)/dy
209                else:
210                    idx = (x>= qmin) & (x <=qmax)
211                    fx = numpy.asarray([self.model.run(item)for item in x[idx ]])
212                    res= (y[idx] - fx)/dy[idx] 
213               
214               
215                sum=0
216                for item in res:
217                    if numpy.isfinite(item):
218                        sum +=item
219                self.tcChi.SetValue(format_number(math.fabs(sum)))
220            except:
221                wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
222                            "Chisqr cannot be compute: %s"% sys.exc_value))
223           
224           
225    def onFit(self,event):
226        """ signal for fitting"""
227         
228        flag=self.checkFitRange()
229        self.set_manager(self.manager)
230     
231        qmin=float(self.xmin.GetValue())
232        qmax =float( self.xmax.GetValue())
233        if len(self.param_toFit) >0 and flag==True:
234            self.manager.schedule_for_fit( value=1,fitproblem =None) 
235            self.manager._on_single_fit(qmin=qmin,qmax=qmax)
236        else:
237              wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
238                            "Select at least on parameter to fit "))
239    def populate_box(self, dict):
240        """
241            Populate each combox box of each page
242            @param page: the page to populate
243        """
244        id=0
245        self.model_list_box=dict
246        list_name=[]
247        for item in  self.model_list_box.itervalues():
248            name = item.__name__
249            if hasattr(item, "name"):
250                name = item.name
251            list_name.append(name)
252        list_name.sort()   
253        for name in list_name:
254            self.modelbox.Insert(name,int(id))
255            id+=1
256        wx.EVT_COMBOBOX(self.modelbox,-1, self._on_select_model) 
257        return 0
258   
259   
260    def _on_select_model(self,event):
261        """
262            react when a model is selected from page's combo box
263            post an event to its owner to draw an appropriate theory
264        """
265       
266        for item in self.model_list_box.itervalues():
267            name = item.__name__
268            if hasattr(item, "name"):
269                name = item.name
270            #print "fitpage: _on_select_model model name",name ,event.GetString()
271            if name ==event.GetString():
272                try:
273                    evt = ModelEventbox(model=item(),name=name)
274                    wx.PostEvent(self.event_owner, evt)
275                except:
276                    raise #ValueError,"model.name is not equal to model class name"
277                break
278   
279    def _onTextEnter(self,event):
280        """
281            set a flag to determine if the fitting range entered by the user is valid
282        """
283     
284        try:
285            flag=self.checkFitRange()
286            if flag==True and self.model!=None:
287                print"fit page",self.xmin.GetValue(),self.xmax.GetValue()
288                self.manager.redraw_model(float(self.xmin.GetValue())\
289                                               ,float(self.xmax.GetValue()))
290        except:
291
292            wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
293                            "Drawing  Error:wrong value entered %s"% sys.exc_value))
294       
295    def checkFitRange(self):
296        """
297            Check the validity of fitting range
298            @note: xmin should always be less than xmax or else each control box
299            background is colored in pink.
300        """
301       
302        flag = True
303        valueMin = self.xmin.GetValue()
304        valueMax = self.xmax.GetValue()
305        # Check for possible values entered
306        print "fitpage: checkfitrange:",valueMin,valueMax
307        try:
308            if (float(valueMax)> float(valueMin)):
309                self.xmax.SetBackgroundColour(wx.WHITE)
310                self.xmin.SetBackgroundColour(wx.WHITE)
311            else:
312                flag = False
313                self.xmin.SetBackgroundColour("pink")
314                self.xmax.SetBackgroundColour("pink")     
315        except:
316            flag = False
317            self.xmin.SetBackgroundColour("pink")
318            self.xmax.SetBackgroundColour("pink")
319           
320        self.xmin.Refresh()
321        self.xmax.Refresh()
322        return flag
323   
324   
325                   
326    def set_data_name(self,dataset):
327        """
328            set data's name.if data has changed reset the panel and xmin and xmax
329            @param name: data 's name
330            @attention:  still  haven't find a better way to display Q name and unit
331            for xmin and xmax range sizer
332        """
333       
334        if self.prev_group_id !=dataset.group_id:
335            self._DataNameEnter()
336        self.data = dataset
337        self.prev_group_id=dataset.group_id
338        #Displaying Data information
339        self.DataSource.SetValue(str(dataset.name))
340        self._xaxis,self._xunit=dataset.get_xaxis()
341        self.text4_3.SetLabel(self._xaxis+"["+self._xunit+"]")
342        self.text4_1.Show()
343        self.text4_2.Show()
344        self.text4_3.Show()
345       
346        self.xmin.SetValue(format_number(min(dataset.x)))
347        self.xmin.Show()
348        self.xmax.SetValue(format_number(max(dataset.x)))
349        self.xmax.Show()
350       
351        if ((len(self.param_toFit ) >0) and self.DataSource.GetValue()and \
352            self.modelbox.GetValue() and (self.model_hasChanged ==False)):
353            self.xmin.Enable()
354            self.xmax.Enable()
355        else:
356            self.xmin.Disable()
357            self.xmax.Disable()
358           
359        self.vbox.Layout()
360        self.GrandParent.GetSizer().Layout()
361       
362       
363    def set_model_name(self,name):
364        """
365            set model name. set also self.model_hasChanged to true is the model
366            type has changed or false if it didn't
367            @param name: model 's name
368        """
369        self.model_hasChanged=False
370        if (name != self.prevmodel_name):
371            self.model_hasChanged=True
372        self.tcChi.Clear()
373        #self.modelbox.SetValue(str(name))
374        self.prevmodel_name=self.modelbox.GetValue()
375       
376           
377    def get_model_box(self): 
378        """ return reference to combox box self.model"""
379        return self.modelbox
380
381   
382    def get_param_list(self):
383        """
384            @return self.param_toFit: list containing  references to TextCtrl
385            checked.Theses TextCtrl will allow reference to parameters to fit.
386            @raise: if return an empty list of parameter fit will nnote work
387            properly so raise ValueError,"missing parameter to fit"
388        """
389        if self.param_toFit !=[]:
390            return self.param_toFit
391        else:
392            raise ValueError,"missing parameter to fit"
393       
394       
395    def set_panel(self,model):
396        """
397            Build the panel from the model content
398            @param model: the model selected in combo box for fitting purpose
399        """
400       
401        self.sizer2.Clear(True)
402        self.parameters = []
403        self.param_toFit=[]
404        self.model = model
405        keys = self.model.getParamList()
406        keys.sort()
407        iy = 1
408        ix = 0
409        self.cb1 = wx.CheckBox(self, -1,'Parameters', (10, 10))
410        wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param)
411        self.sizer2.Add(self.cb1,(iy, ix),(1,1),\
412                          wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
413        ix +=1
414        self.text2_2 = wx.StaticText(self, -1, 'Values')
415        self.sizer2.Add(self.text2_2,(iy, ix),(1,1),\
416                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
417        ix +=2
418        self.text2_3 = wx.StaticText(self, -1, 'Errors')
419        self.sizer2.Add(self.text2_3,(iy, ix),(1,1),\
420                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
421        self.text2_3.Hide() 
422        ix +=1
423        self.text2_4 = wx.StaticText(self, -1, 'Units')
424        self.sizer2.Add(self.text2_4,(iy, ix),(1,1),\
425                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
426        self.text2_4.Hide()
427        for item in keys:
428            iy += 1
429            ix = 0
430
431            cb = wx.CheckBox(self, -1, item, (10, 10))
432            cb.SetValue(False)
433            self.sizer2.Add( cb,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
434            wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
435           
436            ix += 1
437            value= self.model.getParam(item)
438            ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
439            ctl1.SetValue(str (format_number(value)))
440            ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
441            ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
442            self.sizer2.Add(ctl1, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
443            ix += 1
444            text2=wx.StaticText(self, -1, '+/-')
445            self.sizer2.Add(text2,(iy, ix),(1,1),\
446                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
447            text2.Hide() 
448            ix += 1
449            ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
450            self.sizer2.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
451            ctl2.Hide()
452            ix +=1
453           
454            # Units
455 
456            try:
457                units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
458            except:
459                units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
460             
461            self.sizer2.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
462            #save data
463            self.parameters.append([cb,ctl1,text2,ctl2])
464        #Display units text on panel
465        for item in keys:   
466            if self.model.details[item][0]!='':
467                self.text2_4.Show()
468                break
469            else:
470                self.text2_4.Hide()
471        #Disable or enable fit button
472        if (self.modelbox.GetValue() and self.DataSource.GetValue()):
473            if not (len(self.param_toFit ) >0):
474                self.xmin.Disable()
475                self.xmax.Disable()
476            else:
477                self.xmin.Enable()
478                self.xmax.Enable()
479        else:
480            self.xmin.Disable()
481            self.xmax.Disable()
482       
483        self.compute_chisqr()
484        self.vbox.Layout()
485        self.GrandParent.GetSizer().Layout()
486       
487       
488       
489    def _onparamEnter(self,event):
490        """
491            when enter value on panel redraw model according to changed
492        """
493        self.set_model_parameter()
494        self.compute_chisqr()
495     
496    def set_model_parameter(self):
497        """
498            this method redraws the model according to parameters values changes
499            and the reset model according to paramaters changes
500        """
501        if len(self.parameters) !=0 and self.model !=None:
502            for item in self.parameters:
503                try:
504                     name=str(item[0].GetLabelText())
505                     value= float(item[1].GetValue())
506                     self.model.setParam(name,value) 
507                except:
508                     wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
509                            "Drawing  Error:wrong value entered : %s"% sys.exc_value))
510            self.manager.redraw_model(float(self.xmin.GetValue())\
511                                               ,float(self.xmax.GetValue()))     
512                     
513    def select_all_param(self,event): 
514        """
515             set to true or false all checkBox given the main checkbox value cb1
516        """
517        self.param_toFit=[]
518        if  self.parameters !=[]:
519            if  self.cb1.GetValue()==True:
520                for item in self.parameters:
521                    item[0].SetValue(True)
522                    list= [item[0],item[1],item[2],item[3]]
523                    self.param_toFit.append(list )
524                if (self.modelbox.GetValue() and self.DataSource.GetValue()):
525                    if not (len(self.param_toFit ) >0):
526                        self.xmin.Disable()
527                        self.xmax.Disable()
528                    else:
529                        self.xmin.Enable()
530                        self.xmax.Enable()
531            else:
532                for item in self.parameters:
533                    item[0].SetValue(False)
534                self.param_toFit=[]
535             
536                self.xmin.Disable()
537                self.xmax.Disable()
538               
539               
540    def select_param(self,event):
541        """
542            Select TextCtrl  checked for fitting purpose and stores them
543            in  self.param_toFit=[] list
544        """
545        self.param_toFit=[]
546        for item in self.parameters:
547            if item[0].GetValue()==True:
548                list= [item[0],item[1],item[2],item[3]]
549                self.param_toFit.append(list ) 
550            else:
551                if item in self.param_toFit:
552                    self.param_toFit.remove(item)
553        if len(self.parameters)==len(self.param_toFit):
554            self.cb1.SetValue(True)
555        else:
556            self.cb1.SetValue(False)
557        if (self.modelbox.GetValue() and self.DataSource.GetValue()):
558            if not (len(self.param_toFit ) >0):
559                self.xmin.Disable()
560                self.xmax.Disable()
561            else:
562                self.xmin.Enable()
563                self.xmax.Enable()
564        else:
565            self.xmin.Disable()
566            self.xmax.Disable()
567   
568       
569 
570    def onsetValues(self,chisqr, out,cov):
571        """
572            Build the panel from the fit result
573            @param chisqr:Value of the goodness of fit metric
574            @param out:list of parameter with the best value found during fitting
575            @param cov:Covariance matrix
576       
577        """
578        #print "fitting : onsetvalues out",out
579        self.tcChi.Clear()
580        self.tcChi.SetValue(format_number(chisqr))
581        params = {}
582        is_modified = False
583        has_error = False
584        if out.__class__==numpy.float64:
585            self.param_toFit[0][1].SetValue(format_number(out))
586            self.param_toFit[0][1].Refresh()
587            if cov !=None :
588                self.text2_3.Show()
589                self.param_toFit[0][2].Show()
590                self.param_toFit[0][3].Clear()
591                self.param_toFit[0][3].SetValue(format_number(cov[0]))
592                self.param_toFit[0][3].Show()
593        #out is a list : set parameters and errors in TextCtrl
594        else:
595            i=0
596            #print "fitpage: list param  model",list
597            #for item in self.param_toFit:
598            #    print "fitpage: list display",item[0].GetLabelText()
599            for item in self.param_toFit:
600                if( out != None ) and len(out)<=len(self.param_toFit)and i < len(out):
601                    #item[1].SetValue(format_number(out[i]))
602                    item[1].SetValue(format_number(self.model.getParam(item[0].GetLabelText())))
603                    item[1].Refresh() 
604                if (cov !=None)and len(cov)<=len(self.param_toFit)and i < len(cov):
605                    self.text2_3.Show() 
606                    item[2].Show()
607                    item[3].Clear()
608                    item[3].SetValue(format_number(cov[i]))
609                    item[3].Show()   
610                i+=1
611       
612        self.vbox.Layout()
613        self.GrandParent.GetSizer().Layout()
614   
Note: See TracBrowser for help on using the repository browser.