source: sasview/sansview/perspectives/fitting/fitpage.py @ b5e98540

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

fixed the first or last points missing from calculations

  • Property mode set to 100644
File size: 44.9 KB
Line 
1import sys
2import wx
3import wx.lib.newevent
4import numpy
5import copy
6import math
7from sans.models.dispersion_models import ArrayDispersion, GaussianDispersion
8
9from sans.guicomm.events import StatusEvent   
10from sans.guiframe.utils import format_number,check_float
11
12## event to post model to fit to fitting plugins
13(ModelEventbox, EVT_MODEL_BOX) = wx.lib.newevent.NewEvent()
14
15## event to know the selected fit engine
16(FitterTypeEvent, EVT_FITTER_TYPE)   = wx.lib.newevent.NewEvent()
17_BOX_WIDTH = 80
18
19import basepage
20from basepage import BasicPage
21from basepage import PageInfoEvent
22
23
24class FitPage(BasicPage):
25    """
26        FitPanel class contains fields allowing to display results when
27        fitting  a model and one data
28        @note: For Fit to be performed the user should check at least one parameter
29        on fit Panel window.
30 
31    """
32    def __init__(self,parent, page_info):
33        BasicPage.__init__(self, parent, page_info)
34        """
35            Initialization of the Panel
36        """
37        ## fit page does not content npts txtcrtl
38        self.npts=None
39        ## if no dispersity parameters is avaible
40        self.text_disp_1=None
41        ## default fitengine type
42        self.engine_type = None
43        ## draw sizer
44        self._fill_datainfo_sizer()
45        self._fill_model_sizer( self.sizer1)
46        self._fill_range_sizer() 
47        self._on_select_model(event=None)
48   
49        ## to update the panel according to the fit engine type selected
50        self.Bind(EVT_FITTER_TYPE,self._on_engine_change)
51   
52   
53    def _on_engine_change(self, event):
54        """
55            get an event containing the current name of the fit engine type
56            @param event: FitterTypeEvent containing  the name of the current engine
57        """
58        self.engine_type = event.type
59         
60        if len(self.parameters)==0:
61            return
62        for item in self.parameters:
63            if event.type =="scipy":
64                item[5].SetValue(format_number(""))
65                item[5].Hide()
66                item[6].SetValue(format_number(""))
67                item[6].Hide()
68                self.text2_min.Hide()
69                self.text2_max.Hide()
70            else:
71                item[5].Show(True)
72                item[6].Show(True)
73                self.text2_min.Show(True)
74                self.text2_max.Show(True)
75               
76        self.sizer3.Layout()
77        self.SetScrollbars(20,20,200,100)
78       
79   
80    def _fill_range_sizer(self):
81        """
82            Fill the sizer containing the plotting range
83            add  access to npts
84        """
85        sizer_fit = wx.GridSizer(1, 1,0, 0)
86   
87        self.btFit = wx.Button(self,wx.NewId(),'Fit')
88        self.btFit.Bind(wx.EVT_BUTTON, self._onFit,id= self.btFit.GetId())
89        self.btFit.SetToolTipString("Perform fit.")
90     
91       
92        sizer_fit.Add((5,5),1, wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 5)       
93        sizer_fit.Add(self.btFit,0, wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 5) 
94       
95        sizer_smearer = wx.BoxSizer(wx.HORIZONTAL)
96        #Filling the sizer containing instruments smearing info.
97        self.disable_smearer = wx.RadioButton(self, -1, 'No', style=wx.RB_GROUP)
98        self.enable_smearer = wx.RadioButton(self, -1, 'Yes')
99        self.Bind(wx.EVT_RADIOBUTTON, self.onSmear, id=self.disable_smearer.GetId())
100        self.Bind(wx.EVT_RADIOBUTTON, self.onSmear, id=self.enable_smearer.GetId())
101       
102        sizer_smearer.Add(wx.StaticText(self,-1,'Instrument Smearing? '))
103        sizer_smearer.Add((10, 10))
104        sizer_smearer.Add( self.enable_smearer )
105        sizer_smearer.Add((10,10))
106        sizer_smearer.Add( self.disable_smearer )
107       
108        #Display Chi^2/dof
109        sizer_smearer.Add((70,10))
110        box_description= wx.StaticBox(self, -1,'Chi2/dof')
111        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
112        boxsizer1.SetMinSize((60,-1))
113        self.tcChi    =  wx.StaticText(self, -1, "-", style=wx.ALIGN_LEFT)       
114        boxsizer1.Add( self.tcChi )   
115        sizer_smearer.Add( boxsizer1 )
116               
117        #Set sizer for Fitting section
118        self._set_range_sizer( title="Fitting",
119                               object1=sizer_smearer, object= sizer_fit)
120 
121       
122    def _fill_datainfo_sizer(self):
123        """
124            fill sizer 0 with data info
125        """
126        self.sizer0.Clear(True)
127        ## no loaded data , don't fill the sizer
128        if self.data== None:
129            self.sizer0.Layout()
130            return
131       
132        box_description= wx.StaticBox(self, -1, 'Data')
133        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
134        #----------------------------------------------------------
135        sizer_data = wx.GridSizer(3, 3,5, 5)
136        #Filling the sizer containing data related fields
137        DataSource  =wx.StaticText(self, -1,str(self.data.name))
138
139        sizer_data.Add(wx.StaticText(self, -1, 'Source Name : '))
140        sizer_data.Add(DataSource )
141        sizer_data.Add( (0,5) )
142       
143        #---------sizer 2 draw--------------------------------
144        #set maximum range for x in linear scale
145        if not hasattr(self.data,"data"): #Display only for 1D data fit
146            # Minimum value of data   
147            #data_min = str(format_number(numpy.min(self.data.x)))
148            data_min = str((numpy.min(self.data.x)))
149            # Maximum value of data 
150#            data_max = str(format_number(numpy.max(self.data.x)))
151            data_max = str((numpy.max(self.data.x)))
152            text4_3 = wx.StaticText(self, -1, 'Total Q Range (1/A)',
153                                     style=wx.ALIGN_LEFT)
154            sizer_data.Add( text4_3 )
155            sizer_data.Add(wx.StaticText(self, -1, "Min : %s"%data_min))
156           
157            sizer_data.Add(wx.StaticText(self, -1, "Max : %s"%data_max))
158           
159        else:
160            radius_min= 0
161            x= numpy.max(self.data.xmin, self.data.xmax)
162            y= numpy.max(self.data.ymin, self.data.ymax)
163            radius_max = math.sqrt(x*x + y*y)
164           
165            #For qmin and qmax, do not use format_number.(If do, qmin and max could be different from what is in the data.)
166            # Minimum value of data   
167            #data_min = str(format_number(radius_min))
168            data_min = str((radius_min))
169            # Maximum value of data 
170            #data_max = str(format_number(radius_max))
171            data_max = str((radius_max))
172            text4_3 = wx.StaticText(self, -1, 'Total Q Range (1/A)',
173                                     style=wx.ALIGN_LEFT)
174            sizer_data.Add( text4_3 )
175            sizer_data.Add(wx.StaticText(self, -1, "Min : %s"%data_min))
176            sizer_data.Add(wx.StaticText(self, -1, "Max : %s"%data_max))
177           
178        boxsizer1.Add(sizer_data)
179        #------------------------------------------------------------
180        self.sizer0.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
181        self.sizer0.Layout()
182       
183        self.qmin_x= data_min
184        self.qmax_x= data_max
185       
186       
187    def _fill_model_sizer(self, sizer):
188        """
189            fill sizer containing model info
190        """
191       
192        ## class base method  to add view 2d button   
193        self._set_model_sizer(sizer=sizer, title="Model",object=None )   
194       
195   
196    def _set_sizer_gaussian(self):
197        """
198            draw sizer with gaussian dispersity parameters
199        """
200        self.fittable_param=[]
201        self.fixed_param=[]
202        self.orientation_params=[]
203        self.sizer4_4.Clear(True)
204       
205        if self.model==None:
206            ##no model is selected
207            return
208        if not self.enable_disp.GetValue():
209            ## the user didn't select dispersity display
210            return 
211       
212        self._reset_dispersity()
213        # Create the dispersion objects
214        for item in self.model.dispersion.keys():
215            disp_model =  GaussianDispersion()
216            self._disp_obj_dict[item] = disp_model
217            self.model.set_dispersion(item, disp_model)
218
219        ix=0
220        iy=1
221        disp = wx.StaticText(self, -1, 'Names')
222        self.sizer4_4.Add(disp,( iy, ix),(1,1), 
223                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
224        ix += 1 
225        values = wx.StaticText(self, -1, 'Values')
226        self.sizer4_4.Add(values,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
227        ix +=2 
228        self.text_disp_1 = wx.StaticText(self, -1, 'Errors')
229        self.sizer4_4.Add( self.text_disp_1,(iy, ix),(1,1),\
230                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
231        self.text_disp_1.Hide()
232        ix += 1 
233        npts = wx.StaticText(self, -1, 'Npts')
234        self.sizer4_4.Add(npts,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
235        ix += 1 
236        nsigmas = wx.StaticText(self, -1, 'Nsigmas')
237        self.sizer4_4.Add(nsigmas,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
238       
239        for item in self.model.dispersion.keys():
240            if not item in self.model.orientation_params:
241                self.disp_cb_dict[item]= None
242                name1=item+".width"
243                name2=item+".npts"
244                name3=item+".nsigmas"
245                iy += 1
246                for p in self.model.dispersion[item].keys(): 
247       
248                    if p=="width":
249                        ix = 0
250                        cb = wx.CheckBox(self, -1, name1, (10, 10))
251                        wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
252                        self.sizer4_4.Add( cb,( iy, ix),(1,1), 
253                                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
254                        ix = 1
255                        value= self.model.getParam(name1)
256                        ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
257                                            style=wx.TE_PROCESS_ENTER)
258                        ctl1.SetValue(str (format_number(value)))
259                        ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
260                        ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
261                        ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
262                        self.sizer4_4.Add(ctl1, (iy,ix),(1,1),wx.EXPAND)
263                        ## text to show error sign
264                        ix = 2
265                        text2=wx.StaticText(self, -1, '+/-')
266                        self.sizer4_4.Add(text2,(iy, ix),(1,1),
267                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
268                        text2.Hide() 
269                        ## txtcrtl to add error from fit
270                        ix = 3
271                        ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
272                        self.sizer4_4.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
273                        ctl2.Hide()
274                        self.fittable_param.append([cb,name1,ctl1,text2,
275                                                    ctl2, None, None,None])
276                    elif p=="npts":
277                            ix = 4
278                            value= self.model.getParam(name2)
279                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
280                                                style=wx.TE_PROCESS_ENTER)
281                           
282                            Tctl.SetValue(str (format_number(value)))
283                            Tctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
284                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
285                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
286                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
287                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
288                            self.fixed_param.append([None,name2, Tctl,None,None,
289                                                      None, None,None])
290                    elif p=="nsigmas":
291                            ix = 5
292                            value= self.model.getParam(name3)
293                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
294                                                style=wx.TE_PROCESS_ENTER)
295                            Tctl.SetValue(str (format_number(value)))
296                            Tctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
297                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
298                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
299                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
300                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
301                            ix +=1
302                            self.sizer4_4.Add((20,20), (iy,ix),(1,1),
303                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
304                           
305                            self.fixed_param.append([None,name3, Tctl
306                                                     ,None,None, None, None,None])
307        ix =0
308        iy +=1 
309        self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
310        for item in self.model.dispersion.keys():
311            if  item in self.model.orientation_params:
312                self.disp_cb_dict[item]= None
313                name1=item+".width"
314                name2=item+".npts"
315                name3=item+".nsigmas"
316                iy += 1
317                for p in self.model.dispersion[item].keys(): 
318       
319                    if p=="width":
320                        ix = 0
321                        cb = wx.CheckBox(self, -1, name1, (10, 10))
322                        wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
323                        self.sizer4_4.Add( cb,( iy, ix),(1,1), 
324                                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
325                        if self.data.__class__.__name__ =="Data2D":
326                            cb.Enable()
327                        else:
328                            cb.Disable()
329                        ix = 1
330                        value= self.model.getParam(name1)
331                        ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
332                                            style=wx.TE_PROCESS_ENTER)
333                        ctl1.SetValue(str (format_number(value)))
334                        if self.data.__class__.__name__ =="Data2D":
335                            ctl1.Enable()
336                        else:
337                            ctl1.Disable()
338                        ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
339                        ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
340                        ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
341                        self.sizer4_4.Add(ctl1, (iy,ix),(1,1),wx.EXPAND)
342                        ## text to show error sign
343                        ix = 2
344                        text2=wx.StaticText(self, -1, '+/-')
345                        self.sizer4_4.Add(text2,(iy, ix),(1,1),
346                                          wx.EXPAND|wx.ADJUST_MINSIZE, 0)
347                        text2.Hide() 
348                        ## txtcrtl to add error from fit
349                        ix = 3
350                        ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
351                        self.sizer4_4.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
352                        ctl2.Hide()
353                        if self.data.__class__.__name__ =="Data2D":
354                            ctl2.Enable()
355                        else:
356                            ctl2.Disable()
357                        self.fittable_param.append([cb,name1,ctl1,text2,
358                                                    ctl2, None, None,None])
359                        self.orientation_params.append([cb,name1,ctl1,text2,
360                                                    ctl2, None, None,None])
361                    elif p=="npts":
362                            ix = 4
363                            value= self.model.getParam(name2)
364                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
365                                                style=wx.TE_PROCESS_ENTER)
366                           
367                            Tctl.SetValue(str (format_number(value)))
368                            if self.data.__class__.__name__ =="Data2D":
369                                Tctl.Enable()
370                            else:
371                                Tctl.Disable()
372                            Tctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
373                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
374                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
375                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
376                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
377                            self.fixed_param.append([None,name2, Tctl,None,None,
378                                                      None, None,None])
379                            self.orientation_params.append([None,name2, Tctl,None,None,
380                                                      None, None,None])
381                    elif p=="nsigmas":
382                            ix = 5
383                            value= self.model.getParam(name3)
384                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20),
385                                                style=wx.TE_PROCESS_ENTER)
386                            Tctl.SetValue(str (format_number(value)))
387                            if self.data.__class__.__name__ =="Data2D":
388                                Tctl.Enable()
389                            else:
390                                Tctl.Disable()
391                            Tctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
392                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
393                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
394                            self.sizer4_4.Add(Tctl, (iy,ix),(1,1),
395                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
396                            ix +=1
397                            self.sizer4_4.Add((20,20), (iy,ix),(1,1),
398                                               wx.EXPAND|wx.ADJUST_MINSIZE, 0)
399                            self.fixed_param.append([None,name3, Tctl
400                                                     ,None,None, None, None,None])   
401                            self.orientation_params.append([None,name3, Tctl
402                                                     ,None,None, None, None,None]) 
403                                 
404        wx.PostEvent(self.parent, StatusEvent(status=\
405                        " Selected Distribution: Gaussian"))   
406        ix =0
407        iy +=1 
408        self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)       
409        self.sizer4_4.Layout()
410        self.sizer4.Layout()
411        self.SetScrollbars(20,20,200,100)
412     
413       
414    def _onFit(self, event):     
415        """
416            Allow to fit
417        """
418        #self.btFit.SetLabel("Stop")
419        from sans.guiframe.utils import check_value
420        flag = check_value( self.qmin, self.qmax) 
421       
422        if not flag:
423            msg= "Fitting range invalid"
424            wx.PostEvent(self.parent.parent, StatusEvent(status= msg ))
425            return 
426       
427        if len(self.param_toFit) <= 0:
428            msg= "Select at least one parameter to fit"
429            wx.PostEvent(self.parent.parent, StatusEvent(status= msg ))
430            return 
431       
432        self.qmin_x=float(self.qmin.GetValue())
433        self.qmax_x =float( self.qmax.GetValue())
434        self.manager._reset_schedule_problem( value=0)
435        self.manager.schedule_for_fit( value=1,page=self,fitproblem =None) 
436        self.manager.set_fit_range(page= self,qmin= self.qmin_x, qmax= self.qmax_x)
437        #single fit
438        self.manager.onFit()
439           
440        self.sizer5.Layout()
441        self.SetScrollbars(20,20,55,40)
442       
443       
444    def _on_select_model(self, event): 
445        """
446             call back for model selection
447        """   
448        self._on_select_model_helper() 
449        self.set_model_param_sizer(self.model)
450        try:
451            self.compute_chisqr()
452        except:
453            ## error occured on chisqr computation
454            pass
455        self.enable_disp.SetValue(False)
456        self.disable_disp.SetValue(True)
457        self._set_dipers_Param(event=None)
458       
459        evt = ModelEventbox(model=self.model)
460        wx.PostEvent(self.event_owner, evt)   
461       
462
463    def _onparamEnter(self,event):
464        """
465            when enter value on panel redraw model according to changed
466        """
467        tcrtl= event.GetEventObject()
468        if check_float(tcrtl):
469            self._onparamEnter_helper()
470            self.compute_chisqr()
471        else:
472            msg= "Cannot Plot :Must enter a number!!!  "
473            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
474            return 
475       
476    def reset_page(self, state):
477        """
478            reset the state
479        """
480        self.reset_page_helper(state)
481        evt = ModelEventbox(model=self.model)
482        wx.PostEvent(self.event_owner, evt)   
483           
484           
485    def get_range(self):
486        """
487            return the fitting range
488        """
489        return float(self.qmin_x) , float(self.qmax_x)
490       
491    def get_param_list(self):
492        """
493            @return self.param_toFit: list containing  references to TextCtrl
494            checked.Theses TextCtrl will allow reference to parameters to fit.
495            @raise: if return an empty list of parameter fit will nnote work
496            properly so raise ValueError,"missing parameter to fit"
497        """
498        if self.param_toFit !=[]:
499            return self.param_toFit
500        else:
501            raise ValueError,"missing parameter to fit"   
502     
503    def onsetValues(self,chisqr, out,cov):
504        """
505            Build the panel from the fit result
506            @param chisqr:Value of the goodness of fit metric
507            @param out:list of parameter with the best value found during fitting
508            @param cov:Covariance matrix
509       
510        """
511        self.tcChi.SetLabel(format_number(chisqr))
512        params = {}
513        is_modified = False
514        has_error = False
515        self.text2_3.Hide()
516        if self.text_disp_1 !=None:
517            self.text_disp_1.Hide()
518        #set the panel when fit result are float not list
519        if out.__class__==numpy.float64:
520            self.param_toFit[0][2].SetValue(format_number(out))
521            self.param_toFit[0][2].Refresh()
522           
523            self.param_toFit[0][4].Clear()
524            self.param_toFit[0][4].Hide()
525            if cov !=None :
526                self.text2_3.Show(True)
527                if self.text_disp_1 !=None:
528                    self.text_disp_1.Show(True)
529                if cov[0]==None: 
530                    self.param_toFit[0][3].Hide()
531                    self.param_toFit[0][4].Clear()
532                    self.param_toFit[0][4].Hide()
533                    self.param_toFit[0][4].Refresh()
534                else:
535                    self.param_toFit[0][3].Show(True)
536                    self.param_toFit[0][4].Clear()
537                    self.param_toFit[0][4].SetValue(format_number(cov[0]))
538                    self.param_toFit[0][4].Show(True)
539                    self.param_toFit[0][4].Refresh()
540        else:
541            i=0
542            j=0
543            #Set the panel when fit result are list
544            for item in self.param_toFit:
545                ## reset error value to initial state
546                item[4].Clear()
547                item[4].Hide()
548                item[4].Refresh()
549                if( out != None ) and len(out)<=len(self.param_toFit)and i < len(out):
550                    item[2].SetValue(format_number(self.model.getParam(item[1])))
551                    item[2].Refresh()
552                if(cov !=None)and len(cov)<=len(self.param_toFit)and i < len(cov):
553                    self.text2_3.Show(True) 
554                    if self.text_disp_1!=None:
555                        self.text_disp_1.Show(True)
556                    item[3].Show(True)
557                    item[4].Clear()
558                    for j in range(len(out)):
559                        if out[j]==self.model.getParam(item[1]):
560                            break
561                    ## unable to compare cov[j]==numpy.nan so switch to None
562                    if cov[j]==None:
563                        item[3].Hide()
564                        item[4].Refresh()
565                        item[4].Clear()
566                        item[4].Hide()
567                    else:
568                        item[4].SetValue(format_number(cov[j]))
569                        item[4].Refresh()
570                        item[4].Show(True)   
571                i+=1
572       
573        self.sizer3.Layout()
574        self.sizer4.Layout()
575        self.SetScrollbars(20,20,200,100)
576       
577       
578     
579    def onSmear(self, event):
580        """
581            Create a smear object that will change the way residuals
582            are compute when fitting
583        """
584        smear =None
585        msg=""
586        if self.enable_smearer.GetValue():
587            from DataLoader.qsmearing import smear_selection
588            smear = smear_selection( self.data )
589            if hasattr(self.data,"dxl"):
590                msg= ": Resolution smearing parameters"
591            if hasattr(self.data,"dxw"):
592                msg= ": Slit smearing parameters"
593            if smear ==None:
594                wx.PostEvent(self.manager.parent, StatusEvent(status=\
595                            "Data contains no smearing information"))
596            else:
597                wx.PostEvent(self.manager.parent, StatusEvent(status=\
598                            "Data contains smearing information %s"%msg))
599        ## set smearing value whether or not the data contain the smearing info
600        self.manager.set_smearer(smear, qmin= float(self.qmin_x),
601                                      qmax= float(self.qmax_x))   
602        ## save the state enable smearing
603        self.save_current_state()
604       
605 
606    def compute_chisqr2D(self):
607        """
608            compute chi square given a model and data 2D and set the value
609            to the tcChi txtcrl
610        """
611        from sans.guiframe.utils import check_value
612        flag = check_value( self.qmin, self.qmax)
613        err_image = self.data.err_data
614        if err_image==[] or err_image==None:
615            err_image= numpy.zeros(len(self.data.x_bins),len(self.data.y_bins))
616                       
617        err_image[err_image==0]=1
618        res=[]
619        if flag== True:
620            try:
621                self.qmin_x = float(self.qmin.GetValue())
622                self.qmax_x = float(self.qmax.GetValue())
623                for i in range(len(self.data.x_bins)):
624                    for j in range(len(self.data.y_bins)):
625                        #Check the range containing data between self.qmin_x and self.qmax_x
626                        value =  math.pow(self.data.x_bins[i],2)+ math.pow(self.data.y_bins[j],2)
627                        if value >= math.pow(self.qmin_x,2) and value <= math.pow(self.qmax_x,2):
628                           
629                            temp = [self.data.x_bins[i],self.data.y_bins[j]]
630                            error= err_image[j][i]
631                            chisqrji = (self.data.data[j][i]- self.model.runXY(temp ))/error
632                            #Vector containing residuals
633                            res.append( math.pow(chisqrji,2) )
634
635                # compute sum of residual
636                sum=0
637                for item in res:
638                    if numpy.isfinite(item):
639                        sum +=item
640                self.tcChi.SetLabel(format_number(math.fabs(sum/ len(res))))
641            except:
642                wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
643                            "Chisqr cannot be compute: %s"% sys.exc_value))
644                return
645   
646       
647    def compute_chisqr(self):
648        """
649            compute chi square given a model and data 1D and set the value
650            to the tcChi txtcrl
651        """
652        from sans.guiframe.utils import check_value
653        flag = check_value( self.qmin, self.qmax)
654       
655        if flag== True:
656            try:
657                if hasattr(self.data,"data"):
658                    self.compute_chisqr2D()
659                    return
660                else:
661                    self.qmin_x = float(self.qmin.GetValue())
662                    self.qmax_x = float(self.qmax.GetValue())
663                    # return residuals within self.qmin_x and self.qmax_x
664                    x,y = [numpy.asarray(v) for v in (self.data.x,self.data.y)]
665                   
666                    if self.data.dy==None:
667                        dy= numpy.zeros(len(y))
668                    else:
669                        dy= numpy.asarray(self.data.dy)
670                    dy[dy==0]=1
671                    if self.qmin_x==None and self.qmax_x==None: 
672                        fx =numpy.asarray([self.model.run(v) for v in x])
673                        temp=(y - fx)/dy
674                        res= temp*temp
675                    else:
676                        idx = (x>= self.qmin_x) & (x <=self.qmax_x)
677                        fx = numpy.asarray([self.model.run(item)for item in x[idx ]])
678                        temp=(y[idx] - fx)/dy[idx]
679                        res= temp*temp
680                    #sum of residuals
681                    sum=0
682                    for item in res:
683                        if numpy.isfinite(item):
684                            sum +=item
685                    self.tcChi.SetLabel(format_number(math.fabs(sum/ len(res))))
686            except:
687                wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
688                            "Chisqr cannot be compute: %s"% sys.exc_value))
689                return 
690           
691   
692    def select_all_param(self,event): 
693        """
694             set to true or false all checkBox given the main checkbox value cb1
695        """
696        self.param_toFit=[]
697       
698        if  self.parameters !=[]:
699            if  self.cb1.GetValue()==True:
700                for item in self.parameters:
701                    item[0].SetValue(True)
702                    self.param_toFit.append(item )
703                if len(self.fittable_param)>0:
704                    for item in self.fittable_param:
705                        item[0].SetValue(True)
706                        self.param_toFit.append(item )
707            else:
708                for item in self.parameters:
709                    item[0].SetValue(False)
710                for item in self.fittable_param:
711                    item[0].SetValue(False)
712                self.param_toFit=[]
713        self.save_current_state() 
714       
715               
716               
717    def select_param(self,event):
718        """
719            Select TextCtrl  checked for fitting purpose and stores them
720            in  self.param_toFit=[] list
721        """
722        self.param_toFit=[]
723        for item in self.parameters:
724            #Select parameters to fit for list of primary parameters
725            if item[0].GetValue()==True:
726                if not (item in self.param_toFit):
727                    self.param_toFit.append(item ) 
728            else:
729                #remove parameters from the fitting list
730                if item in self.param_toFit:
731                    self.param_toFit.remove(item)
732        #Select parameters to fit for list of fittable parameters with dispersion         
733        for item in self.fittable_param:
734            if item[0].GetValue()==True:
735                if not (item in self.param_toFit):
736                    self.param_toFit.append(item) 
737            else:
738                #remove parameters from the fitting list
739                if item in self.param_toFit:
740                    self.param_toFit.remove(item)           
741        #Set the value of checkbox that selected every checkbox or not           
742        if len(self.parameters)+len(self.fittable_param) ==len(self.param_toFit):
743            self.cb1.SetValue(True)
744        else:
745            self.cb1.SetValue(False)
746        ## save current state of the page
747        self.save_current_state()
748       
749   
750       
751    def set_model_param_sizer(self, model):
752        """
753            Build the panel from the model content
754            @param model: the model selected in combo box for fitting purpose
755        """
756        self.sizer3.Clear(True)
757        self.parameters = []
758        self.param_toFit=[]
759        self.fittable_param=[]
760        self.fixed_param=[]
761        self.orientation_params=[]
762       
763        if model ==None:
764            self.sizer3.Layout()
765            self.SetScrollbars(20,20,200,100)
766            return
767        ## the panel is drawn using the current value of the fit engine
768        if self.engine_type==None and self.manager !=None:
769            self.engine_type= self.manager._return_engine_type()
770           
771        box_description= wx.StaticBox(self, -1,str("Model Parameters"))
772        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
773        sizer = wx.GridBagSizer(5,5)
774        ## save the current model
775        self.model = model
776           
777        keys = self.model.getParamList()
778        #list of dispersion paramaters
779        self.disp_list=self.model.getDispParamList()
780       
781        keys.sort()
782   
783        iy = 1
784        ix = 0
785        self.cb1 = wx.CheckBox(self, -1,"Select all", (10, 10))
786        wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param)
787        self.cb1.SetValue(False)
788       
789        sizer.Add(self.cb1,(iy, ix),(1,1),\
790                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
791        ix +=1
792        self.text2_2 = wx.StaticText(self, -1, 'Values')
793        sizer.Add(self.text2_2,(iy, ix),(1,1),\
794                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
795        ix +=2 
796        self.text2_3 = wx.StaticText(self, -1, 'Errors')
797        sizer.Add(self.text2_3,(iy, ix),(1,1),\
798                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
799        self.text2_3.Hide()
800        ix +=1 
801        self.text2_min = wx.StaticText(self, -1, 'Min')
802        sizer.Add(self.text2_min,(iy, ix),(1,1),\
803                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
804        self.text2_min.Hide()
805        ix +=1 
806        self.text2_max = wx.StaticText(self, -1, 'Max')
807        sizer.Add(self.text2_max,(iy, ix),(1,1),\
808                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
809        self.text2_max.Hide()
810        ix += 1
811        self.text2_4 = wx.StaticText(self, -1, '[Units]')
812        sizer.Add(self.text2_4,(iy, ix),(1,1),\
813                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
814        self.text2_4.Hide()
815        if self.engine_type=="park":
816            self.text2_max.Show(True)
817            self.text2_min.Show(True)
818
819        for item in keys:
820            if not item in self.disp_list and not item in self.model.orientation_params:
821                iy += 1
822                ix = 0
823                ## add parameters name with checkbox for selecting to fit
824                cb = wx.CheckBox(self, -1, item )
825                cb.SetValue(False)
826                wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
827                sizer.Add( cb,( iy, ix),(1,1),
828                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
829                ## add parameter value
830                ix += 1
831                value= self.model.getParam(item)
832                ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
833                                    style=wx.TE_PROCESS_ENTER)
834               
835                ctl1.SetValue(format_number(value))
836                ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
837                ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
838                ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
839                sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
840                ## text to show error sign
841                ix += 1
842                text2=wx.StaticText(self, -1, '+/-')
843                sizer.Add(text2,(iy, ix),(1,1),\
844                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
845                text2.Hide() 
846                ## txtcrtl to add error from fit
847                ix += 1
848                ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
849                sizer.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
850                ctl2.Hide()
851               
852                param_min, param_max= self.model.details[item][1:]
853                ix += 1
854                ctl3 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
855                ctl3.SetValue(format_number(param_min))
856                ctl3.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
857                ctl3.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
858                ctl3.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
859                sizer.Add(ctl3, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
860                ctl3.Hide()
861       
862                ix += 1
863                ctl4 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
864                ctl4.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
865                ctl4.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
866                ctl4.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
867                sizer.Add(ctl4, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
868                ctl4.SetValue(format_number(param_max))
869                ctl4.Hide()
870               
871                if self.engine_type=="park":
872                    ctl3.Show(True)
873                    ctl4.Show(True)
874                   
875                ix +=1
876                # Units
877                try:
878                    units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
879                except:
880                    units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
881                sizer.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
882               
883                ##[cb state, name, value, "+/-", error of fit, min, max , units]
884                self.parameters.append([cb,item, ctl1,
885                                        text2,ctl2, ctl3, ctl4,None])
886             
887        iy+=1
888        sizer.Add((10,10),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
889        for item in self.model.orientation_params:
890            if not item in self.disp_list :
891                iy += 1
892                ix = 0
893                ## add parameters name with checkbox for selecting to fit
894                cb = wx.CheckBox(self, -1, item )
895                cb.SetValue(False)
896                wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
897                if self.data.__class__.__name__ =="Data2D":
898                    cb.Enable()
899                else:
900                    cb.Disable()
901                sizer.Add( cb,( iy, ix),(1,1),
902                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
903                ## add parameter value
904                ix += 1
905                value= self.model.getParam(item)
906                ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
907                                    style=wx.TE_PROCESS_ENTER)
908               
909                ctl1.SetValue(format_number(value))
910                if self.data.__class__.__name__ =="Data2D":
911                    ctl1.Enable()
912                else:
913                    ctl1.Disable()
914                ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
915                ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
916                ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
917                sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
918                ## text to show error sign
919                ix += 1
920                text2=wx.StaticText(self, -1, '+/-')
921                sizer.Add(text2,(iy, ix),(1,1),\
922                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
923                text2.Hide() 
924                ## txtcrtl to add error from fit
925                ix += 1
926                ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
927                sizer.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
928                ctl2.Hide()
929                if self.data.__class__.__name__ =="Data2D":
930                    ctl1.Enable()
931                else:
932                    ctl1.Disable()
933                param_min, param_max= self.model.details[item][1:]
934                ix += 1
935                ctl3 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
936                ctl3.SetValue(format_number(param_min))
937                ctl3.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
938                ctl3.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
939                ctl3.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
940                sizer.Add(ctl3, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
941                ctl3.Hide()
942                if self.data.__class__.__name__ =="Data2D":
943                    ctl3.Enable()
944                else:
945                    ctl3.Disable()
946       
947                ix += 1
948                ctl4 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
949                ctl4.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
950                ctl4.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
951                ctl4.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
952                sizer.Add(ctl4, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
953                ctl4.SetValue(format_number(param_max))
954                ctl4.Hide()
955                if self.data.__class__.__name__ =="Data2D":
956                    ctl4.Enable()
957                else:
958                    ctl4.Disable()
959                if self.engine_type=="park":
960                    ctl3.Show(True)
961                    ctl4.Show(True)
962                   
963                ix +=1
964                # Units
965                try:
966                    units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
967                except:
968                    units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
969                sizer.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
970               
971                ##[cb state, name, value, "+/-", error of fit, min, max , units]
972                self.parameters.append([cb,item, ctl1,
973                                        text2,ctl2, ctl3, ctl4,None])
974                self.orientation_params.append([cb,item, ctl1,
975                                        text2,ctl2, ctl3, ctl4,None])
976             
977        iy+=1
978        sizer.Add((10,10),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
979       
980        #Display units text on panel
981        for item in keys:   
982            if self.model.details[item][0]!='':
983                self.text2_4.Show()
984                break
985            else:
986                self.text2_4.Hide()
987   
988        boxsizer1.Add(sizer)
989       
990        self.sizer3.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
991        self.sizer3.Layout()
992        self.SetScrollbars(20,20,200,100)
993       
994   
995           
996       
997class HelpWindow(wx.Frame):
998    def __init__(self, parent, id, title):
999        wx.Frame.__init__(self, parent, id, title, size=(570, 400))
1000       
1001        from sans.models.CylinderModel import CylinderModel
1002        model = CylinderModel()
1003       
1004        from danse.common.plottools.plottables import Data1D
1005        data= Data1D(x=[1,2], y=[3,4], dy=[0.1, 0,1])
1006   
1007        from fitpanel import PageInfo
1008        myinfo = PageInfo(self,  model, data=data )
1009       
1010        ## add data
1011       
1012        from models import ModelList
1013        mylist= ModelList()
1014
1015        from sans.models.SphereModel import SphereModel
1016        from sans.models.SquareWellStructure import SquareWellStructure
1017        from sans.models.DebyeModel import DebyeModel
1018        from sans.models.LineModel import LineModel
1019        name= "shapes"
1020        list1= [SphereModel]
1021        mylist.set_list( name, list1)
1022       
1023        name= "Shape-independent"
1024        list1= [DebyeModel]
1025        mylist.set_list( name, list1)
1026       
1027        name= "Structure Factors"
1028        list1= [SquareWellStructure]
1029        mylist.set_list( name, list1)
1030       
1031        name= "Added models"
1032        list1= [LineModel]
1033        mylist.set_list( name, list1)
1034       
1035        myinfo.model_list_box = mylist.get_list()
1036       
1037        self.page = FitPage(self, myinfo) 
1038       
1039       
1040       
1041        self.Centre()
1042        self.Show(True)
1043
1044
1045   
1046if __name__=="__main__":
1047    app = wx.App()
1048    HelpWindow(None, -1, 'HelpWindow')
1049    app.MainLoop()
1050               
Note: See TracBrowser for help on using the repository browser.