source: sasview/sansview/perspectives/fitting/fitting.py @ 202a7dc3

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 202a7dc3 was 202a7dc3, checked in by Gervaise Alina <gervyh@…>, 16 years ago

statusbar message added

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