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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 202a7dc3 was 202a7dc3, checked in by Gervaise Alina <gervyh@…>, 16 years ago

statusbar message added

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