source: sasview/sansview/perspectives/fitting/fitpage2D.py @ b3328d8

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