source: sasview/sansview/perspectives/fitting/fitpage.py @ 882a912

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

fitting model with 2 different plot

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