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

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

2 d fit working better still not plotting all data

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