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

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

fixed bug in model 2d plot

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