source: sasview/sansview/perspectives/fitting/fitpage2D.py @ 2dbb681

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

change window title

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