source: sasview/guitools/fitDialog.py @ 863607a

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

working on fit linear

  • Property mode set to 100644
File size: 11.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       
143    def _onFit(self ,event):
144        """
145            Performs the fit. Receive an event when clicking on the button Fit.Computes chisqr ,
146            A and B parameters of the best linear fit y=Ax +B
147            Push a plottable to
148        """
149       
150        tempx=[]
151        tempy=[]
152        tempdy = []
153       
154        #Check if the field of Fit Dialog contain values and use the x max and min of the user
155        xmin,xmax = self._checkVal(self.FXmin.GetValue(),self.FXmax.GetValue())
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            xminView=self.floatTransform(xmin)
165            xmaxView=self.floatTransform(xmax)
166       
167            # Store the transformed values of view x, y,dy in variables  before the fit
168            if  self.ytrans.lower() == "log10(y)":
169                for y_i in y:
170                    tempy.append(math.log10(y_i)) 
171            else:
172                tempy = y
173            if  self.xtrans.lower() == "log10(x)":
174                for x_i in x:
175                    tempx.append(math.log10(x_i)) 
176            else:
177                tempx = x
178                   
179            for y_i in y:
180                dy = 1/y_i
181                if dy >= y_i:
182                    dy = 0.9*y_i
183                tempdy.append(dy)
184                   
185            #Find the fitting parameters
186            chisqr, out, cov = fittings.sansfit(self.model, 
187                            [self.cstA, self.cstB],tempx, tempy,tempdy,xminView,xmaxView)
188           
189            #Check that cov and out are iterable before displaying them
190            if cov ==None:
191                errA =0.0
192                errB =0.0
193            else:
194                errA= math.sqrt(cov[0][0])
195                errB= math.sqrt(cov[1][1])
196            if out==None:
197                cstA=0.0
198                cstB=0.0
199            else:
200                cstA=out[0]
201                cstB=out[1]
202            # Reset model with the right values of A and B
203            self.model.setParam('A', float(cstA))
204            self.model.setParam('B', float(cstB))
205           
206            tempx = []
207            tempy = []
208            y_model = 0.0
209            # load tempy with the minimum transformation
210           
211            if self.xtrans == "log10(x)":
212                y_model = self.model.run(math.log10(xmin))
213                tempx.append(xmin)
214            else:
215                y_model = self.model.run(xminView)
216                tempx.append(xminView)
217               
218            if self.ytrans == "log10(y)":
219                tempy.append(math.pow(10,y_model))
220            else:
221                tempy.append(y_model)
222               
223            # load tempy with the maximum transformation
224            if self.xtrans == "log10(x)":
225                y_model = self.model.run(math.log10(xmax))
226                tempx.append(xmax)
227            else:
228                y_model = self.model.run(xmaxView)
229                tempx.append(xmaxView)
230               
231            if self.ytrans == "log10(y)":
232                tempy.append(math.pow(10,y_model))
233            else: 
234                tempy.append(y_model)
235         
236            # Create new data plottable with result
237            self.file_data1.x =[] 
238            self.file_data1.y =[] 
239            self.file_data1.x =tempx 
240            self.file_data1.y =tempy     
241            self.file_data1.dx=None
242            self.file_data1.dy=None
243            #Load the view with the new values
244            self.file_data1.reset_view()
245           
246            #Send the data to display to the PlotPanel
247            self.push_data(self.file_data1,xminView, xmaxView)
248           
249            # Display the fitting value on the Fit Dialog
250            self._onsetValues(cstA, cstB, errA,errB,chisqr)
251   
252    def _onsetValues(self,cstA,cstB,errA,errB,Chi):
253         """
254              Display  the value on fit Dialog
255         """
256         self.tcA.SetValue(str(cstA))
257         self.tcB.SetValue(str(cstB))
258         self.tcErrA.SetValue(str(errA))
259         self.tcErrB.SetValue(str(errB))
260         self.tcChi.SetValue(str(Chi))
261         
262    def _returnPlottable(self):
263        return self.file_data1
264   
265    def _checkVal(self,usermin, usermax):
266        """
267                Ensure that fields parameter contains a min and a max value
268                within x min and x max range
269        """
270        if float(usermin) < float(usermax):
271            if float(usermin) >= float(self.mini) and float(usermin) < float(self.maxi):
272                self.FXmin.SetValue(str(usermin))
273            else:
274                self.FXmin.SetValue(str(self.mini))
275               
276            if float(usermax) > float(self.mini) and float(usermax) <= float(self.maxi):
277                self.FXmax.SetLabel(str(usermax))
278            else:
279                self.FXmax.SetLabel(str(self.maxi))
280               
281            mini =float(self.FXmin.GetValue())
282            maxi =float(self.FXmax.GetValue())
283           
284            return mini, maxi
285    def floatTransform(self,x):
286        """
287             transform a float.It is use to determine the x.View min and x.View max for values
288             not in x
289        """
290        if ( self.xtrans=="x" ):
291            return transform.toX(x)
292       
293        if ( self.xtrans=="x^(2)" ):
294            return transform.toX2(x)
295       
296        if (self.xtrans=="log10(x)" ):
297            if x >0:
298                return math.log10(x)
299            else:
300                raise ValueError,"cannot compute log of a negative number"
301       
302               
303   
304if __name__ == "__main__": 
305    app = wx.App()
306    dialog=LinearFit(None, -1, 'Fitting')
307    dialog.ShowModal()
308    app.MainLoop()
309
310
Note: See TracBrowser for help on using the repository browser.