source: sasview/guitools/fitDialog.py @ bbec827

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

working

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