source: sasview/plottools/src/danse/common/plottools/fitDialog.py @ 9bab141

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 9bab141 was 9bab141, checked in by Jae Cho <jhjcho@…>, 12 years ago

added Rg etc on fitdialog

  • Property mode set to 100644
File size: 27.7 KB
Line 
1import wx
2from plottables import Theory1D
3import math
4import numpy
5import fittings
6import transform
7import sys
8
9#Linear fit panel size
10if sys.platform.count("win32") > 0:
11    FONT_VARIANT = 0
12    PNL_WIDTH = 450
13    PNL_HEIGHT = 500
14else:
15    FONT_VARIANT = 1
16    PNL_WIDTH = 500
17    PNL_HEIGHT = 500
18RG_ON = True   
19   
20def format_number(value, high=False):
21    """
22    Return a float in a standardized, human-readable formatted string
23    """
24    try:
25        value = float(value)
26    except:
27        output = "NaN"
28        return output.lstrip().rstrip()
29   
30    if high:
31        output = "%-6.4g" % value
32       
33    else:
34        output = "%-5.3g" % value
35    return output.lstrip().rstrip()
36
37
38class LinearFit(wx.Dialog):
39    def __init__(self, parent, plottable, push_data, transform, title):
40        """
41        Dialog window pops- up when select Linear fit on Context menu
42        Displays fitting parameters
43        """
44        wx.Dialog.__init__(self, parent, title=title, 
45                           size=(PNL_WIDTH, 350))
46        self.parent = parent
47        self.transform = transform
48        #Font
49        self.SetWindowVariant(variant=FONT_VARIANT)
50        # Registered owner for close event
51        self._registered_close = None
52       
53        #dialog panel self call function to plot the fitting function
54        self.push_data = push_data
55        #dialog self plottable
56        self.plottable = plottable
57        self.rg_on = False
58        # Receive transformations of x and y
59        self.xLabel, self.yLabel, self.Avalue, self.Bvalue,\
60               self.ErrAvalue, self.ErrBvalue, self.Chivalue = self.transform()
61       
62        #Dialog interface
63        vbox  = wx.BoxSizer(wx.VERTICAL)
64        sizer = wx.GridBagSizer(5, 5)
65        _BOX_WIDTH = 100
66 
67        self.tcA      = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
68        self.tcA.SetToolTipString("Fit value for the slope parameter.")
69        self.tcErrA   = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
70        self.tcErrA.SetToolTipString("Error on the slope parameter.")
71        self.tcB      = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
72        self.tcA.SetToolTipString("Fit value for the constant parameter.")
73        self.tcErrB   = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
74        self.tcErrB.SetToolTipString("Error on the constant parameter.")
75        self.tcChi    = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
76        self.tcChi.SetToolTipString("Chi^2 over degrees of freedom.")
77        self.xminFit  = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
78        msg = "Enter the minimum value on "
79        msg += "the x-axis to be included in the fit."
80        self.xminFit.SetToolTipString(msg)
81        self.xmaxFit  = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
82        msg = "Enter the maximum value on "
83        msg += " the x-axis to be included in the fit."
84        self.xmaxFit.SetToolTipString(msg)
85        self.initXmin = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
86        msg = "Minimum value on the x-axis for the plotted data."
87        self.initXmin.SetToolTipString(msg)
88        self.initXmax = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, 20))
89        msg = "Maximum value on the x-axis for the plotted data."
90        self.initXmax.SetToolTipString(msg)
91
92        # Make the info box not editable
93        #_BACKGROUND_COLOR = '#ffdf85'
94        _BACKGROUND_COLOR = self.GetBackgroundColour()
95        self.initXmin.SetEditable(False)
96        self.initXmin.SetBackgroundColour(_BACKGROUND_COLOR)
97        self.initXmax.SetEditable(False)
98        self.initXmax.SetBackgroundColour(_BACKGROUND_COLOR)
99       
100        # Buttons on the bottom
101        self.static_line_1 = wx.StaticLine(self, -1)
102        self.btFit = wx.Button(self, -1, 'Fit')
103        self.btFit.Bind(wx.EVT_BUTTON, self._onFit)
104        self.btFit.SetToolTipString("Perform fit.")
105        self.btClose =wx.Button(self, wx.ID_CANCEL, 'Close')
106        self.btClose.Bind(wx.EVT_BUTTON, self._on_close)
107       
108        # Intro
109        explanation = "Perform fit for y(x) = ax + b"
110        vbox.Add(sizer)
111        ix = 0
112        iy = 1
113        sizer.Add(wx.StaticText(self, -1, explanation), (iy, ix),
114                 (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
115        iy += 2
116        sizer.Add(wx.StaticText(self, -1, 'Parameter a'), (iy, ix),
117                 (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
118        ix += 1
119        sizer.Add(self.tcA,(iy, ix),(1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
120        ix += 1
121        sizer.Add(wx.StaticText(self, -1, '+/-'),
122                  (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
123        ix += 1
124        sizer.Add(self.tcErrA, (iy, ix), (1, 1),
125                  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
126        iy += 1
127        ix = 0
128        sizer.Add(wx.StaticText(self, -1, 'Parameter b'), (iy, ix),(1, 1),
129                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
130        ix += 1
131        sizer.Add(self.tcB, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
132        ix += 1
133        sizer.Add(wx.StaticText(self, -1, '+/-'), (iy, ix),
134                  (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
135        ix += 1
136        sizer.Add(self.tcErrB, (iy, ix), (1, 1),
137                   wx.EXPAND|wx.ADJUST_MINSIZE, 0)
138        iy += 1
139        ix = 0
140        sizer.Add(wx.StaticText(self, -1, 'Chi2/dof'), (iy, ix), (1, 1),
141                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
142        ix += 1
143        sizer.Add(self.tcChi, (iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
144
145       
146        #sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
147        iy += 2
148        ix = 1
149        sizer.Add(wx.StaticText(self, -1, 'Min'), (iy, ix), (1, 1),
150                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
151        ix += 2
152        sizer.Add(wx.StaticText(self, -1, 'Max'), (iy, ix),
153                  (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
154
155        iy += 1
156        ix = 0
157        sizer.Add(wx.StaticText(self, -1, 'Maximum range (linear scale)'),
158                  (iy, ix),(1,1),
159                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
160        ix += 1
161        sizer.Add(self.initXmin, (iy, ix), (1,1),
162                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
163        ix += 2
164        sizer.Add(self.initXmax, (iy, ix), (1,1), 
165                  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
166       
167        iy += 1
168        ix = 0
169        sizer.Add(wx.StaticText(self, -1, 'Fit range of ' + self.xLabel),
170                  (iy, ix), (1, 1),
171                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
172        ix += 1
173        sizer.Add(self.xminFit, (iy, ix), (1, 1),
174                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
175        ix += 2
176        sizer.Add(self.xmaxFit, (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
177        if RG_ON:
178            if (self.yLabel == "ln(y)" or self.yLabel == "ln(y*x)") and \
179                    (self.xLabel == "x^(2)"):
180                self.rg_on = True
181                self.SetSize((PNL_WIDTH, PNL_HEIGHT))
182                I0_stxt = wx.StaticText(self, -1, 'I(q=0)')
183                self.I0_tctr = wx.TextCtrl(self, -1, '')
184                self.I0_tctr.SetEditable(False)
185                self.I0_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
186                self.I0err_tctr = wx.TextCtrl(self, -1, '')
187                self.I0err_tctr.SetEditable(False)
188                self.I0err_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
189                Rg_stxt = wx.StaticText(self, -1, 'Rg (A)')
190                Rg_stxt.Show(self.yLabel == "ln(y)" )
191                self.Rg_tctr = wx.TextCtrl(self, -1, '')
192                self.Rg_tctr.SetEditable(False)
193                self.Rg_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
194                self.Rg_tctr.Show(self.yLabel == "ln(y)" )
195                self.Rgerr_tctr = wx.TextCtrl(self, -1, '')
196                self.Rgerr_tctr.SetEditable(False)
197                self.Rgerr_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
198                self.Rgerr_tctr.Show(self.yLabel == "ln(y)" )
199                Diameter_stxt = wx.StaticText(self, -1, 'Rod Diameter (A)')
200                Diameter_stxt.Show(self.yLabel == "ln(y*x)")
201                self.Diameter_tctr = wx.TextCtrl(self, -1, '')
202                self.Diameter_tctr.SetEditable(False)
203                self.Diameter_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
204                self.Diameter_tctr.Show(self.yLabel == "ln(y*x)")
205                self.Diametererr_tctr = wx.TextCtrl(self, -1, '')
206                self.Diametererr_tctr.SetEditable(False)
207                self.Diametererr_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
208                self.Diametererr_tctr.Show(self.yLabel == "ln(y*x)")
209                RgQmin_stxt = wx.StaticText(self, -1, 'Rg*Qmin')
210                self.RgQmin_tctr = wx.TextCtrl(self, -1, '')
211                self.RgQmin_tctr.SetEditable(False)
212                self.RgQmin_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
213                RgQmax_stxt = wx.StaticText(self, -1, 'Rg*Qmax')
214                self.RgQmax_tctr = wx.TextCtrl(self, -1, '')
215                self.RgQmax_tctr.SetEditable(False)
216                self.RgQmax_tctr.SetBackgroundColour(_BACKGROUND_COLOR)
217
218                #sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
219                iy += 2
220                ix = 0
221                sizer.Add(I0_stxt, (iy, ix),(1,1),
222                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
223                ix += 1
224                sizer.Add(self.I0_tctr, (iy, ix), (1,1),
225                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
226       
227                ix += 2
228                sizer.Add(self.I0err_tctr, (iy, ix), (1,1), 
229                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
230               
231                iy += 1
232                ix = 0
233                sizer.Add(Rg_stxt, (iy, ix),(1,1),
234                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
235                ix += 1
236                sizer.Add(self.Rg_tctr, (iy, ix), (1,1),
237                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
238       
239                ix += 2
240                sizer.Add(self.Rgerr_tctr, (iy, ix), (1,1), 
241                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
242                iy += 1
243                ix = 0
244                sizer.Add(Diameter_stxt, (iy, ix),(1,1),
245                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
246                ix += 1
247                sizer.Add(self.Diameter_tctr, (iy, ix), (1,1),
248                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
249       
250                ix += 2
251                sizer.Add(self.Diametererr_tctr, (iy, ix), (1,1), 
252                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
253                iy += 1
254                ix = 0
255                sizer.Add(RgQmin_stxt, (iy, ix),(1,1),
256                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
257                ix += 1
258                sizer.Add(self.RgQmin_tctr, (iy, ix), (1,1),
259                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
260                iy += 1
261                ix = 0
262                sizer.Add(RgQmax_stxt, (iy, ix),(1,1),
263                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
264                ix += 1
265                sizer.Add(self.RgQmax_tctr, (iy, ix), (1,1),
266                                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
267           
268        iy += 1
269        ix = 1
270       
271        vbox.Add(self.static_line_1, 0, wx.EXPAND, 0)
272        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
273        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
274        sizer_button.Add(self.btFit, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
275        sizer_button.Add(self.btClose, 0,
276                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
277        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
278       
279        sizer.Add(self.btFit, (iy, ix), (1,1), wx.LEFT|wx.ADJUST_MINSIZE, 0)
280        #panel.SetSizer(sizer)
281        self.SetSizer(vbox)
282        self.Centre()
283        # Receives the type of model for the fitting
284        from LineModel import LineModel
285        self.model = LineModel()
286        #Display the fittings values
287        self.default_A = self.model.getParam('A')
288        self.default_B = self.model.getParam('B')
289        self.cstA = fittings.Parameter(self.model, 'A', self.default_A)
290        self.cstB = fittings.Parameter(self.model, 'B', self.default_B)
291       
292        # Set default value of parameter in fit dialog
293        if self.Avalue == None:
294            self.tcA.SetValue(format_number(self.default_A))
295        else:
296            self.tcA.SetLabel(format_number(self.Avalue))
297        if self.Bvalue == None:
298            self.tcB.SetValue(format_number(self.default_B))
299        else:
300            self.tcB.SetLabel(format_number(self.Bvalue))
301        if self.ErrAvalue == None:
302            self.tcErrA.SetLabel(format_number(0.0))
303        else:
304            self.tcErrA.SetLabel(format_number(self.ErrAvalue))
305        if self.ErrBvalue == None:
306            self.tcErrB.SetLabel(format_number(0.0))
307        else:
308            self.tcErrB.SetLabel(format_number(self.ErrBvalue))
309        if self.Chivalue == None:
310            self.tcChi.SetLabel(format_number(0.0))
311        else:
312            self.tcChi.SetLabel(format_number(self.Chivalue))
313        if self.plottable.x != []:
314            #store the values of View in self.x,self.y,self.dx,self.dy
315            self.x, self.y, self.dx, \
316                     self.dy = self.plottable.returnValuesOfView()
317            try:
318                self.mini = self.floatForwardTransform(min(self.x))
319            except:
320                self.mini = "Invalid"
321            try:
322                self.maxi = self.floatForwardTransform(max(self.x))
323            except:
324                self.maxi = "Invalid"
325
326            self.initXmin.SetValue(format_number(min(self.plottable.x)))
327            self.initXmax.SetValue(format_number(max(self.plottable.x)))
328            self.mini = min(self.x)
329            self.maxi = max(self.x)
330            self.xminFit.SetValue(format_number(self.mini))
331            self.xmaxFit.SetValue(format_number(self.maxi))
332   
333    def register_close(self, owner):
334        """
335        Method to register the close event to a parent
336        window that needs notification when the dialog
337        is closed
338       
339        :param owner: parent window
340       
341        """
342        self._registered_close = owner
343       
344    def _on_close(self, event):
345        """
346        Close event.
347        Notify registered owner if available.
348        """
349        event.Skip()
350        if self._registered_close is not None:
351            self._registered_close()
352       
353    def _onFit(self, event):
354        """
355        Performs the fit. Receive an event when clicking on
356        the button Fit.Computes chisqr ,
357        A and B parameters of the best linear fit y=Ax +B
358        Push a plottable to
359        """
360        tempx = []
361        tempy = []
362        tempdy = []
363       
364        # Check if View contains a x array .we online fit when x exits
365        # makes transformation for y as a line to fit
366        if self.x != []:
367            if(self.checkFitValues(self.xminFit) == True):
368                #Check if the field of Fit Dialog contain values
369                # and use the x max and min of the user
370                #xminView,xmaxView = self._checkVal(self.xminFit.GetValue(),
371                #self.xmaxFit.GetValue())
372                if not self._checkVal(self.xminFit, self.xmaxFit):
373                    return
374                xminView = float(self.xminFit.GetValue())
375                xmaxView = float(self.xmaxFit.GetValue())
376                #xmin = self.floatInvTransform(xminView)
377                #xmax = self.floatInvTransform(xmaxView)
378                xmin = xminView
379                xmax = xmaxView
380                # Store the transformed values of view x, y,dy
381                # in variables  before the fit
382                if self.yLabel.lower() == "log10(y)":
383                    if (self.xLabel.lower() == "log10(x)"):
384                        for i in range(len(self.x)):
385                            if self.x[i] >= math.log10(xmin):
386                                tempy.append(math.log10(self.y[i]))
387                                tempdy.append(transform.errToLogX(self.y[i],
388                                                        0, self.dy[i], 0))
389                    else:
390                        for i in range(len(self.y)):
391                            tempy.append(math.log10(self.y[i]))
392                            tempdy.append(transform.errToLogX(self.y[i],
393                                                            0, self.dy[i], 0))
394                else:
395                    tempy = self.y
396                    tempdy = self.dy
397               
398                if (self.xLabel.lower() == "log10(x)"):
399                    for x_i in self.x:
400                        if x_i >= math.log10(xmin):
401                            tempx.append(math.log10(x_i))
402                else:
403                    tempx = self.x
404             
405                #Find the fitting parameters
406                # Always use the same defaults, so that fit history
407                #doesn't play a role!
408                self.cstA = fittings.Parameter(self.model, 'A', self.default_A)
409                self.cstB = fittings.Parameter(self.model, 'B', self.default_B)
410               
411                if (self.xLabel.lower() == "log10(x)"):
412                    tempdy = numpy.asarray(tempdy)
413                    tempdy[tempdy == 0] = 1
414                    chisqr, out, cov = fittings.sansfit(self.model,
415                                                        [self.cstA, self.cstB],
416                                                        tempx, tempy,
417                                                        tempdy,
418                                                        math.log10(xmin),
419                                                        math.log10(xmax))
420                else:
421                    tempdy = numpy.asarray(tempdy)
422                    tempdy[tempdy == 0] = 1
423                    chisqr, out, cov = fittings.sansfit(self.model,
424                                                        [self.cstA, self.cstB],
425                                                        tempx, tempy, tempdy,
426                                                        xminView, xmaxView)
427                # Use chi2/dof
428                if len(tempx) > 0:
429                    chisqr = chisqr/len(tempx)
430               
431                #Check that cov and out are iterable before displaying them
432                if cov == None:
433                    errA = 0.0
434                    errB = 0.0
435                else:
436                    errA = math.sqrt(cov[0][0])
437                    errB = math.sqrt(cov[1][1])
438                if out == None:
439                    cstA = 0.0
440                    cstB = 0.0
441                else:
442                    cstA = out[0]
443                    cstB = out[1]
444                # Reset model with the right values of A and B
445                self.model.setParam('A', float(cstA))
446                self.model.setParam('B', float(cstB))
447               
448                tempx = []
449                tempy = []
450                y_model = 0.0
451                # load tempy with the minimum transformation
452               
453                if self.xLabel == "log10(x)":
454                    y_model = self.model.run(math.log10(xmin))
455                    tempx.append(xmin)
456                else:
457                    y_model = self.model.run(xminView)
458                    tempx.append(xminView)
459                   
460                if self.yLabel == "log10(y)":
461                    tempy.append(math.pow(10, y_model))
462                else:
463                    tempy.append(y_model)
464                   
465                # load tempy with the maximum transformation
466                if self.xLabel == "log10(x)":
467                    y_model = self.model.run(math.log10(xmax))
468                    tempx.append(xmax)
469                else:
470                    y_model = self.model.run(xmaxView)
471                    tempx.append(xmaxView)
472                   
473                if self.yLabel == "log10(y)":
474                    tempy.append(math.pow(10, y_model))
475                else:
476                    tempy.append(y_model)
477                #Set the fit parameter display when  FitDialog is opened again
478                self.Avalue = cstB
479                self.Bvalue = cstA
480                self.ErrAvalue = errA
481                self.ErrBvalue = errB
482                self.Chivalue = chisqr
483                self.push_data(tempx, tempy, xminView, xmaxView,
484                               xmin, xmax, self._ongetValues())
485               
486                # Display the fitting value on the Fit Dialog
487                self._onsetValues(cstB, cstA, errA, errB, chisqr)
488               
489    def _onsetValues(self, cstA, cstB, errA, errB, Chi):
490        """
491        Display  the value on fit Dialog
492        """
493        rg = None
494        self.tcA.SetValue(format_number(cstA))
495        self.tcB.SetValue(format_number(cstB))
496        self.tcErrA.SetValue(format_number(errA))
497        self.tcErrB.SetValue(format_number(errB))
498        self.tcChi.SetValue(format_number(Chi))
499        if self.rg_on:
500            if self.Rg_tctr.IsShown():
501                rg = numpy.sqrt(-3 * float(cstA))
502                value = format_number(rg)
503                self.Rg_tctr.SetValue(value)
504                if self.I0_tctr.IsShown():
505                    val = numpy.exp(cstB)
506                    self.I0_tctr.SetValue(format_number(val))
507            if self.Rgerr_tctr.IsShown():
508                if rg != None and rg != 0:
509                    value = format_number(3 * float(cstA) / (2 * rg))
510                else:
511                    value =''
512                self.Rgerr_tctr.SetValue(value)
513                if self.I0err_tctr.IsShown():
514                    val = numpy.abs(numpy.exp(cstB) - numpy.exp(cstB + errB))
515                    self.I0err_tctr.SetValue(format_number(val))
516            if self.Diameter_tctr.IsShown():
517                rg = 4 * numpy.sqrt(-float(cstA))
518                value = format_number(rg)
519                self.Diameter_tctr.SetValue(value)
520            if self.Diametererr_tctr.IsShown():
521                if rg != None and rg != 0:
522                    value = format_number(8 * float(cstA) / rg)
523                else:
524                    value =''
525                self.Diametererr_tctr.SetValue(value)
526            if self.RgQmin_tctr.IsShown():
527                value = format_number(rg * self.mini)
528                self.RgQmin_tctr.SetValue(value)
529            if self.RgQmax_tctr.IsShown():
530                value = format_number(rg * self.maxi)
531                self.RgQmax_tctr.SetValue(value)
532               
533    def _ongetValues(self):
534        """
535        Display  the value on fit Dialog
536        """
537        return self.Avalue, self.Bvalue, self.ErrAvalue, \
538                            self.ErrBvalue, self.Chivalue
539   
540    def _checkVal(self, usermin, usermax):
541        """
542        Ensure that fields parameter contains a min and a max value
543        within x min and x max range
544        """
545        self.mini = float(self.xminFit.GetValue())
546        self.maxi = float(self.xmaxFit.GetValue())
547        flag = True
548        try:
549            mini = float(usermin.GetValue())
550            maxi = float(usermax.GetValue())
551            if mini < maxi:
552                usermin.SetBackgroundColour(wx.WHITE)
553                usermin.Refresh()
554            else:
555                flag = False
556                usermin.SetBackgroundColour("pink")
557                usermin.Refresh()
558        except:
559            # Check for possible values entered
560            flag = False
561            usermin.SetBackgroundColour("pink")
562            usermin.Refresh()
563     
564        return flag
565           
566    def floatForwardTransform(self, x):
567        """
568        transform a float.
569        """
570        #TODO: refactor this with proper object-oriented design
571        # This code stinks.
572        if(self.xLabel == "x"):
573            return transform.toX(x)
574        if(self.xLabel == "x^(2)"):
575            return transform.toX2(x)
576        if(self.xLabel == "ln(x)"):
577            return transform.toLogX(x)
578        if(self.xLabel == "log10(x)"):
579            return math.log10(x)
580                   
581    def floatTransform(self, x):
582        """
583        transform a float.It is use to determine the x.
584        View min and x.View max for values
585        not in x
586        """
587        #TODO: refactor this with proper object-oriented design
588        # This code stinks.
589        if(self.xLabel == "x"):
590            return transform.toX(x)
591        if(self.xLabel == "x^(2)"):
592            return transform.toX2(x)
593        if(self.xLabel == "ln(x)"):
594            return transform.toLogX(x)
595        if(self.xLabel == "log10(x)"):
596            if x > 0:
597                return x
598            else:
599                raise ValueError, "cannot compute log of a negative number"
600           
601    def floatInvTransform(self, x):
602        """
603        transform a float.It is use to determine the x.View min and x.View
604        max for values not in x
605       
606        """
607        #TODO: refactor this. This is just a hack to make the
608        # functionality work without rewritting the whole code
609        # with good design (which really should be done...).
610        if(self.xLabel == "x^(2)"):
611            return math.sqrt(x)
612       
613        elif(self.xLabel == "log10(x)"):
614            return math.pow(10, x)
615       
616        elif(self.xLabel == "ln(x)"):
617            return math.exp(x)
618        return x
619           
620    def checkFitValues(self, item):
621        """
622            Check the validity of input values
623        """
624        flag = True
625        value = item.GetValue()
626        # Check for possible values entered
627        if (self.xLabel == "log10(x)"):  #or self.xLabel=="ln(x)"):
628            if(float(value) > 0):
629                item.SetBackgroundColour(wx.WHITE)
630                item.Refresh()
631            else:
632                flag = False
633                item.SetBackgroundColour("pink")
634                item.Refresh()
635        return flag
636       
637    def setFitRange(self, xmin, xmax, xminTrans, xmaxTrans):
638        """
639        Set fit parameters
640        """
641        self.xminFit.SetValue(format_number(xmin))
642        self.xmaxFit.SetValue(format_number(xmax))
643       
644    def set_fit_region(self, xmin, xmax):
645        """
646        Set the fit region
647        :param xmin: minimum x-value to be included in fit
648        :param xmax: maximum x-value to be included in fit
649        """
650        # Check values
651        try:
652            float(xmin)
653            float(xmax)
654        except:
655            msg = "LinearFit.set_fit_region: fit range must be floats"
656            raise ValueError, msg
657        self.xminFit.SetValue(format_number(xmin))
658        self.xmaxFit.SetValue(format_number(xmax))
659 
660 
661class MyApp(wx.App):
662    """
663    """
664    def OnInit(self):
665        """
666        """
667        wx.InitAllImageHandlers()
668        plot = Theory1D([], [])
669        dialog = LinearFit(parent=None, plottable=plot,
670                           push_data=self.onFitDisplay,
671                           transform=self.returnTrans,
672                            title='Linear Fit')
673        if dialog.ShowModal() == wx.ID_OK:
674            pass
675        dialog.Destroy()
676        return 1
677   
678    def onFitDisplay(self, tempx, tempy, xminView, xmaxView, xmin, xmax, func):
679        """
680        """
681        pass
682       
683    def returnTrans(self):
684        """
685        """
686        return '', '', 0, 0, 0, 0, 0
Note: See TracBrowser for help on using the repository browser.