source: sasview/guitools/fitDialog.py @ ac9c465

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 ac9c465 was 052a66bc, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

Bug fixing

  • Property mode set to 100644
File size: 18.4 KB
Line 
1#!/usr/bin/python
2
3# fitDialog.py
4
5import wx
6from PlotPanel import PlotPanel
7from plottables import Theory1D
8import math,pylab,fittings
9import transform
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 LinearFit(wx.Dialog):
28    def __init__(self, parent, plottable, push_data,transform, id, title):
29        wx.Dialog.__init__(self, parent, id, title, size=(400, 380))
30
31        """
32            Dialog window pops- up when select Linear fit on Context menu
33            Displays fitting parameters
34        """
35        self.parent = parent
36        self.transform = transform
37       
38        #dialog panel self call function to plot the fitting function
39        self.push_data = push_data
40        #dialog self plottable
41        self.plottable = plottable
42       
43        # Receive transformations of x and y
44        self.xLabel,self.yLabel,self.Avalue,self.Bvalue,\
45        self.ErrAvalue,self.ErrBvalue,self.Chivalue= self.transform()
46       
47        #Dialog interface
48        vbox  = wx.BoxSizer(wx.VERTICAL)
49        sizer = wx.GridBagSizer(5,5)
50       
51        _BOX_WIDTH = 100
52 
53        self.tcA      = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
54        self.tcA.SetToolTipString("Fit value for the slope parameter.")
55        self.tcErrA   = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
56        self.tcErrA.SetToolTipString("Error on the slope parameter.")
57        self.tcB      = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
58        self.tcA.SetToolTipString("Fit value for the constant parameter.")
59        self.tcErrB   = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
60        self.tcErrB.SetToolTipString("Error on the constant parameter.")
61        self.tcChi    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
62        self.tcChi.SetToolTipString("Chi^2 over degrees of freedom.")
63        self.xminFit  = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
64        self.xminFit.SetToolTipString("Enter the minimum value on the x-axis to be included in the fit.")
65        self.xmaxFit  = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
66        self.xmaxFit.SetToolTipString("Enter the maximum value on the x-axis to be included in the fit.")
67        self.xminTransFit = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
68        self.xminTransFit.SetToolTipString("Minimum value on the x-axis for the plotted data.")
69        self.xmaxTransFit = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
70        self.xmaxTransFit.SetToolTipString("Maximum value on the x-axis for the plotted data.")
71        self.initXmin = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
72        self.initXmin.SetToolTipString("Minimum value available on the x-axis for the plotted data.")
73        self.initXmax = wx.TextCtrl(self,-1,size=(_BOX_WIDTH,20))
74        self.initXmax.SetToolTipString("Maximum value available on the x-axis for the plotted data.")
75
76        # Make the info box not editable
77        #_BACKGROUND_COLOR = '#ffdf85'
78        _BACKGROUND_COLOR = self.GetBackgroundColour()
79        self.xminTransFit.SetEditable(False)
80        self.xminTransFit.SetBackgroundColour(_BACKGROUND_COLOR)
81        self.xmaxTransFit.SetEditable(False)
82        self.xmaxTransFit.SetBackgroundColour(_BACKGROUND_COLOR)
83        self.initXmin.SetEditable(False)
84        self.initXmin.SetBackgroundColour(_BACKGROUND_COLOR)
85        self.initXmax.SetEditable(False)
86        self.initXmax.SetBackgroundColour(_BACKGROUND_COLOR)
87       
88       
89        # Buttons on the bottom
90        self.static_line_1 = wx.StaticLine(self, -1)
91        self.btFit =wx.Button(self,-1,'Fit')
92        self.btFit.Bind(wx.EVT_BUTTON, self._onFit)
93        self.btFit.SetToolTipString("Perform fit.")
94        self.btClose =wx.Button(self, wx.ID_CANCEL,'Close')
95       
96        # Intro
97        explanation  = "Perform fit for y(x) = Ax + B"
98       
99        vbox.Add(sizer)
100       
101        ix = 0
102        iy = 1
103        sizer.Add(wx.StaticText(self, -1, explanation),(iy, ix),\
104                 (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
105        iy += 2
106        sizer.Add(wx.StaticText(self, -1, 'Parameter A'),(iy, ix),\
107                 (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
108        ix += 1
109        sizer.Add(self.tcA,(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
110        ix += 1
111        sizer.Add(wx.StaticText(self, -1, '+/-'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
112        ix += 1
113        sizer.Add(self.tcErrA, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
114        iy += 1
115        ix = 0
116        sizer.Add(wx.StaticText(self, -1, 'Parameter B'),(iy, ix),(1,1),\
117                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
118        ix += 1
119        sizer.Add(self.tcB, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
120        ix += 1
121        sizer.Add(wx.StaticText(self, -1, '+/-'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
122        ix += 1
123        sizer.Add(self.tcErrB, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
124        iy += 1
125        ix = 0
126        sizer.Add(wx.StaticText(self, -1, 'Chi2/dof'),(iy, ix),(1,1),\
127                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
128        ix += 1
129        sizer.Add(self.tcChi, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
130        iy += 2
131        ix = 1
132        sizer.Add(wx.StaticText(self, -1, 'Min'),(iy, ix),(1,1),\
133                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
134        ix += 2
135        sizer.Add(wx.StaticText(self, -1, 'Max'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
136        iy += 1
137        ix = 0
138        sizer.Add(wx.StaticText(self, -1, 'Maximum range'),(iy, ix),(1,1),\
139                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
140        ix +=1
141        sizer.Add(self.initXmin, (iy, ix),(1,1),\
142                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
143        ix += 2
144        sizer.Add(self.initXmax, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
145       
146        iy += 1
147        ix = 0
148        sizer.Add(wx.StaticText(self, -1, 'Fit range of '+self.xLabel),(iy, ix),(1,1),\
149                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
150        ix += 1
151        sizer.Add(self.xminTransFit, (iy, ix),(1,1),\
152                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
153        ix += 2
154        sizer.Add(self.xmaxTransFit, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
155     
156        iy += 1
157        ix = 0
158        sizer.Add(wx.StaticText(self, -1, 'Fit range of x'),(iy, ix),(1,1),\
159                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
160        ix += 1
161        sizer.Add(self.xminFit, (iy, ix),(1,1),\
162                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
163        ix += 2
164        sizer.Add(self.xmaxFit, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
165        iy += 1
166        ix = 1
167       
168        vbox.Add(self.static_line_1, 0, wx.EXPAND, 0)
169       
170        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
171        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
172        sizer_button.Add(self.btFit, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
173        sizer_button.Add(self.btClose, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)       
174        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
175       
176       
177       
178        sizer.Add(self.btFit, (iy, ix),(1,1), wx.LEFT|wx.ADJUST_MINSIZE, 0)
179       
180       
181        #panel.SetSizer(sizer)
182        self.SetSizer(vbox)
183        self.Centre()
184       
185        # Receives the type of model for the fitting
186        from LineModel import LineModel
187        self.model  = LineModel()
188         
189        #Display the fittings values
190        self.default_A = self.model.getParam('A') 
191        self.default_B = self.model.getParam('B') 
192        self.cstA = fittings.Parameter(self.model, 'A', self.default_A)
193        self.cstB  = fittings.Parameter(self.model, 'B', self.default_B)
194       
195        # Set default value of parameter in fit dialog
196       
197        if self.Avalue==None:
198            self.tcA.SetLabel(format_number(self.default_A))
199        else :
200            self.tcA.SetLabel(format_number(self.Avalue))
201        if self.Bvalue==None:
202            self.tcB.SetLabel(format_number(self.default_B))
203        else:
204            self.tcB.SetLabel(format_number(self.Bvalue))
205        if self.ErrAvalue==None:
206            self.tcErrA.SetLabel(format_number(0.0))
207        else:
208            self.tcErrA.SetLabel(format_number(self.ErrAvalue))
209        if self.ErrBvalue==None:
210            self.tcErrB.SetLabel(format_number(0.0))
211        else:
212            self.tcErrB.SetLabel(format_number(self.ErrBvalue))
213        if self.Chivalue==None:
214            self.tcChi.SetLabel(format_number(0.0))
215        else:
216            self.tcChi.SetLabel(format_number(self.Chivalue))
217        if self.plottable.x !=[]:
218            self.mini =min(self.plottable.x)
219            self.maxi =max(self.plottable.x)
220            #store the values of View in self.x,self.y,self.dx,self.dy
221            self.x,self.y,self.dx,self.dy= self.plottable.returnValuesOfView()
222           
223           
224            self.xminTransFit.SetLabel(format_number(min(self.x)))
225            self.xmaxTransFit.SetLabel(format_number(max(self.x)))
226           
227            self.initXmin.SetValue(format_number(self.mini))
228            self.initXmax.SetValue(format_number(self.maxi))
229           
230            self.xminFit.SetLabel(format_number(self.mini))
231            self.xmaxFit.SetLabel(format_number(self.maxi))
232       
233     
234    def _onFit(self ,event):
235        """
236            Performs the fit. Receive an event when clicking on the button Fit.Computes chisqr ,
237            A and B parameters of the best linear fit y=Ax +B
238            Push a plottable to
239        """
240        tempx=[]
241        tempy=[]
242        tempdy = []
243       
244       
245       
246       
247        # Check if View contains a x array .we online fit when x exits
248        # makes transformation for y as a line to fit
249        if self.x != []: 
250           
251               
252            if(self.checkFitValues(self.xminFit) == True):
253                #Check if the field of Fit Dialog contain values and use the x max and min of the user
254                xmin,xmax = self._checkVal(self.xminFit.GetValue(),self.xmaxFit.GetValue())
255               
256                xminView=self.floatTransform(xmin)
257                xmaxView=self.floatTransform(xmax)
258                if (self.xLabel=="log10(x)"):
259                    self.xminTransFit.SetValue(format_number(math.log10(xminView)))
260                    self.xmaxTransFit.SetValue(format_number(math.log10(xmaxView)))
261                else:
262                    self.xminTransFit.SetValue(format_number(xminView))
263                    self.xmaxTransFit.SetValue(format_number(xmaxView))
264                # Store the transformed values of view x, y,dy in variables  before the fit
265                if  self.yLabel.lower() == "log10(y)":
266                    if (self.xLabel.lower() == "log10(x)"):
267                        for i in range(len(self.x)):
268                            if self.x[i]>= math.log10(xmin):
269                                tempy.append(math.log10(self.y[i])) 
270                                tempdy.append(transform.errToLogX(self.y[i],0,self.dy[i],0))
271                    else:
272                        for i in range(len(self.y)):
273                            tempy.append(math.log10(self.y[i])) 
274                            tempdy.append(transform.errToLogX(self.y[i],0,self.dy[i],0))
275                else:
276                    tempy = self.y
277                    tempdy = self.dy
278               
279                if (self.xLabel.lower() == "log10(x)"):
280                    for x_i in self.x:
281                        if x_i >= math.log10(xmin):
282                            tempx.append(math.log10(x_i)) 
283                else:
284                    tempx = self.x
285             
286                #Find the fitting parameters
287               
288                if (self.xLabel.lower() == "log10(x)"):
289                    chisqr, out, cov = fittings.sansfit(self.model, [self.cstA, self.cstB],
290                    tempx, tempy,tempdy,math.log10(xmin),math.log10(xmax))
291                else:
292                    chisqr, out, cov = fittings.sansfit(self.model, 
293                                [self.cstA, self.cstB],tempx, tempy,tempdy,xminView,xmaxView)
294               
295                # Use chi2/dof
296                if len(tempx)>0:
297                    chisqr = chisqr/len(tempx)
298               
299                #Check that cov and out are iterable before displaying them
300                if cov ==None:
301                    errA =0.0
302                    errB =0.0
303                else:
304                    errA= math.sqrt(cov[0][0])
305                    errB= math.sqrt(cov[1][1])
306                if out==None:
307                    cstA=0.0
308                    cstB=0.0
309                else:
310                    cstA=out[0]
311                    cstB=out[1]
312                # Reset model with the right values of A and B
313                self.model.setParam('A', float(cstA))
314                self.model.setParam('B', float(cstB))
315               
316                tempx = []
317                tempy = []
318                y_model = 0.0
319                # load tempy with the minimum transformation
320               
321                if self.xLabel == "log10(x)":
322                    y_model = self.model.run(math.log10(xmin))
323                    tempx.append(xmin)
324                else:
325                    y_model = self.model.run(xminView)
326                    tempx.append(xminView)
327                   
328                if self.yLabel == "log10(y)":
329                    tempy.append(math.pow(10,y_model))
330                    print "tempy",tempy
331                else:
332                    tempy.append(y_model)
333                   
334                # load tempy with the maximum transformation
335                if self.xLabel == "log10(x)":
336                    y_model = self.model.run(math.log10(xmax))
337                    tempx.append(xmax)
338                else:
339                    y_model = self.model.run(xmaxView)
340                    tempx.append(xmaxView)
341                   
342                if self.yLabel == "log10(y)":
343                    tempy.append(math.pow(10,y_model))
344                else: 
345                    tempy.append(y_model)
346                #Set the fit parameter display when  FitDialog is opened again
347                self.Avalue=cstB
348                self.Bvalue=cstA
349                self.ErrAvalue=errA
350                self.ErrBvalue=errB
351                self.Chivalue=chisqr
352                self.push_data(tempx,tempy,xminView,xmaxView,xmin,xmax,self._ongetValues())
353               
354                # Display the fitting value on the Fit Dialog
355                self._onsetValues(cstB, cstA, errA,errB,chisqr)
356               
357               
358           
359    def _onsetValues(self,cstA,cstB,errA,errB,Chi):
360         """
361              Display  the value on fit Dialog
362         """
363         self.tcA.SetValue(format_number(cstA))
364         self.tcB.SetValue(format_number(cstB))
365         self.tcErrA.SetValue(format_number(errA))
366         self.tcErrB.SetValue(format_number(errB))
367         self.tcChi.SetValue(format_number(Chi))
368       
369    def _ongetValues(self):
370         """
371              Display  the value on fit Dialog
372         """
373         return self.Avalue, self.Bvalue,self.ErrAvalue,self.ErrBvalue,self.Chivalue
374         
375   
376    def _checkVal(self,usermin, usermax):
377        """
378                Ensure that fields parameter contains a min and a max value
379                within x min and x max range
380        """
381        if float(usermin) < float(usermax):
382            if float(usermin) >= float(self.mini) and float(usermin) < float(self.maxi):
383                self.xminFit.SetValue(format_number(float(usermin)))
384            else:
385                self.xminFit.SetValue(format_number(float(self.mini)))
386               
387            if float(usermax) > float(self.mini) and float(usermax) <= float(self.maxi):
388                self.xmaxFit.SetLabel(format_number(float(usermax)))
389            else:
390                self.xmaxFit.SetLabel(format_number(float(self.maxi)))
391               
392            mini =float(self.xminFit.GetValue())
393            maxi =float(self.xmaxFit.GetValue())
394           
395            return mini, maxi
396    def floatTransform(self,x):
397        """
398             transform a float.It is use to determine the x.View min and x.View max for values
399             not in x
400        """
401        if ( self.xLabel=="x" ):
402            return transform.toX(x)
403       
404        if ( self.xLabel=="x^(2)" ): 
405            return transform.toX2(x)
406       
407        if (self.xLabel=="log10(x)" ):
408            if x >0:
409                return x
410            else:
411                raise ValueError,"cannot compute log of a negative number"
412           
413    def checkFitValues(self,item):
414        """
415            Check the validity of input values
416        """
417        flag = True
418        value = item.GetValue()
419        # Check for possible values entered
420        if (self.xLabel=="log10(x)"):
421            if (float(value) > 0):
422                item.SetBackgroundColour(wx.WHITE)
423                item.Refresh()
424            else:
425                flag = False
426                item.SetBackgroundColour("pink")
427                item.Refresh()
428     
429        return flag
430       
431    def setFitRange(self,xmin,xmax,xminTrans,xmaxTrans):
432        """
433            Set fit parameters
434        """
435        self.xminFit.SetValue(format_number(xmin))
436        self.xmaxFit.SetValue(format_number(xmax))
437        self.xminTransFit.SetValue(format_number(xminTrans))
438        self.xmaxTransFit.SetValue(format_number(xmaxTrans))
439       
440 
441class MyApp(wx.App):
442    def OnInit(self):
443        wx.InitAllImageHandlers()
444        plot = Theory1D([],[])
445        dialog = LinearFit(None, plot, self.onFitDisplay,self.returnTrans, -1, 'Linear Fit')
446        if dialog.ShowModal() == wx.ID_OK:
447            pass
448        dialog.Destroy()
449       
450        return 1
451   
452    def onFitDisplay(self, tempx,tempy,xminView,xmaxView,xmin,xmax,func):
453        pass
454       
455    def returnTrans(self):
456        return '','',0,0,0,0,0
457
458# end of class MyApp
459
460if __name__ == "__main__":
461    app = MyApp(0)
462    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.