source: sasview/guitools/fitDialog.py @ 2e014bf

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

ore bugs fixed

  • Property mode set to 100644
File size: 14.5 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
11
12class LinearFit(wx.Dialog):
13    #def __init__(self, parent, id, title):
14    def __init__(self, parent, plottable, push_data,transform, id, title):
15        wx.Dialog.__init__(self, parent, id, title, size=(450, 400))
16        """
17            for the fit window
18        """
19        self.parent = parent
20        self.transform = transform
21        #dialog panel self call function to plot the fitting function
22        self.push_data = push_data
23        #dialog self plottable
24        self.plottable = plottable
25        # Receive transformations of x and y
26        self.xtrans,self.ytrans= self.transform()
27        #Dialog interface
28        panel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)   
29        vbox  = wx.BoxSizer(wx.VERTICAL)
30        sizer = wx.GridBagSizer(5,5)
31       
32        vbox.Add(panel, 1, wx.EXPAND | wx.ALL)
33 
34        self.tcA = wx.TextCtrl(panel, -1,size=(120,20),style=wx.SIMPLE_BORDER)
35        self.tcErrA = wx.TextCtrl(panel, -1,size=(120,20),style=wx.SIMPLE_BORDER)
36        self.tcB = wx.TextCtrl(panel, -1,size=(120,20),style=wx.SIMPLE_BORDER)
37        self.tcErrB = wx.TextCtrl(panel, -1,size=(120,20),style=wx.SIMPLE_BORDER)
38        self.tcChi = wx.TextCtrl(panel, -1,size=(120,20),style=wx.SIMPLE_BORDER)
39        self.FXmin = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
40        self.FXmax = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
41        self.FXminX = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
42        self.FXmaxX = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
43        self.PXmin = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
44        self.PXmax = wx.TextCtrl(panel,-1,size=(120,20),style=wx.SIMPLE_BORDER)
45        self.btFit =wx.Button(panel,-1,'Fit',size=(120, 30))
46        self.btClose =wx.Button(panel, wx.ID_CANCEL,'Close',size=(90, 30) )
47        self.static_line_1 = wx.StaticLine(panel, -1)
48       
49        ix = 0
50        iy = 1
51        sizer.Add(wx.StaticText(panel, -1, 'y = Ax +B'),(iy, ix),(1,1),\
52                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
53        iy+=1
54        sizer.Add(wx.StaticText(panel, -1, 'Param A'),(iy, ix),\
55                 (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
56        ix += 1
57        sizer.Add(self.tcA,(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
58        ix += 1
59        sizer.Add(wx.StaticText(panel, -1, '+/-'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
60        ix += 1
61        sizer.Add(self.tcErrA, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
62        iy += 1
63        ix = 0
64        sizer.Add(wx.StaticText(panel, -1, 'Param B'),(iy, ix),(1,1),\
65                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
66        ix += 1
67        sizer.Add(self.tcB, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
68        ix += 1
69        sizer.Add(wx.StaticText(panel, -1, '+/-'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
70        ix += 1
71        sizer.Add(self.tcErrB, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
72        iy += 1
73        ix = 0
74        sizer.Add(wx.StaticText(panel, -1, 'Chi ^{2}'),(iy, ix),(1,1),\
75                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
76        ix += 1
77        sizer.Add(self.tcChi, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
78        iy += 1
79        ix = 1
80        sizer.Add(wx.StaticText(panel, -1, 'Xmin'),(iy, ix),(1,1),\
81                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
82        ix += 2
83        sizer.Add(wx.StaticText(panel, -1, 'Xmax'),(iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
84        iy += 1
85        ix = 0
86        sizer.Add(wx.StaticText(panel, -1, 'Plotted Range'),(iy, ix),(1,1),\
87                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
88        ix +=1
89        sizer.Add(self.PXmin, (iy, ix),(1,1),\
90                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
91        ix += 2
92        sizer.Add(self.PXmax, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
93        iy += 1
94        ix = 1
95        sizer.Add(wx.StaticText(panel, -1,"x transofrmation is: "+self.xtrans ),(iy, ix),(1,1),\
96                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
97        iy += 1
98        ix = 0
99        sizer.Add(wx.StaticText(panel, -1, 'Fit Range'),(iy, ix),(1,1),\
100                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
101        ix += 1
102        sizer.Add(self.FXmin, (iy, ix),(1,1),\
103                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
104        ix += 2
105        sizer.Add(self.FXmax, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
106     
107        iy += 1
108        ix = 0
109        sizer.Add(wx.StaticText(panel, -1, 'Fit Range of x'),(iy, ix),(1,1),\
110                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
111        ix += 1
112        sizer.Add(self.FXminX, (iy, ix),(1,1),\
113                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
114        ix += 2
115        sizer.Add(self.FXmaxX, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
116        iy += 1
117        ix = 1
118       
119        sizer.Add(self.btFit, (iy, ix),(1,1), wx.LEFT|wx.ADJUST_MINSIZE, 0)
120        self.btFit.Bind(wx.EVT_BUTTON, self._onFit)
121        ix += 2
122        sizer.Add(self.btClose, (iy, ix),(1,1),\
123                  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
124       
125        panel.SetSizer(sizer)
126        self.SetSizer(vbox)
127        self.Centre()
128       
129        # Receives the type of model for the fitting
130        from LineModel import LineModel
131        self.model  = LineModel()
132         
133        #Display the fittings values
134        self.default_A = self.model.getParam('A') 
135        self.default_B = self.model.getParam('B') 
136        self.cstA = fittings.Parameter(self.model, 'A', self.default_A)
137        self.cstB  = fittings.Parameter(self.model, 'B', self.default_B)
138       
139        # Set default value of parameter in fit dialog
140        self.tcA.SetLabel(str(self.default_A))
141        self.tcB.SetLabel(str(self.default_B))
142        self.tcErrA.SetLabel(str(0.0))
143        self.tcErrB.SetLabel(str(0.0))
144        self.tcChi.SetLabel(str(0.0))
145       
146        if self.plottable.x !=[]:
147            self.mini =min(self.plottable.x)
148            self.maxi =max(self.plottable.x)
149           
150            self.FXmin.SetLabel(str(self.mini))
151            self.FXmax.SetLabel(str(self.maxi))
152            self.FXmin.Disable()
153            self.FXmax.Disable()
154           
155            self.PXmin.SetValue(str(self.mini))
156            self.PXmax.SetValue(str(self.maxi))
157            self.PXmin.Disable()
158            self.PXmax.Disable()
159           
160            self.FXminX.SetLabel(str(self.mini))
161            self.FXmaxX.SetLabel(str(self.maxi))
162           
163     
164    def _onFit(self ,event):
165        """
166            Performs the fit. Receive an event when clicking on the button Fit.Computes chisqr ,
167            A and B parameters of the best linear fit y=Ax +B
168            Push a plottable to
169        """
170        tempx=[]
171        tempy=[]
172        tempdy = []
173       
174        #store the values of View in x,y, dx,dy
175        x,y,dx,dy=self.plottable.returnValuesOfView()
176       
177        # Check if View contains a x array .we online fit when x exits
178        # makes transformation for y as a line to fit
179        if x != []: 
180           
181               
182            if(self.checkFitValues(self.FXminX) == True):
183                #Check if the field of Fit Dialog contain values and use the x max and min of the user
184                xmin,xmax = self._checkVal(self.FXminX.GetValue(),self.FXmaxX.GetValue())
185               
186                xminView=self.floatTransform(xmin)
187                xmaxView=self.floatTransform(xmax)
188                self.FXmin.SetValue(str(xminView))
189                self.FXmax.SetValue(str(xmaxView))
190                self.FXmin.Disable()
191                self.FXmax.Disable()
192                # Store the transformed values of view x, y,dy in variables  before the fit
193                if  self.ytrans.lower() == "log10(y)":
194                    if (self.xtrans.lower() == "log10(x)"):
195                        for i in range(len(x)):
196                            if x[i]>= math.log10(xmin):
197                                tempy.append(math.log10(y[i])) 
198                                tempdy.append(transform.errToLogX(y[i],0,dy[i],0))
199                    else:
200                        for i in range(len(y)):
201                            tempy.append(math.log10(y[i])) 
202                            tempdy.append(transform.errToLogX(y[i],0,dy[i],0))
203                else:
204                    tempy = y
205                    tempdy = dy
206               
207                if (self.xtrans.lower() == "log10(x)"):
208                    for x_i in x:
209                        if x_i >= math.log10(xmin):
210                            tempx.append(math.log10(x_i)) 
211                else:
212                    tempx = x
213                       
214                #for y_i in y:
215                #    dy = math.sqrt(math.fabs(y_i))
216                #    if dy >= y_i:
217                #        dy = 0.9*y_i
218                #    tempdy.append(dy)
219                       
220                #Find the fitting parameters
221               
222                if (self.xtrans.lower() == "log10(x)"):
223                    chisqr, out, cov = fittings.sansfit(self.model, [self.cstA, self.cstB],
224                    tempx, tempy,tempdy,math.log10(xmin),math.log10(xmax))
225                else:
226                    chisqr, out, cov = fittings.sansfit(self.model, 
227                                [self.cstA, self.cstB],tempx, tempy,tempdy,xminView,xmaxView)
228                print "this out",out
229                #Check that cov and out are iterable before displaying them
230                if cov ==None:
231                    errA =0.0
232                    errB =0.0
233                else:
234                    errA= math.sqrt(cov[0][0])
235                    errB= math.sqrt(cov[1][1])
236                if out==None:
237                    cstA=0.0
238                    cstB=0.0
239                else:
240                    cstA=out[0]
241                    cstB=out[1]
242                # Reset model with the right values of A and B
243                self.model.setParam('A', float(cstA))
244                self.model.setParam('B', float(cstB))
245               
246                tempx = []
247                tempy = []
248                y_model = 0.0
249                # load tempy with the minimum transformation
250               
251                if self.xtrans == "log10(x)":
252                    y_model = self.model.run(math.log10(xmin))
253                    tempx.append(xmin)
254                else:
255                    y_model = self.model.run(xminView)
256                    tempx.append(xminView)
257                   
258                if self.ytrans == "log10(y)":
259                    tempy.append(math.pow(10,y_model))
260                    print "tempy",tempy
261                else:
262                    tempy.append(y_model)
263                   
264                # load tempy with the maximum transformation
265                if self.xtrans == "log10(x)":
266                    y_model = self.model.run(math.log10(xmax))
267                    tempx.append(xmax)
268                else:
269                    y_model = self.model.run(xmaxView)
270                    tempx.append(xmaxView)
271                   
272                if self.ytrans == "log10(y)":
273                    tempy.append(math.pow(10,y_model))
274                else: 
275                    tempy.append(y_model)
276               
277                self.push_data(tempx,tempy,xminView,xmaxView,xmin,xmax)
278               
279                # Display the fitting value on the Fit Dialog
280                self._onsetValues(cstA, cstB, errA,errB,chisqr)
281           
282    def _onsetValues(self,cstA,cstB,errA,errB,Chi):
283         """
284              Display  the value on fit Dialog
285         """
286         self.tcA.SetValue(str(cstA))
287         self.tcB.SetValue(str(cstB))
288         self.tcErrA.SetValue(str(errA))
289         self.tcErrB.SetValue(str(errB))
290         self.tcChi.SetValue(str(Chi))
291         
292    def _returnPlottable(self):
293        return self.file_data1
294   
295    def _checkVal(self,usermin, usermax):
296        """
297                Ensure that fields parameter contains a min and a max value
298                within x min and x max range
299        """
300        if float(usermin) < float(usermax):
301            if float(usermin) >= float(self.mini) and float(usermin) < float(self.maxi):
302                self.FXminX.SetValue(str(usermin))
303            else:
304                self.FXminX.SetValue(str(self.mini))
305               
306            if float(usermax) > float(self.mini) and float(usermax) <= float(self.maxi):
307                self.FXmaxX.SetLabel(str(usermax))
308            else:
309                self.FXmaxX.SetLabel(str(self.maxi))
310               
311            mini =float(self.FXminX.GetValue())
312            maxi =float(self.FXmaxX.GetValue())
313           
314            return mini, maxi
315    def floatTransform(self,x):
316        """
317             transform a float.It is use to determine the x.View min and x.View max for values
318             not in x
319        """
320        if ( self.xtrans=="x" ):
321            return transform.toX(x)
322       
323        if ( self.xtrans=="x^(2)" ): 
324            return transform.toX2(x)
325       
326        if (self.xtrans=="log10(x)" ):
327            if x >0:
328                return x
329            else:
330                raise ValueError,"cannot compute log of a negative number"
331           
332    def checkFitValues(self,item):
333        """
334            Check the validity of input values
335        """
336        flag = True
337        value = item.GetValue()
338        # Check for possible values entered
339        if (self.xtrans=="log10(x)"):
340            if (float(value) > 0):
341                item.SetBackgroundColour(wx.WHITE)
342                item.Refresh()
343            else:
344                flag = False
345                item.SetBackgroundColour("pink")
346                item.Refresh()
347     
348        return flag
349       
350    def setFitRange(self,xmin,xmax,Reelxmin,Reelxmax):
351        if (self.xtrans=="log10(x)"):
352            self.FXmin.SetValue(str(math.log10(xmin)))
353            self.FXmax.SetValue(str(math.log10(xmax)))
354        else:
355            self.FXmin.SetValue(str(xmin))
356            self.FXmax.SetValue(str(xmax))
357        self.FXminX.SetValue(str(Reelxmin))
358        self.FXmaxX.SetValue(str(Reelxmax))
359       
360   
361if __name__ == "__main__": 
362    app = wx.App()
363    dialog=LinearFit(None, -1, 'Fitting')
364    dialog.ShowModal()
365    app.MainLoop()
366
367
Note: See TracBrowser for help on using the repository browser.