source: sasview/sansview/perspectives/fitting/fitting.py @ 39a365d

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

function called modified for simultaneous fit

  • Property mode set to 100644
File size: 36.9 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           
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                pars=[]
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                   
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                    self.fitter.select_problem_for_fit(Uid=self.id,value=value.get_scheduled())
496                    self.id += 1 
497            except:
498                #raise
499                wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
500                return 
501        #Do the simultaneous fit
502        try:
503            # If a thread is already started, stop it
504            if self.calc_thread != None and self.calc_thread.isrunning():
505                self.calc_thread.stop()
506                   
507            self.calc_thread =FitThread(parent =self.parent,
508                                        fn= self.fitter,
509                                       qmin=qmin,
510                                       qmax=qmax,
511                                       ymin= ymin,
512                                       ymax= ymax,
513                                       completefn= self._simul_fit_completed,
514                                       updatefn=None)
515            self.calc_thread.queue()
516            self.calc_thread.ready(2.5)
517           
518        except:
519            #raise
520            wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value))
521            return
522       
523       
524    def _onset_engine(self,event):
525        """ set engine to scipy"""
526        if self._fit_engine== 'park':
527            self._on_change_engine('scipy')
528        else:
529            self._on_change_engine('park')
530        wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine))
531 
532   
533    def _on_change_engine(self, engine='park'):
534        """
535            Allow to select the type of engine to perform fit
536            @param engine: the key work of the engine
537        """
538        self._fit_engine = engine
539   
540   
541    def _on_model_panel(self, evt):
542        """
543            react to model selection on any combo box or model menu.plot the model 
544        """
545       
546        model = evt.model
547        name = evt.name
548       
549        print "name fitting", name
550        sim_page=self.fit_panel.GetPage(1)
551        current_pg = self.fit_panel.get_current_page() 
552        if current_pg != sim_page:
553            current_pg.set_panel(model)
554            #model.name = self.page_finder[current_pg].get_name()
555            #print "model name", model.name
556            model.name="M"+str(self.index_model)
557            try:
558                metadata=self.page_finder[current_pg].get_data()
559                M_name=model.name+"= "+name+"("+metadata.group_id+")"
560            except:
561                M_name=model.name+"= "+name
562            self.index_model += 1 
563           
564           
565            # save model name
566           
567            # save the name containing the data name with the appropriate model
568            self.page_finder[current_pg].set_model(model,M_name)
569            self.plot_helper(currpage= current_pg,qmin= None,qmax= None)
570            sim_page.add_model(self.page_finder)
571       
572    def  set_smearer(self,smearer):     
573         current_pg=self.fit_panel.get_current_page()
574         self.page_finder[current_pg].set_smearer(smearer)
575         
576    def redraw_model(self,qmin= None,qmax= None):
577        """
578            Draw a theory according to model changes or data range.
579            @param qmin: the minimum value plotted for theory
580            @param qmax: the maximum value plotted for theory
581        """
582        current_pg=self.fit_panel.get_current_page()
583        for page, value in self.page_finder.iteritems():
584            if page ==current_pg :
585                break 
586        self.plot_helper(currpage=page,qmin= qmin,qmax= qmax)
587       
588    def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None,
589                    ymin=None,ymax=None, xmin=None, xmax=None,title=None ):
590        """
591            Plot a theory given a model and data
592            @param model: the model from where the theory is derived
593            @param currpage: page in a dictionary referring to some data
594        """
595        if self.fit_panel.GetPageCount() >1:
596            for page in self.page_finder.iterkeys():
597                if  page==currpage : 
598                    data=self.page_finder[page].get_data()
599                    list=self.page_finder[page].get_model()
600                    model=list[0]
601                    break 
602            print "model in fitting",model
603            if data!=None and data.__class__.__name__ != 'Data2D':
604                theory = Theory1D(x=[], y=[])
605                theory.name = model.name
606                theory.group_id = data.group_id
607                """
608                if hasattr(data, "id"):
609                    import string
610                    if string.find("Model",data.id )!=None:
611                        #allow plotting on the same panel
612                        theory.id =str(data.id )+" "+str(self.index_theory)
613                        self.index_theory +=1
614                    else:
615                    """
616                theory.id = "Model"
617                   
618                x_name, x_units = data.get_xaxis() 
619                y_name, y_units = data.get_yaxis() 
620                theory.xaxis(x_name, x_units)
621                theory.yaxis(y_name, y_units)
622                if qmin == None :
623                   qmin = min(data.x)
624                if qmax == None :
625                   qmax = max(data.x)
626                try:
627                    tempx = qmin
628                    tempy = model.run(qmin)
629                    theory.x.append(tempx)
630                    theory.y.append(tempy)
631                except :
632                        wx.PostEvent(self.parent, StatusEvent(status="fitting \
633                        skipping point x %g %s" %(qmin, sys.exc_value)))
634                           
635                for i in range(len(data.x)):
636                    try:
637                        if data.x[i]> qmin and data.x[i]< qmax: # 1d fit range
638                            tempx = data.x[i]
639                            tempy = model.run(tempx)
640                            theory.x.append(tempx) 
641                            theory.y.append(tempy)
642                           
643                    except:
644                        wx.PostEvent(self.parent, StatusEvent(status="fitting \
645                        skipping point x %g %s" %(data.x[i], sys.exc_value)))   
646                try:
647                    tempx = qmax
648                    tempy = model.run(qmax)
649                    theory.x.append(tempx)
650                    theory.y.append(tempy)
651                except:
652                    wx.PostEvent(self.parent, StatusEvent(status="fitting \
653                        skipping point x %g %s" %(qmin, sys.exc_value)) )
654                wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
655                                                title=str(data.name)))
656            else:
657               
658                theory=Data2D(data.data, data.err_data)
659                theory.name= model.name
660                if title !=None:
661                    self.title = title
662                    theory.id= self.title
663                    theory.group_id= self.title+data.name
664                else:
665                    self.title= "Analytical model 2D "
666                    theory.id= "Model"
667                    theory.group_id= "Model"+data.name
668                theory.x_bins= data.x_bins
669                theory.y_bins= data.y_bins
670                tempy=[]
671                #print "max x,y",max(data.xmax,data.xmin),max(data.ymax,data.ymin)
672                if qmin==None:
673                    qmin=0#min(math.fabs(data.xmax),math.fabs(data.ymin))
674                if qmax==None:
675                    qmax=math.sqrt(math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)/
676                                   +math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2))
677                if ymin==None:
678                    ymin=data.ymin
679                if ymax==None:
680                    ymax=data.ymax
681                if xmin ==None:
682                    xmin=data.xmin
683                if xmax==None:
684                    xmax=data.xmax                   
685                #print " q range =",   
686                theory.data = numpy.zeros((len(data.y_bins),len(data.x_bins)))
687                for j in range(len(data.y_bins)):
688                    for i in range(len(data.x_bins)):
689                        tempqij=math.sqrt((math.pow(data.y_bins[j],2)+math.pow(data.x_bins[i],2)))
690                        if tempqij>= qmin and tempqij<= qmax: 
691                            theory.data[j][i]=model.runXY([data.y_bins[j],data.x_bins[i]])
692                        else:
693                            theory.data[j][i]=0 #None # Later, We need to decide which of  0 and None is better.
694                #print "len(data.x_bins),len(data.y_bins);",len(data.x_bins),len(data.y_bins),i,j
695                #print "fitting : plot_helper:", theory.image
696                #print "fitting : plot_helper:",theory.image
697                theory.detector= data.detector
698                theory.source= data.source
699               
700                theory.qmin= qmin
701                theory.qmax= qmax
702                theory.ymin= ymin
703                theory.ymax= ymax
704                theory.xmin= xmin
705                theory.xmax= xmax
706       
707                wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
708                                                title=self.title +str(data.name)))
709       
710       
711    def _on_model_menu(self, evt):
712        """
713            Plot a theory from a model selected from the menu
714        """
715        name = evt.model.__name__
716        if hasattr(evt.model, "name"):
717            name = evt.model.name
718        print "on model menu", name
719        model=evt.model()
720        description=model.description
721       
722        # Create a model page. If a new page is created, the model
723        # will be plotted automatically. If a page already exists,
724        # the content will be updated and the plot refreshed
725        self.fit_panel.add_model_page(model,description,name,topmenu=True)
726       
727    def draw_model(self,model,name ,data=None,description=None,enable1D=True, enable2D=False,
728                   qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
729        """
730             draw model with default data value
731        """
732        if data !=None:
733            self.redraw_model(qmin,qmax)
734            return 
735        self._draw_model2D(model=model,
736                           description=model.description,
737                           enable2D= enable2D,
738                           qmin=qmin,
739                           qmax=qmax,
740                           qstep=qstep)
741        self._draw_model1D(model,name,model.description, enable1D,qmin,qmax, qstep)
742             
743    def _draw_model1D(self,model,name,description=None, enable1D=True,
744                      qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
745       
746        if enable1D:
747            x=  numpy.linspace(start= qmin,
748                               stop= qmax,
749                               num= qstep,
750                               endpoint=True
751                               )     
752            xlen= len(x)
753            y = numpy.zeros(xlen)
754            if not enable1D:
755                for i in range(xlen):
756                    y[i] = model.run(x[i])
757               
758                try:
759                    new_plot = Theory1D(x, y)
760                   
761                    new_plot.name = name
762                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
763                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
764                    new_plot.id = "Model"
765                    new_plot.group_id ="Model"
766                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title="Analytical model 1D"))
767                except:
768                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
769                    #raise
770            else:
771                for i in range(xlen):
772                    y[i] = model.run(x[i])
773                #print x, y   
774                try:
775                    new_plot = Theory1D(x, y)
776                    print "draw model 1D", name
777                    new_plot.name = name
778                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
779                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
780                    new_plot.id ="Model"
781                    new_plot.group_id ="Model"
782                   
783                    # Pass the reset flag to let the plotting event handler
784                    # know that we are replacing the whole plot
785                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot,
786                                     title="Analytical model 1D ", reset=True ))
787                   
788                except:
789                    #raise
790                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
791    def update(self, output,time):
792        pass
793   
794    def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS):
795       
796        wx.PostEvent(self.parent, StatusEvent(status="Calc \
797        complete in %g sec" % elapsed))
798        #print "complete",output, model,qmin, qmax
799        data = output
800        temp= numpy.zeros(numpy.shape(data))
801        temp[temp==0]=1
802        theory= Data2D(image=data, err_image=temp)
803   
804        from DataLoader.data_info import Detector, Source
805       
806        detector = Detector()
807        theory.detector=[]
808        theory.detector.append(detector) 
809           
810        theory.detector[0].distance=1e+32#13705.0
811        theory.source= Source()
812        theory.source.wavelength=2*math.pi/1e+32#8.4
813        theory.x_bins =[]
814        theory.y_bins =[]
815        #Now qmax is xmax.
816        xmax=2*theory.detector[0].distance*math.atan(qmax/(4*math.pi/theory.source.wavelength))
817        theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5)#5.0
818        theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5)#5.0
819        theory.detector[0].beam_center.x= qmax
820        theory.detector[0].beam_center.y= qmax
821        #print "xmax,qmax",xmax,qmax
822        # compute x_bins and y_bins
823        # Qx and Qy vectors
824   
825        distance   = theory.detector[0].distance
826        pixel      = qstep/2-1
827        theta      = pixel / distance / qstep#100.0
828        wavelength = theory.source.wavelength
829        pixel_width_x = theory.detector[0].pixel_size.x
830        pixel_width_y = theory.detector[0].pixel_size.y
831        center_x      = theory.detector[0].beam_center.x/pixel_width_x
832        center_y      = theory.detector[0].beam_center.y/pixel_width_y
833       
834       
835        size_x, size_y= numpy.shape(theory.data)
836        #print "size_x,size_y",size_x, size_y
837        #This case, q and x are equivalent to each other.
838        for i_x in range(size_x):
839            theta = (i_x-center_x)*pixel_width_x / distance #/ size_x#100.0
840            qx = 4.0*math.pi/wavelength * math.tan(theta/2.0)
841            theory.x_bins.append(qx)   
842        for i_y in range(size_y):
843            theta = (i_y-center_y)*pixel_width_y / distance #/ size_y#100.0
844            qy =4.0*math.pi/wavelength * math.tan(theta/2.0)
845            theory.y_bins.append(qy)
846           
847        #theory.err_data= numpy.   
848        theory.name= model.name
849        theory.group_id ="Model"
850        theory.id ="Model"
851       
852       
853       
854        theory.xmin= -qmax/math.sqrt(2)
855        theory.xmax= qmax/math.sqrt(2)
856        theory.ymin= -qmax/math.sqrt(2)
857        theory.ymax= qmax/math.sqrt(2)
858       
859        print "model draw comptele xmax",theory.xmax,model.name
860        wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
861                         title="Analytical model 2D ", reset=True ))
862         
863       
864         
865    def _draw_model2D(self,model,description=None, enable2D=False,
866                      qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
867       
868        x=  numpy.linspace(start= -1*qmax,
869                               stop= qmax,
870                               num= qstep,
871                               endpoint=True ) 
872        y = numpy.linspace(start= -1*qmax,
873                               stop= qmax,
874                               num= qstep,
875                               endpoint=True )
876       
877        lx = len(x)
878        #print x
879        data=numpy.zeros([len(x),len(y)])
880        self.model= model
881        if enable2D:
882            from sans.guiframe.model_thread import Calc2D
883            self.calc_thread = Calc2D(parent =self.parent,x=x,
884                                       y=y,model= self.model, 
885                                       qmin=qmin,
886                                       qmax=qmax,
887                                       qstep=qstep,
888                            completefn=self.complete,
889                            updatefn=None)
890            self.calc_thread.queue()
891            self.calc_thread.ready(2.5)
892           
893    def show_panel2D(self, id=None ):
894        self.parent.show_panel(self.model2D_id)
895           
896   
897if __name__ == "__main__":
898    i = Plugin()
899   
900   
901   
902   
Note: See TracBrowser for help on using the repository browser.