source: sasview/sansview/perspectives/fitting/fitting.py @ 633ba04

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

add thread for fitting

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