source: sasview/guitools/fitDialog.py @ edce46e

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

some modificatiosn made

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