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