source: sasview/sansview/perspectives/fitting/fitpage.py @ 3fef0a8

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

fitting for parameters orientation disable

  • Property mode set to 100644
File size: 48.5 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    def reset_page(self, state):
533        """
534            reset the state
535        """
536        self.reset_page_helper(state)
537        evt = ModelEventbox(model=self.model)
538        wx.PostEvent(self.event_owner, evt)   
539           
540           
541    def get_range(self):
542        """
543            return the fitting range
544        """
545        return float(self.qmin_x) , float(self.qmax_x)
546       
547    def get_param_list(self):
548        """
549            @return self.param_toFit: list containing  references to TextCtrl
550            checked.Theses TextCtrl will allow reference to parameters to fit.
551            @raise: if return an empty list of parameter fit will nnote work
552            properly so raise ValueError,"missing parameter to fit"
553        """
554        if self.param_toFit !=[]:
555            return self.param_toFit
556        else:
557            raise ValueError,"missing parameter to fit"   
558     
559    def onsetValues(self,chisqr, out,cov):
560        """
561            Build the panel from the fit result
562            @param chisqr:Value of the goodness of fit metric
563            @param out:list of parameter with the best value found during fitting
564            @param cov:Covariance matrix
565       
566        """
567        self.tcChi.SetLabel(format_number(chisqr))
568        params = {}
569        is_modified = False
570        has_error = False
571        self.text2_3.Hide()
572        if self.text_disp_1 !=None:
573            self.text_disp_1.Hide()
574        #set the panel when fit result are float not list
575        if out.__class__==numpy.float64:
576            self.param_toFit[0][2].SetValue(format_number(out))
577            self.param_toFit[0][2].Refresh()
578           
579            self.param_toFit[0][4].Clear()
580            self.param_toFit[0][4].Hide()
581            if cov !=None :
582                self.text2_3.Show(True)
583                if self.text_disp_1 !=None:
584                    self.text_disp_1.Show(True)
585                if cov[0]==None: 
586                    self.param_toFit[0][3].Hide()
587                    self.param_toFit[0][4].Clear()
588                    self.param_toFit[0][4].Hide()
589                    self.param_toFit[0][4].Refresh()
590                else:
591                    self.param_toFit[0][3].Show(True)
592                    self.param_toFit[0][4].Clear()
593                    self.param_toFit[0][4].SetValue(format_number(cov[0]))
594                    self.param_toFit[0][4].Show(True)
595                    self.param_toFit[0][4].Refresh()
596        else:
597            i=0
598            j=0
599            #Set the panel when fit result are list
600            for item in self.param_toFit:
601                ## reset error value to initial state
602                item[4].Clear()
603                item[4].Hide()
604                item[4].Refresh()
605                if( out != None ) and len(out)<=len(self.param_toFit)and i < len(out):
606                    item[2].SetValue(format_number(self.model.getParam(item[1])))
607                    item[2].Refresh()
608                if(cov !=None)and len(cov)<=len(self.param_toFit)and i < len(cov):
609                    self.text2_3.Show(True) 
610                    if self.text_disp_1!=None:
611                        self.text_disp_1.Show(True)
612                    item[3].Show(True)
613                    item[4].Clear()
614                    for j in range(len(out)):
615                        if out[j]==self.model.getParam(item[1]):
616                            break
617                    ## unable to compare cov[j]==numpy.nan so switch to None
618                    if cov[j]==None:
619                        item[3].Hide()
620                        item[4].Refresh()
621                        item[4].Clear()
622                        item[4].Hide()
623                    else:
624                        item[4].SetValue(format_number(cov[j]))
625                        item[4].Refresh()
626                        item[4].Show(True)   
627                i+=1
628       
629        self.sizer3.Layout()
630        self.sizer4.Layout()
631        self.SetScrollbars(20,20,200,100)
632       
633       
634    def onSmear(self, event):
635        """
636            Create a smear object that will change the way residuals
637            are compute when fitting
638        """
639        temp_smearer = None
640        if self.enable_smearer.GetValue():
641            msg=""
642            temp_smearer= self.smearer
643            if hasattr(self.data,"dxl"):
644                msg= ": Resolution smearing parameters"
645            if hasattr(self.data,"dxw"):
646                msg= ": Slit smearing parameters"
647            if self.smearer ==None:
648                wx.PostEvent(self.manager.parent, StatusEvent(status=\
649                            "Data contains no smearing information"))
650            else:
651                wx.PostEvent(self.manager.parent, StatusEvent(status=\
652                            "Data contains smearing information %s"%msg))
653       
654        ## set smearing value whether or not the data contain the smearing info
655        self.manager.set_smearer(smearer=temp_smearer, qmin= float(self.qmin_x),
656                                      qmax= float(self.qmax_x)) 
657        ##Calculate chi2
658        self.compute_chisqr(smearer= temp_smearer) 
659        ## save the state enable smearing
660        self.save_current_state()
661       
662         
663   
664       
665 
666    def compute_chisqr2D(self):
667        """
668            compute chi square given a model and data 2D and set the value
669            to the tcChi txtcrl
670        """
671        from sans.guiframe.utils import check_value
672        flag = check_value( self.qmin, self.qmax)
673       
674        err_image = copy.deepcopy(self.data.err_data)
675        if err_image==[] or err_image==None:
676            err_image= numpy.zeros(len(self.data.x_bins),len(self.data.y_bins))
677                       
678        err_image[err_image==0]=1
679       
680        res=[]
681        if flag== True:
682            try:
683                self.qmin_x = float(self.qmin.GetValue())
684                self.qmax_x = float(self.qmax.GetValue())
685                for i in range(len(self.data.x_bins)):
686                    for j in range(len(self.data.y_bins)):
687                        #Check the range containing data between self.qmin_x and self.qmax_x
688                        value =  math.pow(self.data.x_bins[i],2)+ math.pow(self.data.y_bins[j],2)
689                        if value >= math.pow(self.qmin_x,2) and value <= math.pow(self.qmax_x,2):
690                           
691                            temp = [self.data.x_bins[i],self.data.y_bins[j]]
692                            error= err_image[j][i]
693                            chisqrji = (self.data.data[j][i]- self.model.runXY(temp ))/error
694                            #Vector containing residuals
695                            res.append( math.pow(chisqrji,2) )
696
697                # compute sum of residual
698                sum=0
699                for item in res:
700                    if numpy.isfinite(item):
701                        sum +=item
702                self.tcChi.SetLabel(format_number(math.fabs(sum/ len(res))))
703            except:
704                wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
705                            "Chisqr cannot be compute: %s"% sys.exc_value))
706                return
707   
708       
709    def compute_chisqr(self , smearer=None):
710        """
711            compute chi square given a model and data 1D and set the value
712            to the tcChi txtcrl
713        """
714        from sans.guiframe.utils import check_value
715        flag = check_value( self.qmin, self.qmax)
716       
717        if flag== True:
718            try:
719                if hasattr(self.data,"data"):
720                    self.compute_chisqr2D()
721                    return
722                else:
723                    self.qmin_x = float(self.qmin.GetValue())
724                    self.qmax_x = float(self.qmax.GetValue())
725                    # return residuals within self.qmin_x and self.qmax_x
726                    x,y = [numpy.asarray(v) for v in (self.data.x,self.data.y)]
727                   
728                    if self.data.dy==None:
729                        dy= numpy.zeros(len(y))
730                    else:
731                        dy= copy.deepcopy(self.data.dy)
732                        dy= numpy.asarray(dy)
733                    dy[dy==0]=1
734                   
735                    if self.qmin_x==None and self.qmax_x==None: 
736                        fx =numpy.asarray([self.model.run(v) for v in x])
737                        if smearer!=None:
738                            fx= smearer(fx)
739                        temp=(y - fx)/dy
740                        res= temp*temp
741                    else:
742                        idx = (x>= self.qmin_x) & (x <=self.qmax_x)
743                        fx = numpy.asarray([self.model.run(item)for item in x[idx ]])
744                        if smearer!=None:
745                            fx= smearer(fx)
746                        temp=(y[idx] - fx)/dy[idx]
747                        res= temp*temp
748                    #sum of residuals
749                    sum=0
750                    for item in res:
751                        if numpy.isfinite(item):
752                            sum +=item
753                    self.tcChi.SetLabel(format_number(math.fabs(sum/ len(res))))
754            except:
755                wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
756                            "Chisqr cannot be compute: %s"% sys.exc_value))
757                return 
758           
759   
760    def select_all_param(self,event): 
761        """
762             set to true or false all checkBox given the main checkbox value cb1
763        """           
764
765        self.param_toFit=[]
766        if  self.parameters !=[]:
767            if  self.cb1.GetValue():
768                for item in self.parameters:
769                    ## for data2D select all to fit
770                    if self.data.__class__.__name__=="Data2D":
771                        item[0].SetValue(True)
772                        self.param_toFit.append(item )
773                    else:
774                        ## for 1D all parameters except orientation
775                        if not item in self.orientation_params:
776                            item[0].SetValue(True)
777                            self.param_toFit.append(item )
778                if len(self.fittable_param)>0:
779                    for item in self.fittable_param:
780                        if self.data.__class__.__name__=="Data2D":
781                            item[0].SetValue(True)
782                            self.param_toFit.append(item )
783                        else:
784                            ## for 1D all parameters except orientation
785                            if not item in self.orientation_params:
786                                item[0].SetValue(True)
787                                self.param_toFit.append(item )
788            else:
789                for item in self.parameters:
790                    item[0].SetValue(False)
791                for item in self.fittable_param:
792                    item[0].SetValue(False)
793                self.param_toFit=[]
794               
795        self.save_current_state() 
796       
797               
798               
799    def select_param(self,event):
800        """
801            Select TextCtrl  checked for fitting purpose and stores them
802            in  self.param_toFit=[] list
803        """
804        self.param_toFit=[]
805        for item in self.parameters:
806            #Select parameters to fit for list of primary parameters
807            if item[0].GetValue():
808                if not (item in self.param_toFit):
809                    self.param_toFit.append(item ) 
810            else:
811                #remove parameters from the fitting list
812                if item in self.param_toFit:
813                    self.param_toFit.remove(item)
814        #Select parameters to fit for list of fittable parameters with dispersion         
815        for item in self.fittable_param:
816            if item[0].GetValue():
817                if not (item in self.param_toFit):
818                    self.param_toFit.append(item) 
819            else:
820                #remove parameters from the fitting list
821                if item in self.param_toFit:
822                    self.param_toFit.remove(item)           
823        #Set the value of checkbox that selected every checkbox or not           
824        if len(self.parameters)+len(self.fittable_param) ==len(self.param_toFit):
825            self.cb1.SetValue(True)
826        else:
827            self.cb1.SetValue(False)
828        ## save current state of the page
829        self.save_current_state()
830       
831   
832       
833    def set_model_param_sizer(self, model):
834        """
835            Build the panel from the model content
836            @param model: the model selected in combo box for fitting purpose
837        """
838        self.sizer3.Clear(True)
839        self.parameters = []
840        self.param_toFit=[]
841        self.fittable_param=[]
842        self.fixed_param=[]
843        self.orientation_params=[]
844        self.orientation_params_disp=[]
845       
846        if model ==None:
847            self.sizer3.Layout()
848            self.SetScrollbars(20,20,200,100)
849            return
850        ## the panel is drawn using the current value of the fit engine
851        if self.engine_type==None and self.manager !=None:
852            self.engine_type= self.manager._return_engine_type()
853           
854        box_description= wx.StaticBox(self, -1,str("Model Parameters"))
855        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
856        sizer = wx.GridBagSizer(5,5)
857        ## save the current model
858        self.model = model
859           
860        keys = self.model.getParamList()
861        #list of dispersion paramaters
862        self.disp_list=self.model.getDispParamList()
863       
864        keys.sort()
865   
866        iy = 1
867        ix = 0
868        self.cb1 = wx.CheckBox(self, -1,"Select all", (10, 10))
869        wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param)
870        self.cb1.SetValue(False)
871       
872        sizer.Add(self.cb1,(iy, ix),(1,1),\
873                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
874        ix += 1
875        self.text2_4 = wx.StaticText(self, -1, '[Units]')
876        sizer.Add(self.text2_4,(iy, ix),(1,1),\
877                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
878        #self.text2_4.Hide()
879        ix +=1
880        self.text2_2 = wx.StaticText(self, -1, 'Values')
881        sizer.Add(self.text2_2,(iy, ix),(1,1),\
882                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
883        ix +=2 
884        self.text2_3 = wx.StaticText(self, -1, 'Errors')
885        sizer.Add(self.text2_3,(iy, ix),(1,1),\
886                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
887        self.text2_3.Hide()
888        ix +=1 
889        self.text2_min = wx.StaticText(self, -1, 'Min')
890        sizer.Add(self.text2_min,(iy, ix),(1,1),\
891                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
892        self.text2_min.Hide()
893        ix +=1 
894        self.text2_max = wx.StaticText(self, -1, 'Max')
895        sizer.Add(self.text2_max,(iy, ix),(1,1),\
896                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
897        self.text2_max.Hide()
898        if self.engine_type=="park":
899            self.text2_max.Show(True)
900            self.text2_min.Show(True)
901
902        for item in keys:
903            if not item in self.disp_list and not item in self.model.orientation_params:
904                iy += 1
905                ix = 0
906                ## add parameters name with checkbox for selecting to fit
907                cb = wx.CheckBox(self, -1, item )
908                cb.SetValue(False)
909                wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
910                sizer.Add( cb,( iy, ix),(1,1),
911                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
912                ix +=1
913                # Units
914                try:
915                    units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
916                except:
917                    units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
918                sizer.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
919               
920                ## add parameter value
921                ix += 1
922                value= self.model.getParam(item)
923                ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
924                                    style=wx.TE_PROCESS_ENTER)
925               
926                ctl1.SetValue(format_number(value))
927                ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
928                ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
929                ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
930                sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
931                ## text to show error sign
932                ix += 1
933                text2=wx.StaticText(self, -1, '+/-')
934                sizer.Add(text2,(iy, ix),(1,1),\
935                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
936                text2.Hide() 
937                ## txtcrtl to add error from fit
938                ix += 1
939                ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
940                sizer.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
941                ctl2.Hide()
942               
943                param_min, param_max= self.model.details[item][1:]
944                ix += 1
945                ctl3 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
946                if param_min ==None:
947                    ctl3.SetValue("")
948                else:
949                    ctl3.SetValue(str(param_min))
950                ctl3.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
951                ctl3.Bind(wx.EVT_KILL_FOCUS, self._onparamRangeEnter)
952                ctl3.Bind(wx.EVT_TEXT_ENTER,self._onparamRangeEnter)
953                sizer.Add(ctl3, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
954                ctl3.Hide()
955       
956                ix += 1
957                ctl4 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
958                ctl4.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
959                ctl4.Bind(wx.EVT_KILL_FOCUS, self._onparamRangeEnter)
960                ctl4.Bind(wx.EVT_TEXT_ENTER,self._onparamRangeEnter)
961                sizer.Add(ctl4, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
962                if param_max==None:
963                    ctl4.SetValue("")
964                else:
965                    ctl4.SetValue(str(param_max))
966                ctl4.Hide()
967               
968                if self.engine_type=="park":
969                    ctl3.Show(True)
970                    ctl4.Show(True)
971                   
972                ##[cb state, name, value, "+/-", error of fit, min, max , units]
973                self.parameters.append([cb,item, ctl1,
974                                        text2,ctl2, ctl3, ctl4,None])
975             
976        iy+=1
977        sizer.Add((10,10),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
978        for item in self.model.orientation_params:
979            if not item in self.disp_list :
980                iy += 1
981                ix = 0
982                ## add parameters name with checkbox for selecting to fit
983                cb = wx.CheckBox(self, -1, item )
984                cb.SetValue(False)
985                wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
986                if self.data.__class__.__name__ =="Data2D":
987                    cb.Enable()
988                else:
989                    cb.Disable()
990                sizer.Add( cb,( iy, ix),(1,1),
991                             wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
992                ix +=1
993                # Units
994                try:
995                    units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
996                except:
997                    units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
998                if self.data.__class__.__name__ =="Data2D":
999                    units.Enable()
1000                else:
1001                    units.Disable()
1002                sizer.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1003
1004                ## add parameter value
1005                ix += 1
1006                value= self.model.getParam(item)
1007                ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20),
1008                                    style=wx.TE_PROCESS_ENTER)
1009               
1010                ctl1.SetValue(format_number(value))
1011                if self.data.__class__.__name__ =="Data2D":
1012                    ctl1.Enable()
1013                else:
1014                    ctl1.Disable()
1015                ctl1.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
1016                ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
1017                ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
1018                sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
1019                ## text to show error sign
1020                ix += 1
1021                text2=wx.StaticText(self, -1, '+/-')
1022                sizer.Add(text2,(iy, ix),(1,1),\
1023                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
1024                text2.Hide() 
1025                ## txtcrtl to add error from fit
1026                ix += 1
1027                ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
1028                sizer.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1029                ctl2.Hide()
1030                if self.data.__class__.__name__ =="Data2D":
1031                    ctl1.Enable()
1032                else:
1033                    ctl1.Disable()
1034                param_min, param_max= self.model.details[item][1:]
1035                ix += 1
1036                ctl3 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
1037                if param_min ==None:
1038                    ctl3.SetValue("")
1039                else:
1040                    ctl3.SetValue(str(param_min))
1041                ctl3.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
1042                ctl3.Bind(wx.EVT_KILL_FOCUS, self._onparamRangeEnter)
1043                ctl3.Bind(wx.EVT_TEXT_ENTER,self._onparamRangeEnter)
1044                sizer.Add(ctl3, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1045                ctl3.Hide()
1046                if self.data.__class__.__name__ =="Data2D":
1047                    ctl3.Enable()
1048                else:
1049                    ctl3.Disable()
1050                ix += 1
1051                ctl4 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
1052                ctl4.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
1053                ctl4.Bind(wx.EVT_KILL_FOCUS, self._onparamRangeEnter)
1054                ctl4.Bind(wx.EVT_TEXT_ENTER,self._onparamRangeEnter)
1055                sizer.Add(ctl4, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1056                if param_max ==None:
1057                    ctl4.SetValue("")
1058                else:
1059                    ctl4.SetValue(str(param_max))
1060                ctl4.Hide()
1061                if self.data.__class__.__name__ =="Data2D":
1062                    ctl4.Enable()
1063                else:
1064                    ctl4.Disable()
1065                if self.engine_type=="park":
1066                    ctl3.Show(True)
1067                    ctl4.Show(True)
1068                   
1069               
1070                ##[cb state, name, value, "+/-", error of fit, min, max , units]
1071                self.parameters.append([cb,item, ctl1,
1072                                        text2,ctl2, ctl3, ctl4,None])
1073                self.orientation_params.append([cb,item, ctl1,
1074                                        text2,ctl2, ctl3, ctl4,None])
1075             
1076        iy+=1
1077        sizer.Add((10,10),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1078       
1079        #Display units text on panel
1080        for item in keys:   
1081            if self.model.details[item][0]!='':
1082                self.text2_4.Show()
1083                break
1084            else:
1085                self.text2_4.Hide()
1086   
1087        boxsizer1.Add(sizer)
1088       
1089        self.sizer3.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
1090        self.sizer3.Layout()
1091        self.SetScrollbars(20,20,200,100)
1092       
1093   
1094           
1095       
1096class HelpWindow(wx.Frame):
1097    def __init__(self, parent, id, title):
1098        wx.Frame.__init__(self, parent, id, title, size=(570, 400))
1099       
1100        from sans.models.CylinderModel import CylinderModel
1101        model = CylinderModel()
1102       
1103        from danse.common.plottools.plottables import Data1D
1104        data= Data1D(x=[1,2], y=[3,4], dy=[0.1, 0,1])
1105   
1106        from fitpanel import PageInfo
1107        myinfo = PageInfo(self,  model, data=data )
1108       
1109        ## add data
1110       
1111        from models import ModelList
1112        mylist= ModelList()
1113
1114        from sans.models.SphereModel import SphereModel
1115        from sans.models.SquareWellStructure import SquareWellStructure
1116        from sans.models.DebyeModel import DebyeModel
1117        from sans.models.LineModel import LineModel
1118        name= "shapes"
1119        list1= [SphereModel]
1120        mylist.set_list( name, list1)
1121       
1122        name= "Shape-independent"
1123        list1= [DebyeModel]
1124        mylist.set_list( name, list1)
1125       
1126        name= "Structure Factors"
1127        list1= [SquareWellStructure]
1128        mylist.set_list( name, list1)
1129       
1130        name= "Added models"
1131        list1= [LineModel]
1132        mylist.set_list( name, list1)
1133       
1134        myinfo.model_list_box = mylist.get_list()
1135       
1136        self.page = FitPage(self, myinfo) 
1137       
1138       
1139       
1140        self.Centre()
1141        self.Show(True)
1142
1143
1144   
1145if __name__=="__main__":
1146    app = wx.App()
1147    HelpWindow(None, -1, 'HelpWindow')
1148    app.MainLoop()
1149               
Note: See TracBrowser for help on using the repository browser.