source: sasview/sansview/perspectives/fitting/fitting.py @ d0eac66

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

Fixed generating an error when calling 'select data for fitting' twice.

  • Property mode set to 100644
File size: 35.6 KB
Line 
1import os,os.path, re
2import sys, wx, logging
3import string, numpy, math
4
5from copy import deepcopy
6from danse.common.plottools.plottables import Data1D, Theory1D,Data2D
7from danse.common.plottools.PlotPanel import PlotPanel
8from sans.guicomm.events import NewPlotEvent, StatusEvent 
9from sans.guicomm.events import EVT_SLICER_PANEL,EVT_MODEL2D_PANEL
10
11from sans.fit.AbstractFitEngine import Model,Data,FitData1D,FitData2D
12from fitproblem import FitProblem
13from fitpanel import FitPanel
14from fit_thread import FitThread
15import models,modelpage
16import fitpage1D,fitpage2D
17import park
18DEFAULT_BEAM = 0.005
19DEFAULT_QMIN = 0.0
20DEFAULT_QMAX = 0.1
21DEFAULT_NPTS = 40
22import time
23import thread
24print "main",thread.get_ident()
25
26class Plugin:
27    """
28        Fitting plugin is used to perform fit
29    """
30    def __init__(self):
31        ## Plug-in name
32        self.sub_menu = "Fitting"
33       
34        ## Reference to the parent window
35        self.parent = None
36        self.menu_mng = models.ModelManager()
37        ## List of panels for the simulation perspective (names)
38        self.perspective = []
39        self.mypanels=[]
40        self.calc_thread = None
41        self.done = False
42        # Start with a good default
43        self.elapsed = 0.022
44        self.fitter  = None
45       
46        #Flag to let the plug-in know that it is running standalone
47        self.standalone=True
48        ## Fit engine
49        self._fit_engine = 'scipy'
50        self.enable_model2D=False
51        # Log startup
52        logging.info("Fitting plug-in started")   
53        # model 2D view
54        self.model2D_id=None
55
56    def populate_menu(self, id, owner):
57        """
58            Create a menu for the Fitting plug-in
59            @param id: id to create a menu
60            @param owner: owner of menu
61            @ return : list of information to populate the main menu
62        """
63        self.parent.Bind(EVT_MODEL2D_PANEL, self._on_model2D_show)
64        #Menu for fitting
65        self.menu1 = wx.Menu()
66        id1 = wx.NewId()
67        self.menu1.Append(id1, '&Show fit panel')
68        wx.EVT_MENU(owner, id1, self.on_perspective)
69        id3 = wx.NewId()
70        self.menu1.AppendCheckItem(id3, "park") 
71   
72        wx.EVT_MENU(owner, id3, self._onset_engine)
73       
74        #menu for model
75        menu2 = wx.Menu()
76   
77        self.menu_mng.populate_menu(menu2, owner)
78        id2 = wx.NewId()
79        owner.Bind(models.EVT_MODEL,self._on_model_menu)
80        #owner.Bind(modelpage.EVT_MODEL,self._on_model_menu)
81        self.fit_panel.set_owner(owner)
82        self.fit_panel.set_model_list(self.menu_mng.get_model_list())
83        owner.Bind(fitpage1D.EVT_MODEL_BOX,self._on_model_panel)
84        owner.Bind(fitpage2D.EVT_MODEL_BOX,self._on_model_panel)
85        #create  menubar items
86        return [(id, self.menu1, "Fitting"),(id2, menu2, "Model")]
87   
88   
89    def help(self, evt):
90        """
91            Show a general help dialog.
92            TODO: replace the text with a nice image
93        """
94        from helpDialog import  HelpWindow
95        dialog = HelpWindow(None, -1, 'HelpWindow')
96        if dialog.ShowModal() == wx.ID_OK:
97            pass
98        dialog.Destroy()
99       
100   
101    def get_context_menu(self, graph=None):
102        """
103            Get the context menu items available for P(r)
104            @param graph: the Graph object to which we attach the context menu
105            @return: a list of menu items with call-back function
106        """
107        self.graph=graph
108        for item in graph.plottables:
109            if item.__class__.__name__ is "Data2D":
110                return [["Select data  for Fitting",\
111                          "Dialog with fitting parameters ", self._onSelect]] 
112            else:
113                if item.name==graph.selected_plottable and\
114                 item.__class__.__name__ is  "Data1D":
115                    return [["Select data  for Fitting", \
116                             "Dialog with fitting parameters ", self._onSelect]] 
117        return []   
118
119
120    def get_panels(self, parent):
121        """
122            Create and return a list of panel objects
123        """
124        self.parent = parent
125        # Creation of the fit panel
126        self.fit_panel = FitPanel(self.parent, -1)
127        #Set the manager forthe main panel
128        self.fit_panel.set_manager(self)
129        # List of windows used for the perspective
130        self.perspective = []
131        self.perspective.append(self.fit_panel.window_name)
132        # take care of saving  data, model and page associated with each other
133        self.page_finder = {}
134        #index number to create random model name
135        self.index_model = 0
136        self.parent.Bind(EVT_SLICER_PANEL, self._on_slicer_event)
137       
138       
139        #create the fitting panel
140        #return [self.fit_panel]
141       
142        self.mypanels.append(self.fit_panel)
143        return self.mypanels
144   
145   
146    def _on_model2D_show(self, event ):
147        print "model2D get the id ", event.id
148       
149       
150    def _on_slicer_event(self, event):
151        print "fitting:slicer event ", event.panel
152        if event.panel!=None:
153            new_panel = event.panel
154            # Set group ID if available
155            event_id = self.parent.popup_panel(new_panel)
156            self.menu1.Append(event_id, new_panel.window_caption, 
157                             "Show %s plot panel" % new_panel.window_caption)
158            # Set UID to allow us to reference the panel later
159            new_panel.uid = event_id
160            new_panel
161            self.mypanels.append(new_panel) 
162        return       
163    def _on_show_panel(self, event):
164        print "_on_show_panel: fitting"
165     
166    def get_perspective(self):
167        """
168            Get the list of panel names for this perspective
169        """
170        return self.perspective
171   
172   
173    def on_perspective(self, event):
174        """
175            Call back function for the perspective menu item.
176            We notify the parent window that the perspective
177            has changed.
178        """
179        self.parent.set_perspective(self.perspective)
180   
181   
182    def post_init(self):
183        """
184            Post initialization call back to close the loose ends
185            [Somehow openGL needs this call]
186        """
187        self.parent.set_perspective(self.perspective)
188       
189       
190    def _onSelect(self,event):
191        """
192            when Select data to fit a new page is created .Its reference is
193            added to self.page_finder
194        """
195        self.panel = event.GetEventObject()
196        for item in self.panel.graph.plottables:
197            if item.name == self.panel.graph.selected_plottable or\
198                 item.__class__.__name__ is "Data2D":
199                #find a name for the page created for notebook
200                try:
201                   
202                    page, model_name = self.fit_panel.add_fit_page(item)
203                    # add data associated to the page created
204                   
205                    if page !=None:   
206                        #create a fitproblem storing all link to data,model,page creation
207                        self.page_finder[page]= FitProblem()
208                        self.page_finder[page].save_model_name(model_name) 
209                        self.page_finder[page].add_data(item)
210                        wx.PostEvent(self.parent, StatusEvent(status="Page Created"))
211                    else:
212                        wx.PostEvent(self.parent, StatusEvent(status="Page was already Created"))
213                except:
214                    #raise
215                    wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\
216                    %sys.exc_value))
217    def schedule_for_fit(self,value=0,fitproblem =None): 
218        """
219       
220        """   
221        if fitproblem !=None:
222            fitproblem.schedule_tofit(value)
223        else:
224            current_pg=self.fit_panel.get_current_page() 
225            for page, val in self.page_finder.iteritems():
226                if page ==current_pg :
227                    val.schedule_tofit(value)
228                    break
229                     
230                   
231    def get_page_finder(self):
232        """ @return self.page_finder used also by simfitpage.py""" 
233        return self.page_finder
234   
235   
236    def set_page_finder(self,modelname,names,values):
237        """
238             Used by simfitpage.py to reset a parameter given the string constrainst.
239             @param modelname: the name ot the model for with the parameter has to reset
240             @param value: can be a string in this case.
241             @param names: the paramter name
242             @note: expecting park used for fit.
243        """ 
244        sim_page=self.fit_panel.get_page(1)
245        for page, value in self.page_finder.iteritems():
246            if page != sim_page:
247                list=value.get_model()
248                model=list[0]
249                #print "fitting",model.name,modelname
250                if model.name== modelname:
251                    value.set_model_param(names,values)
252                    break
253
254   
255                           
256    def split_string(self,item): 
257        """
258            receive a word containing dot and split it. used to split parameterset
259            name into model name and parameter name example:
260            paramaterset (item) = M1.A
261            @return model_name =M1 , parameter name =A
262        """
263        if string.find(item,".")!=-1:
264            param_names= re.split("\.",item)
265            model_name=param_names[0]
266            param_name=param_names[1] 
267            return model_name,param_name
268       
269   
270    def _single_fit_completed(self,result,pars,cpage,qmin,qmax,elapsed,
271                              ymin=None, ymax=None, xmin=None, xmax=None):
272        """
273            Display fit result on one page of the notebook.
274            @param result: result of fit
275            @param pars: list of names of parameters fitted
276            @param current_pg: the page where information will be displayed
277            @param qmin: the minimum value of x to replot the model
278            @param qmax: the maximum value of x to replot model
279         
280        """
281        #print "single fit ", pars,result.pvec,result.stderr,result.fitness
282        #self.done = True
283        #wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed))
284        try:
285            for page, value in self.page_finder.iteritems():
286                if page==cpage :
287                    #fitdata = value.get_data()
288                    list = value.get_model()
289                    model= list[0]
290                    break
291            i = 0
292            #print "fitting: single fit pars ", pars
293            for name in pars:
294                if result.pvec.__class__==numpy.float64:
295                    model.setParam(name,result.pvec)
296                else:
297                    model.setParam(name,result.pvec[i])
298#                    print "fitting: single fit", name, result.pvec[i]
299                    i += 1
300            print "fitting result : chisqr",result.fitness
301            print "fitting result : pvec",result.pvec
302            print "fitting result : stderr",result.stderr
303            print "qmin qmax xmin xmax ymin , ymax",qmin, qmax,xmin, xmax ,ymin, ymax
304           
305            cpage.onsetValues(result.fitness, result.pvec,result.stderr)
306            self.plot_helper(currpage=cpage,qmin=qmin,qmax=qmax,
307                             ymin=ymin, ymax=ymax,
308                             xmin=xmin, xmax=xmax,title="Fitted model 2D ")
309        except:
310            #raise
311            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
312           
313       
314    def _simul_fit_completed(self,result,qmin,qmax, elapsed,pars=None,cpage=None, ymin=None, ymax=None):
315        """
316            Parameter estimation completed,
317            display the results to the user
318            @param alpha: estimated best alpha
319            @param elapsed: computation time
320        """
321        wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed))
322        try:
323            for page, value in self.page_finder.iteritems():
324                if value.get_scheduled()==1:
325                    #fitdata = value.get_data()
326                    list = value.get_model()
327                    model= list[0]
328                   
329                    small_out = []
330                    small_cov = []
331                    i = 0
332                    #Separate result in to data corresponding to each page
333                    for p in result.parameters:
334                        model_name,param_name = self.split_string(p.name) 
335                        if model.name == model_name:
336                            small_out.append(p.value )
337                            small_cov.append(p.stderr)
338                            model.setParam(param_name,p.value) 
339                    # Display result on each page
340                    page.onsetValues(result.fitness, small_out,small_cov)
341                    #Replot model
342                    self.plot_helper(currpage= page,qmin= qmin,qmax= qmax,ymin=ymin, ymax=ymax) 
343        except:
344             wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
345           
346 
347    def _on_single_fit(self,id=None,qmin=None, qmax=None,ymin=None, ymax=None,xmin=None,xmax=None):
348        """
349            perform fit for the  current page  and return chisqr,out and cov
350            @param engineName: type of fit to be performed
351            @param id: unique id corresponding to a fit problem(model, set of data)
352            @param model: model to fit
353           
354        """
355        #print "in single fitting"
356        #set an engine to perform fit
357        from sans.fit.Fitting import Fit
358        self.fitter= Fit(self._fit_engine)
359        #Setting an id to store model and data in fit engine
360        if id==None:
361            self.id=0
362        else:
363            self.id = id
364        page_fitted=None
365        fit_problem=None
366        #Get information (model , data) related to the page on
367        #with the fit will be perform
368        #current_pg=self.fit_panel.get_current_page()
369        #simul_pg=self.fit_panel.get_page(0)
370           
371        for page, value in self.page_finder.iteritems():
372            if  value.get_scheduled() ==1 :
373                metadata = value.get_data()
374                list=value.get_model()
375                model=list[0]
376                smearer= value.get_smearer()
377                print "single fit", model, smearer
378                #Create list of parameters for fitting used
379                pars=[]
380                templist=[]
381                try:
382                    #templist=current_pg.get_param_list()
383                    templist=page.get_param_list()
384                    for element in templist:
385                        pars.append(str(element[0].GetLabelText()))
386                    pars.sort()
387                    #print "single fit start pars:", pars
388                    #Do the single fit
389                    self.fitter.set_model(Model(model), self.id, pars) 
390                    #print "args...:",metadata,self.id,smearer,qmin,qmax,ymin,ymax
391                 
392                    self.fitter.set_data(data=metadata,Uid=self.id,
393                                         smearer=smearer,qmin= qmin,qmax=qmax,
394                                         ymin=ymin,ymax=ymax)
395                   
396                    self.fitter.select_problem_for_fit(Uid=self.id,value=value.get_scheduled())
397                    page_fitted=page
398                    self.id+=1
399                    self.schedule_for_fit( 0,value) 
400                except:
401                    raise 
402                    #wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
403                    return
404                # make sure to keep an alphabetic order
405                #of parameter names in the list     
406        try:
407            # If a thread is already started, stop it
408            if self.calc_thread != None and self.calc_thread.isrunning():
409                self.calc_thread.stop()
410                   
411            self.calc_thread =FitThread(parent =self.parent,
412                                        fn= self.fitter,
413                                        pars= pars,
414                                        cpage= page_fitted,
415                                       qmin=qmin,
416                                       qmax=qmax,
417                                     
418                                       completefn=self._single_fit_completed,
419                                       updatefn=None)
420            self.calc_thread.queue()
421            self.calc_thread.ready(2.5)
422            #while not self.done:
423                #print "when here"
424             #   time.sleep(1)
425           
426           
427        except:
428            raise
429            wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value))
430            return
431         
432    def _on_simul_fit(self, id=None,qmin=None,qmax=None, ymin=None, ymax=None):
433        """
434            perform fit for all the pages selected on simpage and return chisqr,out and cov
435            @param engineName: type of fit to be performed
436            @param id: unique id corresponding to a fit problem(model, set of data)
437             in park_integration
438            @param model: model to fit
439           
440        """
441        #set an engine to perform fit
442        from sans.fit.Fitting import Fit
443        self.fitter= Fit(self._fit_engine)
444       
445        #Setting an id to store model and data
446        if id==None:
447             id = 0
448        self.id = id
449       
450        for page, value in self.page_finder.iteritems():
451            try:
452                if value.get_scheduled()==1:
453                    metadata = value.get_data()
454                    list = value.get_model()
455                    model= list[0]
456                    #Create dictionary of parameters for fitting used
457                    pars = []
458                    templist = []
459                    templist = page.get_param_list()
460                    for element in templist:
461                        try:
462                            name = str(element[0].GetLabelText())
463                            pars.append(name)
464                        except:
465                            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
466                            return
467                    # need to check this print "new model "
468                    new_model=Model(model)
469                    param=value.get_model_param()
470                   
471                    if len(param)>0:
472                        for item in param:
473                            param_value = item[1]
474                            param_name = item[0]
475                            #print "fitting ", param,param_name, param_value
476                           
477                            #new_model.set( model.getParam(param_name[0])= param_value)
478                            #new_model.set( exec"%s=%s"%(param_name[0], param_value))
479                            #new_model.set( exec "%s"%(param_nam) = param_value)
480                            new_model.parameterset[ param_name].set( param_value )
481                         
482                    self.fitter.set_model(new_model, self.id, pars) 
483                    self.fitter.set_data(metadata,self.id,qmin,qmax,ymin,ymax)
484                    self.fitter.select_problem_for_fit(Uid=self.id,value=value.get_scheduled())
485                    self.id += 1 
486            except:
487                #raise
488                wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
489                return 
490        #Do the simultaneous fit
491        try:
492            # If a thread is already started, stop it
493            if self.calc_thread != None and self.calc_thread.isrunning():
494                self.calc_thread.stop()
495                   
496            self.calc_thread =FitThread(parent =self.parent,
497                                        fn= self.fitter,
498                                       qmin=qmin,
499                                       qmax=qmax,
500                                       ymin= ymin,
501                                       ymax= ymax,
502                                       completefn= self._simul_fit_completed,
503                                       updatefn=None)
504            self.calc_thread.queue()
505            self.calc_thread.ready(2.5)
506           
507        except:
508            #raise
509            wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value))
510            return
511       
512       
513    def _onset_engine(self,event):
514        """ set engine to scipy"""
515        if self._fit_engine== 'park':
516            self._on_change_engine('scipy')
517        else:
518            self._on_change_engine('park')
519        wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine))
520 
521   
522    def _on_change_engine(self, engine='park'):
523        """
524            Allow to select the type of engine to perform fit
525            @param engine: the key work of the engine
526        """
527        self._fit_engine = engine
528   
529   
530    def _on_model_panel(self, evt):
531        """
532            react to model selection on any combo box or model menu.plot the model 
533        """
534       
535        model = evt.model
536        name = evt.name
537       
538        sim_page=self.fit_panel.GetPage(1)
539        current_pg = self.fit_panel.get_current_page() 
540        if current_pg != sim_page:
541            current_pg.set_panel(model)
542            model.name = self.page_finder[current_pg].get_name()
543            try:
544                metadata=self.page_finder[current_pg].get_data()
545                M_name=model.name+"= "+name+"("+metadata.group_id+")"
546            except:
547                M_name=model.name+"= "+name
548            #model.name="M"+str(self.index_model)
549            self.index_model += 1 
550            # save model name
551           
552            # save the name containing the data name with the appropriate model
553            self.page_finder[current_pg].set_model(model,M_name)
554            self.plot_helper(currpage= current_pg,qmin= None,qmax= None)
555            sim_page.add_model(self.page_finder)
556       
557    def  set_smearer(self,smearer):     
558         current_pg=self.fit_panel.get_current_page()
559         self.page_finder[current_pg].set_smearer(smearer)
560         
561    def redraw_model(self,qmin= None,qmax= None):
562        """
563            Draw a theory according to model changes or data range.
564            @param qmin: the minimum value plotted for theory
565            @param qmax: the maximum value plotted for theory
566        """
567        current_pg=self.fit_panel.get_current_page()
568        for page, value in self.page_finder.iteritems():
569            if page ==current_pg :
570                break 
571        self.plot_helper(currpage=page,qmin= qmin,qmax= qmax)
572       
573    def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None,
574                    ymin=None,ymax=None, xmin=None, xmax=None,title=None ):
575        """
576            Plot a theory given a model and data
577            @param model: the model from where the theory is derived
578            @param currpage: page in a dictionary referring to some data
579        """
580        if self.fit_panel.GetPageCount() >1:
581            for page in self.page_finder.iterkeys():
582                if  page==currpage : 
583                    data=self.page_finder[page].get_data()
584                    list=self.page_finder[page].get_model()
585                    model=list[0]
586                    break 
587            print "model in fitting",model
588            if data!=None and data.__class__.__name__ != 'Data2D':
589                theory = Theory1D(x=[], y=[])
590                theory.name = model.name
591                theory.group_id = data.group_id
592                theory.id = "Model"
593                x_name, x_units = data.get_xaxis() 
594                y_name, y_units = data.get_yaxis() 
595                theory.xaxis(x_name, x_units)
596                theory.yaxis(y_name, y_units)
597                if qmin == None :
598                   qmin = min(data.x)
599                if qmax == None :
600                   qmax = max(data.x)
601                try:
602                    tempx = qmin
603                    tempy = model.run(qmin)
604                    theory.x.append(tempx)
605                    theory.y.append(tempy)
606                except :
607                        wx.PostEvent(self.parent, StatusEvent(status="fitting \
608                        skipping point x %g %s" %(qmin, sys.exc_value)))
609                           
610                for i in range(len(data.x)):
611                    try:
612                        if data.x[i]> qmin and data.x[i]< qmax:
613                            tempx = data.x[i]
614                            tempy = model.run(tempx)
615                            theory.x.append(tempx) 
616                            theory.y.append(tempy)
617                           
618                    except:
619                        wx.PostEvent(self.parent, StatusEvent(status="fitting \
620                        skipping point x %g %s" %(data.x[i], sys.exc_value)))   
621                try:
622                    tempx = qmax
623                    tempy = model.run(qmax)
624                    theory.x.append(tempx)
625                    theory.y.append(tempy)
626                except:
627                    wx.PostEvent(self.parent, StatusEvent(status="fitting \
628                        skipping point x %g %s" %(qmin, sys.exc_value)) )
629                wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
630                                                title=str(data.name)))
631            else:
632               
633                theory=Data2D(data.data, data.err_data)
634                theory.name= model.name
635                if title !=None:
636                    self.title = title
637                    theory.id= self.title
638                    theory.group_id= self.title+data.name
639                else:
640                    self.title= "Analytical model 2D "
641                    theory.id= "Model"
642                    theory.group_id= "Model"+data.name
643                theory.x_bins= data.x_bins
644                theory.y_bins= data.y_bins
645                tempy=[]
646                #print "max x,y",max(data.xmax,data.xmin),max(data.ymax,data.ymin)
647                if qmin==None:
648                    qmin=0#data.xmin
649                if qmax==None:
650                    qmax=math.sqrt(math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)/
651                                   +math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2))
652                if ymin==None:
653                    ymin=data.ymin
654                if ymax==None:
655                    ymax=data.ymax
656                if xmin ==None:
657                    xmin=data.xmin
658                if xmax==None:
659                    xmax=data.xmax                   
660                #print " q range =",   
661                theory.data = numpy.zeros((len(data.y_bins),len(data.x_bins)))
662                for j in range(len(data.y_bins)):
663                    for i in range(len(data.x_bins)):
664                        tempqij=math.sqrt((math.pow(data.y_bins[j],2)+math.pow(data.x_bins[i],2)))
665                        #if tempqij>= qmin and tempqij<= qmax:
666                        theory.data[j][i]=model.runXY([data.y_bins[j],data.x_bins[i]])
667                        #else:
668                            #theory.data[j][i]=None
669                #print "len(data.x_bins),len(data.y_bins);",len(data.x_bins),len(data.y_bins),i,j
670                #print "fitting : plot_helper:", theory.image
671                #print "fitting : plot_helper:",theory.image
672                theory.detector= data.detector
673                theory.source= data.source
674               
675                theory.qmin= qmin
676                theory.qmax= qmax
677                theory.ymin= ymin
678                theory.ymax= ymax
679                theory.xmin= xmin
680                theory.xmax= xmax
681       
682                wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
683                                                title=self.title +str(data.name)))
684       
685       
686    def _on_model_menu(self, evt):
687        """
688            Plot a theory from a model selected from the menu
689        """
690        name = evt.model.__name__
691        if hasattr(evt.model, "name"):
692            name = evt.model.name
693        print "on model menu", name
694        model=evt.model()
695        description=model.description
696       
697        # Create a model page. If a new page is created, the model
698        # will be plotted automatically. If a page already exists,
699        # the content will be updated and the plot refreshed
700        self.fit_panel.add_model_page(model,description,name,topmenu=True)
701       
702    def draw_model(self,model,name ,data=None,description=None,enable1D=True, enable2D=False,
703                   qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
704        """
705             draw model with default data value
706        """
707        if data !=None:
708            self.redraw_model(qmin,qmax)
709            return 
710        self._draw_model2D(model=model,
711                           description=model.description,
712                           enable2D= enable2D,
713                           qmin=qmin,
714                           qmax=qmax,
715                           qstep=qstep)
716        self._draw_model1D(model,name,model.description, enable1D,qmin,qmax, qstep)
717             
718    def _draw_model1D(self,model,name,description=None, enable1D=True,
719                      qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
720       
721        if enable1D:
722            x=  numpy.linspace(start= qmin,
723                               stop= qmax,
724                               num= qstep,
725                               endpoint=True
726                               )     
727            xlen= len(x)
728            y = numpy.zeros(xlen)
729            if not enable1D:
730                for i in range(xlen):
731                    y[i] = model.run(x[i])
732               
733                try:
734                    new_plot = Theory1D(x, y)
735                   
736                    new_plot.name = name
737                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
738                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
739                    new_plot.id = "Model"
740                    new_plot.group_id ="Model"
741                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title="Analytical model 1D"))
742                except:
743                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
744                    #raise
745            else:
746                for i in range(xlen):
747                    y[i] = model.run(x[i])
748                #print x, y   
749                try:
750                    new_plot = Theory1D(x, y)
751                    print "draw model 1D", name
752                    new_plot.name = name
753                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
754                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
755                    new_plot.id ="Model"
756                    new_plot.group_id ="Model"
757                   
758                    # Pass the reset flag to let the plotting event handler
759                    # know that we are replacing the whole plot
760                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot,
761                                     title="Analytical model 1D ", reset=True ))
762                   
763                except:
764                    #raise
765                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
766    def update(self, output,time):
767        pass
768   
769    def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS):
770       
771        wx.PostEvent(self.parent, StatusEvent(status="Calc \
772        complete in %g sec" % elapsed))
773        #print "complete",output, model,qmin, qmax
774        data = output
775        temp= numpy.zeros(numpy.shape(data))
776        temp[temp==0]=1
777        theory= Data2D(image=data, err_image=temp)
778   
779        from DataLoader.data_info import Detector, Source
780       
781        detector = Detector()
782        theory.detector=[]
783        theory.detector.append(detector)
784           
785        theory.detector[0].pixel_size.x= qmax/(qstep/2-1)#5.0
786        theory.detector[0].pixel_size.y= qmax/(qstep/2-1)#5.0
787        theory.detector[0].beam_center.x= qmax
788        theory.detector[0].beam_center.y= qmax
789        theory.detector[0].distance= 1e+12#13705.0
790        theory.source= Source()
791        theory.source.wavelength= 2*math.pi/1e+12#8.4
792        theory.x_bins =[]
793        theory.y_bins =[]
794        # compute x_bins and y_bins
795        # Qx and Qy vectors
796   
797        distance   = theory.detector[0].distance
798        pixel      = qstep/2-1
799        theta      = pixel / distance / 100.0
800        wavelength = theory.source.wavelength
801        pixel_width_x = theory.detector[0].pixel_size.x
802        pixel_width_y = theory.detector[0].pixel_size.y
803        center_x      = theory.detector[0].beam_center.x/pixel_width_x
804        center_y      = theory.detector[0].beam_center.y/pixel_width_y
805       
806       
807        size_x, size_y= numpy.shape(theory.data)
808        #print "size_x,size_y",size_x, size_y
809        for i_x in range(size_x):
810            theta = (i_x-center_x+1)*pixel_width_x / distance / size_x#100.0
811            qx = 4.0*math.pi/wavelength * math.sin(theta/2.0)
812            theory.x_bins.append(qx)   
813        for i_y in range(size_y):
814            theta = (i_y-center_y+1)*pixel_width_y / distance / size_y#100.0
815            qy = 4.0*math.pi/wavelength * math.sin(theta/2.0)
816            theory.y_bins.append(qy)
817           
818        #theory.err_data= numpy.   
819        theory.name= model.name
820        theory.group_id ="Model"
821        theory.id ="Model"
822       
823       
824       
825        theory.xmin= -qmax
826        theory.xmax= qmax
827        theory.ymin= -qmax
828        theory.ymax= qmax
829       
830        print "model draw comptele xmax",theory.xmax,model.name
831        wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
832                         title="Analytical model 2D ", reset=True ))
833         
834       
835         
836    def _draw_model2D(self,model,description=None, enable2D=False,
837                      qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
838       
839        x=  numpy.linspace(start= -1*qmax,
840                               stop= qmax,
841                               num= qstep,
842                               endpoint=True ) 
843        y = numpy.linspace(start= -1*qmax,
844                               stop= qmax,
845                               num= qstep,
846                               endpoint=True )
847       
848        lx = len(x)
849        #print x
850        data=numpy.zeros([len(x),len(y)])
851        self.model= model
852        if enable2D:
853            from model_thread import Calc2D
854            self.calc_thread = Calc2D(parent =self.parent,x=x,
855                                       y=y,model= self.model, 
856                                       qmin=qmin,
857                                       qmax=qmax,
858                                       qstep=qstep,
859                            completefn=self.complete,
860                            updatefn=None)
861            self.calc_thread.queue()
862            self.calc_thread.ready(2.5)
863           
864    def show_panel2D(self, id=None ):
865        self.parent.show_panel(self.model2D_id)
866           
867   
868if __name__ == "__main__":
869    i = Plugin()
870   
871   
872   
873   
Note: See TracBrowser for help on using the repository browser.