source: sasview/sansview/perspectives/fitting/fitting.py @ 0d9dae8

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 0d9dae8 was 1374fbe4, checked in by Jae Cho <jhjcho@…>, 16 years ago

Fixed mis-representation of 2d fit-model image after loading 2d data.

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