source: sasview/sansview/perspectives/fitting/old_fitting.py @ 26bf293

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

redesign the model1D and madel page

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