Changeset bb18ef1 in sasview for sansview/perspectives


Ignore:
Timestamp:
Mar 18, 2009 11:41:18 AM (15 years ago)
Author:
Gervaise Alina <gervyh@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
35eeea8
Parents:
8cfdd5e
Message:

some changes of sansview review

Location:
sansview/perspectives/fitting
Files:
2 added
7 edited

Legend:

Unmodified
Added
Removed
  • sansview/perspectives/fitting/fit_thread.py

    r925a30e rbb18ef1  
    175175            raise 
    176176        except: 
    177             raise 
    178             #wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) 
    179             #return  
     177            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) 
     178            return  
    180179     
  • sansview/perspectives/fitting/fitpage1D.py

    r5150250 rbb18ef1  
    140140        # This sizer contains model list and chisqr value  
    141141        #filling sizer4 
     142        ## structure combox box 
     143        self.structbox = wx.ComboBox(self, -1) 
     144        # define combox box 
    142145        self.modelbox = wx.ComboBox(self, -1) 
     146         
    143147        self.tcChi    =  wx.StaticText(self, -1, str(0), style=wx.ALIGN_LEFT) 
    144148        self.tcChi.Hide() 
     
    149153        self.sizer4.Add(wx.StaticText(self,-1,'Model'),(iy,ix),(1,1)\ 
    150154                  , wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     155         
    151156        ix += 1 
    152157        self.sizer4.Add(self.modelbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     158        ix +=1 
     159        self.text_mult= wx.StaticText(self,-1,' x ') 
     160        self.sizer4.Add(self.text_mult,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     161        ix += 1 
     162        self.sizer4.Add(self.structbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     163         
     164         
     165         
    153166        ix += 1 
    154167        self.sizer4.Add(self.text1_1,(iy,ix),(1,1),\ 
     
    262275        # model on which the fit would be performed 
    263276        self.model=None 
    264          
     277        
    265278        self.back_up_model= None 
    266279        #dictionary of model name and model class 
     
    282295        self.Centre() 
    283296        self.Layout() 
    284         self.GrandParent.GetSizer().Layout() 
     297         
     298        self.parent.GetSizer().Layout() 
    285299    
    286300    def compute_chisqr2D(self): 
     
    289303            to the tcChi txtcrl 
    290304        """ 
    291         flag=self.checkFitRange() 
     305        from sans.guiframe.utils import check_value 
     306        flag = check_value( self.qmin, self.qmax) 
     307        #flag=self.checkFitRange() 
    292308        res=[] 
    293309        if flag== True: 
     
    322338            to the tcChi txtcrl 
    323339        """ 
    324         flag=self.checkFitRange() 
     340        from sans.guiframe.utils import check_value 
     341        flag = check_value( self.qmin, self.qmax) 
     342        #flag=self.checkFitRange() 
    325343        if flag== True: 
    326344            try: 
     
    367385        self.parent.GetSizer().Layout() 
    368386 
    369         for item in self.model_list_box.itervalues(): 
    370             name = item.__name__ 
    371             if hasattr(item, "name"): 
    372                 name = item.name 
    373              
     387        
     388        name= self.modelbox.GetString(self.modelbox.GetCurrentSelection()) 
     389        form_factor =self.modelbox.GetClientData(self.modelbox.GetCurrentSelection()) 
     390        struct_factor =self.structbox.GetClientData(self.structbox.GetCurrentSelection()) 
     391        
     392       
     393        if form_factor!="separator": 
     394            if struct_factor != None and struct_factor.__name__ != "NoStructure": 
     395                from sans.models.MultiplicationModel import MultiplicationModel 
     396                self.model= MultiplicationModel(form_factor(),struct_factor()) 
     397            else: 
     398                 self.model= form_factor()  
     399            self.back_up_model= self.model.clone() 
     400            name= self.model.name 
    374401            if name == None: 
    375402                self.qmin.Disable() 
     
    378405                self.qmin.Enable() 
    379406                self.qmax.Enable()  
    380              
    381             if name ==event.GetString(): 
    382                 try: 
    383                     self.model=item() 
    384                     self.back_up_model= self.model.clone() 
    385                     evt = ModelEventbox(model=self.model,name=name) 
    386                     wx.PostEvent(self.event_owner, evt) 
    387                     self.text1_1.Show() 
    388                     self.compute_chisqr() 
    389                     self.tcChi.Show() 
    390                 except: 
    391                     raise #ValueError,"model.name is not equal to model class name" 
    392                 break   
     407            evt = ModelEventbox(model=self.model,name=name) 
     408            wx.PostEvent(self.event_owner, evt)    
     409            self.text1_1.Show() 
     410            self.tcChi.Show() 
     411            self.compute_chisqr() 
     412         
     413             
     414        else: 
     415            self.model=None  
     416            msg= " Select non - model value:%s ! Previous Model reloaded "%name  
     417            wx.PostEvent(self.parent.parent, StatusEvent(status= msg)) 
     418             
     419        self.set_panel(self.model) 
    393420             
    394421                  
    395422    def onFit(self,event): 
    396         """ signal for fitting""" 
    397           
    398         flag=self.checkFitRange() 
    399         self.set_manager(self.manager) 
    400       
     423        """  
     424            signal for fitting .Perform single fit only 
     425        """ 
     426        from sans.guiframe.utils import check_value 
     427        flag = check_value( self.qmin, self.qmax)  
     428         
     429        if not flag: 
     430            msg= "Fitting range invalid" 
     431            wx.PostEvent(self.parent.parent, StatusEvent(status= msg )) 
     432            return  
     433         
     434        if len(self.param_toFit) <= 0: 
     435            msg= "Select at least one parameter to fit" 
     436            wx.PostEvent(self.parent.parent, StatusEvent(status= msg )) 
     437            return  
     438         
    401439        self.qmin_x=float(self.qmin.GetValue()) 
    402440        self.qmax_x =float( self.qmax.GetValue()) 
    403         if len(self.param_toFit) >0 and flag==True: 
    404             self.manager.schedule_for_fit( value=1,fitproblem =None)  
    405             if hasattr(self.data, "data"): 
    406                 #single fit for Data2D 
    407                 self.manager._on_single_fit(qmin=self.qmin_x,qmax=self.qmax_x, 
    408                                             ymin=self.data.ymin, ymax=self.data.ymax, 
    409                                             xmin=self.data.xmin,xmax=self.data.xmax) 
    410             else: 
    411                 #single fit for Data1D 
    412                 self.manager._on_single_fit(qmin=self.qmin_x,qmax=self.qmax_x) 
     441         
     442        self.manager.schedule_for_fit( value=1,fitproblem =None)  
     443        if hasattr(self.data, "data"): 
     444            #single fit for Data2D 
     445            self.manager._on_single_fit(qmin=self.qmin_x,qmax=self.qmax_x, 
     446                                        ymin=self.data.ymin, ymax=self.data.ymax, 
     447                                        xmin=self.data.xmin,xmax=self.data.xmax) 
     448        else: 
     449            #single fit for Data1D 
     450            self.manager._on_single_fit(qmin=self.qmin_x,qmax=self.qmax_x) 
    413451                 
    414452            self.vbox.Layout() 
     
    416454            self.Layout() 
    417455            self.parent.GetSizer().Layout() 
    418         else: 
    419             wx.PostEvent(self.parent.parent, StatusEvent(status=\ 
    420                             "Select at least one parameter to fit ")) 
     456         
     457             
    421458   
    422     
    423     def _onTextEnter(self,event): 
    424         """ 
    425             set a flag to determine if the fitting range entered by the user is valid 
    426         """ 
    427        
    428         try: 
    429             flag=self.checkFitRange() 
    430             if flag==True and self.model!=None: 
    431                 self.manager.redraw_model(float(self.xmin.GetValue())\ 
    432                                                ,float(self.xmax.GetValue())) 
    433         except: 
    434  
    435             wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\ 
    436                             "Drawing  Error:wrong value entered %s"% sys.exc_value)) 
    437          
    438459    
    439460     
     
    576597            from DataLoader.qsmearing import smear_selection 
    577598            smear =smear_selection( self.data ) 
    578             if hasattr(self.data,"dx"): 
     599            if hasattr(self.data,"dxl"): 
    579600                msg= ": Resolution smearing parameters" 
    580             if hasattr(self.data,"dxl"): 
    581                 msg= ": Slit_l smearing parameters" 
    582601            if hasattr(self.data,"dxw"): 
    583                 msg= ": Slit_w smearing parameters" 
     602                msg= ": Slit smearing parameters" 
    584603            if smear ==None: 
    585604                wx.PostEvent(self.manager.parent, StatusEvent(status=\ 
  • sansview/perspectives/fitting/fitpanel.py

    rae9c692 rbb18ef1  
    3333        #Creating the default page --welcomed page 
    3434        self.about_page=None 
    35         from welcome_panel import PanelAbout 
     35        from sans.guiframe.welcome_panel import PanelAbout 
    3636        self.about_page = PanelAbout(self, -1) 
    3737        self.AddPage(self.about_page,"welcome!") 
     
    4040        #dictionary of miodel {model class name, model class} 
    4141        self.model_list_box={} 
     42        ## list of structure factor 
     43        self.struct_list_box=[] 
    4244        # save the title of the last page tab added 
    4345        self.fit_page_name=[] 
     
    101103            @param owner: the class responsible of plotting 
    102104        """ 
    103         self.event_owner = owner 
     105        self.event_owner=owner 
    104106         
    105107    def add_sim_page(self): 
     
    126128        if not name in self.fit_page_name : 
    127129            from fitpage1D import FitPage1D 
    128             panel = FitPage1D(parent=self,data=data, id=-1) 
     130            panel = FitPage1D(self,data, -1) 
    129131            panel.name=name 
    130132             
     
    149151        """ 
    150152        from modelpage import ModelPage 
    151          
     153        #print "fitpanel model", model 
    152154        panel = ModelPage(self,model,page_title, -1) 
    153155        panel.set_manager(self.manager) 
     
    169171        self.manager.draw_model(model, page_title) 
    170172         
     173    def new_help_add_model_page(self,model,description,page_title, qmin=0, qmax=0.1, npts=50): 
     174        """ 
     175            #TODO: fill in description 
     176             
     177            @param qmin: mimimum Q 
     178            @param qmax: maximum Q 
     179            @param npts: number of Q points 
     180        """ 
     181        ## storing page info 
     182        from pageInfo import  PageInfo 
     183        myinfo = PageInfo( self, model ) 
     184        myinfo.model_list_box = self.model_list_box 
     185        from modelpage import ModelPage 
     186         
     187        panel = ModelPage(self,myinfo,page_title) 
     188        panel.set_manager(self.manager) 
     189        panel.set_owner(self.event_owner) 
     190         
     191         
     192        self.AddPage(page=panel,caption="Model",select=True) 
     193        panel.populate_box( self.model_list_box) 
     194        panel.name = page_title 
     195        self.draw_model_name=page_title 
     196        self.model_page_number=self.GetSelection() 
     197        self.model_page=self.GetPage(self.GetSelection()) 
     198         
     199         
     200        # Set the range used to plot models 
     201        self.model_page.set_range(qmin, qmax, npts) 
     202         
     203        # We just created a model page, we are ready to plot the model 
     204        #self.manager.draw_model(model, model.name) 
     205        #FOR PLUGIN  for some reason model.name is = BASEcomponent 
     206        self.manager.draw_model(model, page_title) 
     207      
    171208         
    172209    def add_model_page(self,model,description,page_title, qmin=0, qmax=0.1, npts=50, topmenu=False): 
     
    193230            @return the current page selected 
    194231        """ 
     232        #return self.nb.GetCurrentPage() 
    195233        return self.GetPage(self.GetSelection() ) 
    196234   
    197     
     235     
     236      
    198237    def set_model_list(self,dict): 
    199238         """  
  • sansview/perspectives/fitting/fitproblem.py

    r925a30e rbb18ef1  
    4545        return self.smearer 
    4646     
     47    def save_model_name(self, name):   
     48        self.name_per_page= name 
     49         
     50         
     51    def get_name(self): 
     52        return self.name_per_page 
    4753     
    4854    def set_model(self,model,name): 
     
    5258             @param name: name created for model 
    5359        """ 
    54         self.model_list=[model,name] 
     60         
     61        if len(self.model_list)>0 and name==None: 
     62            self.model_list=[model,self.model_list[1]] 
     63        else: 
     64            self.model_list=[model,name] 
    5565 
    5666   
  • sansview/perspectives/fitting/fitting.py

    r0f7b597 rbb18ef1  
    8181        #Set park engine 
    8282        id3 = wx.NewId() 
    83         self.menu1.AppendCheckItem(id3, "park")  
    84         wx.EVT_MENU(owner, id3, self._onset_engine) 
     83        scipy_help= "Scipy Engine: Perform Simple fit. More in Help window...." 
     84        self.menu1.Append(id3, "Scipy",scipy_help)  
     85        wx.EVT_MENU(owner, id3,  self._onset_engine_scipy) 
     86         
     87        id3 = wx.NewId() 
     88        park_help = "Park Engine: Perform Complex fit. More in Help window...." 
     89        self.menu1.Append(id3, "park",park_help)  
     90        wx.EVT_MENU(owner, id3,  self._onset_engine_park) 
    8591         
    8692        #menu for model 
    8793        menu2 = wx.Menu() 
     94     
    8895        self.menu_mng.populate_menu(menu2, owner) 
    8996        id2 = wx.NewId() 
    9097        owner.Bind(models.EVT_MODEL,self._on_model_menu) 
    91         ## Allow fitpanel to access list of models 
     98       
    9299        self.fit_panel.set_owner(owner) 
    93100        self.fit_panel.set_model_list(self.menu_mng.get_model_list()) 
     
    96103        #create  menubar items 
    97104        return [(id, self.menu1, "Fitting"),(id2, menu2, "Model")] 
    98      
    99105     
    100106    def on_add_sim_page(self, event): 
     
    130136                
    131137                if item.name==graph.selected_plottable : 
     138                    if not hasattr(item, "group_id"): 
     139                        return [] 
    132140                    return [["Select data  for Fitting", \ 
    133141                             "Dialog with fitting parameters ", self._onSelect]]  
     
    240248        for item in self.panel.graph.plottables: 
    241249            if item.name == self.panel.graph.selected_plottable: 
    242                 ## reset the error back to data 
    243250                if len(self.err_dy)>0: 
    244251                    if item.name in  self.err_dy.iterkeys(): 
     
    354361                    model= list[0] 
    355362                    break 
    356             ## reset the current model with new fitted parameters     
    357363            i = 0 
    358364            for name in pars: 
     
    383389        """ 
    384390        if cpage!=None: 
    385             ## the fit perform was a single fit but selected  from the  
    386             ## simultaneous fit page 
    387391            self._single_fit_completed(result=result,pars=pars,cpage=cpage, 
    388392                                       qmin=qmin,qmax=qmax, 
     
    540544             
    541545        """ 
    542         #set an engine to perform fit 
    543         from sans.fit.Fitting import Fit 
    544         self.fitter= Fit(self._fit_engine) 
     546        ##Setting an id to store model and data 
    545547        self.fit_id= 0 
    546548        #Setting an id to store model and data 
    547549        if id!=None: 
    548550             self.fit_id= id 
    549         
     551        ##  count the number of fitproblem schedule to fit  
     552        fitproblem_count= 0 
     553        for value in self.page_finder.itervalues(): 
     554            if value.get_scheduled()==1: 
     555                fitproblem_count += 1 
     556        ## if simultaneous fit change automatically the engine to park 
     557        if fitproblem_count >1: 
     558            self._on_change_engine(engine='park') 
     559        from sans.fit.Fitting import Fit 
     560        self.fitter= Fit(self._fit_engine) 
     561         
     562         
    550563        for page, value in self.page_finder.iteritems(): 
    551564            try: 
     
    576589                            param_value = item[1] 
    577590                            param_name = item[0] 
     591     
    578592                            new_model.parameterset[ param_name].set( param_value ) 
    579593                         
     
    613627            if self.calc_thread != None and self.calc_thread.isrunning(): 
    614628                self.calc_thread.stop() 
    615             ## Perform a single fit , then need to page  
    616             if  self.fit_id==1: 
     629                        ## perform single fit 
     630            if  fitproblem_count==1: 
    617631                self.calc_thread =FitThread(parent =self.parent, 
    618632                                        fn= self.fitter, 
     
    644658            return 
    645659         
    646          
    647     def _onset_engine(self,event): 
     660    def _onset_engine_park(self,event): 
    648661        """  
    649             Toggle engine name from "park" to "scipy" or reverse if event received 
    650             @param event: wx.menu item checked 
    651         """ 
    652         if self._fit_engine== 'park': 
    653             self._on_change_engine('scipy') 
    654         else: 
    655             self._on_change_engine('park') 
    656              
    657         msg= "Engine set to: %s" % self._fit_engine 
    658         wx.PostEvent(self.parent, StatusEvent(status= msg )) 
    659    
     662            set engine to park 
     663        """ 
     664        self._on_change_engine('park') 
     665        
     666        
     667    def _onset_engine_scipy(self,event): 
     668        """  
     669            set engine to scipy 
     670        """ 
     671        self._on_change_engine('scipy') 
     672        
    660673     
    661674    def _on_change_engine(self, engine='park'): 
     
    665678        """ 
    666679        self._fit_engine = engine 
     680        wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine)) 
    667681    
    668682    
     
    681695        ## example trying to call set_panel on self.sim_page 
    682696        if current_pg != sim_page: 
    683             current_pg.set_panel(model) 
    684697            
    685             model.name="M"+str(self.index_model) 
     698            if len(self.page_finder[current_pg].get_model())==0: 
     699                 
     700                model.name="M"+str(self.index_model) 
     701                self.index_model += 1   
     702            else: 
     703                model.name= self.page_finder[current_pg].get_model()[0].name 
     704                 
    686705            try: 
    687                 metadata=self.page_finder[current_pg].get_data() 
    688                 M_name=model.name+"= "+name+"("+metadata.group_id+")" 
     706                metadata=self.page_finder[current_pg].get_plotted_data() 
     707                M_name = model.name+"= "+name+"("+metadata.name+")" 
    689708            except: 
    690                 M_name=model.name+"= "+name 
    691             self.index_model += 1   
    692              
    693             # save model name 
     709                M_name = model.name+"= "+name 
    694710            # save the name containing the data name with the appropriate model 
    695711            self.page_finder[current_pg].set_model(model,M_name) 
     712             
     713                 
     714            # save model name 
    696715            self.plot_helper(currpage= current_pg,qmin= None,qmax= None) 
    697             ## draw  self.sim_page and store information on the selected model 
    698716            if self.sim_page!=None: 
    699717                self.sim_page.add_model(self.page_finder) 
     
    719737        for page, value in self.page_finder.iteritems(): 
    720738            if page ==current_pg : 
    721                 self.plot_helper(currpage=page,qmin= qmin,qmax= qmax) 
    722739                break  
    723          
     740        self.plot_helper(currpage=page,qmin= qmin,qmax= qmax) 
    724741         
    725742         
     
    734751        if self.fit_panel.GetPageCount() >1: 
    735752            for page in self.page_finder.iterkeys(): 
    736                 if  page==currpage :   
     753                if  page == currpage :   
    737754                    data= self.page_finder[page].get_plotted_data() 
    738755                    list= self.page_finder[page].get_model() 
    739                     smearer= self.page_finder[page].get_smearer() 
    740                     model=list[0] 
     756                    smearer = self.page_finder[page].get_smearer() 
     757                    model = list[0] 
    741758                    break  
    742759            ## create Model 1D 
    743             if data!=None and data.__class__.__name__ != 'Data2D': 
     760            if data != None and data.__class__.__name__ != 'Data2D': 
    744761                x= numpy.zeros(len(data.x))   
    745                 y= numpy.zeros(len(data.x))  
     762                y= numpy.zeros(len(data.y))  
    746763                 
    747764                theory = Theory1D(x=x, y=y) 
    748765                theory.name = model.name 
    749                 theory.group_id = data.group_id 
     766                if hasattr(data ,"group_id"): 
     767                    theory.group_id = data.group_id 
    750768                theory.id = "Model" 
    751                  
    752                   
    753769                 
    754770                x_name, x_units = data.get_xaxis()  
     
    757773                theory.yaxis(y_name, y_units) 
    758774                if qmin == None : 
    759                    qmin = min(data.x) 
     775                    qmin = min(data.x) 
    760776                if qmax == None : 
    761                    qmax = max(data.x) 
     777                    qmax = max(data.x) 
     778                 
    762779                j=0 
    763780                try: 
     
    865882            @param evt: wx.menu event 
    866883        """ 
    867         name = evt.model.__name__ 
     884        name = evt.model.__class__.__name__ 
    868885        if hasattr(evt.model, "name"): 
    869886            name = evt.model.name 
    870         model=evt.model() 
     887        model=evt.model 
    871888        description=model.description 
    872889         
     
    875892        # the content will be updated and the plot refreshed 
    876893        self.fit_panel.add_model_page(model,description,name,topmenu=True) 
    877          
    878          
     894     
     895    def complete1D_from_data(self, output,model, data, x, elapsed, name): 
     896        """ 
     897             plot model 1D with data info  
     898        """ 
     899        y= output 
     900        x= data.x 
     901        theory = Theory1D(x=x, y=y) 
     902        theory.name = model.name 
     903        theory.group_id = data.group_id 
     904        theory.id = "Model" 
     905         
     906        x_name, x_units = data.get_xaxis()  
     907        y_name, y_units = data.get_yaxis()  
     908        theory.xaxis(x_name, x_units) 
     909        theory.yaxis(y_name, y_units) 
     910        wx.PostEvent(self.parent, NewPlotEvent(plot=theory, 
     911                                                title=str(data.name))) 
     912         
     913    def draw_model1D_from_Data(self, data, model,name=None, 
     914                                qmin=None, qmax=None, smearer= None): 
     915        """ 
     916            Draw model 1D from loaded data1D 
     917            @param data: loaded data 
     918            @param model: the model to plot 
     919        """ 
     920        x = data.x 
     921        self.model= model 
     922        if qmin == None : 
     923           qmin = min(data.x) 
     924        if qmax == None : 
     925           qmax = max(data.x) 
     926        if name ==None: 
     927            name=model.name 
     928        try: 
     929            from model_thread import Calc1D 
     930            ## If a thread is already started, stop it 
     931            if self.calc_thread != None and self.calc_thread.isrunning(): 
     932                self.calc_thread.stop() 
     933            self.calc_thread = Calc1D( x= x, 
     934                                      model= self.model,  
     935                                       qmin= qmin, 
     936                                       qmax= qmax, 
     937                                       name= name, 
     938                                       smearer= smearer, 
     939                            completefn= self.complete1D_from_data, 
     940                            updatefn= self.update1D) 
     941            self.calc_thread.queue() 
     942             
     943        except: 
     944            msg= " Error occurred when drawing %s Model 1D: "%self.model.name 
     945            msg+= " %s"%sys.exc_value 
     946            wx.PostEvent( self.parent, StatusEvent(status= msg )) 
     947            return   
     948             
    879949    def draw_model(self, model, name, data= None, description= None, 
    880950                   enable1D= True, enable2D= False, 
     
    907977                           qstep=qstep) 
    908978         
    909                
     979     
     980    def update1D(self,x, output): 
     981        """ 
     982            Update the output of plotting model 1D 
     983        """ 
     984        self.calc_thread.ready(1) 
     985     
     986    def complete1D(self, x,output, elapsed, name,data=None): 
     987        """ 
     988            Complete plotting 1D data 
     989        """  
     990        try: 
     991            y = output 
     992            new_plot = Theory1D(x, y) 
     993            new_plot.name = name 
     994            new_plot.xaxis("\\rm{Q}", 'A^{-1}') 
     995            new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") 
     996            new_plot.id ="Model" 
     997            new_plot.group_id ="Model" 
     998            # Pass the reset flag to let the plotting event handler 
     999            # know that we are replacing the whole plot 
     1000            wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 
     1001                             title="Analytical model 1D ", reset=True )) 
     1002             
     1003        except: 
     1004            msg= " Error occurred when drawing %s Model 1D: "%new_plot.name 
     1005            msg+= " %s"%sys.exc_value 
     1006            wx.PostEvent( self.parent, StatusEvent(status= msg )) 
     1007            return   
     1008         
     1009                  
    9101010    def _draw_model1D(self, model, name, description= None, enable1D= True, 
    9111011                      qmin= DEFAULT_QMIN, qmax= DEFAULT_QMAX, qstep= DEFAULT_NPTS): 
     
    9251025                           endpoint=True 
    9261026                           )       
    927         xlen= len(x) 
    928         y = numpy.zeros(xlen) 
    929          
    930         if  enable1D: 
    931             for i in range(xlen): 
    932                 y[i] = model.run(x[i])  
     1027        self.model= model 
     1028        if enable1D: 
    9331029            try: 
    934                 new_plot = Theory1D(x, y) 
    935                 new_plot.name = name 
    936                 new_plot.xaxis("\\rm{Q}", 'A^{-1}') 
    937                 new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") 
    938                 new_plot.id ="Model" 
    939                 new_plot.group_id ="Model" 
    940                 # Pass the reset flag to let the plotting event handler 
    941                 # know that we are replacing the whole plot 
    942                 wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 
    943                                  title="Analytical model 1D ", reset=True )) 
     1030                from model_thread import Calc1D 
     1031                ## If a thread is already started, stop it 
     1032                if self.calc_thread != None and self.calc_thread.isrunning(): 
     1033                    self.calc_thread.stop() 
     1034                self.calc_thread = Calc1D( x= x, 
     1035                                          model= self.model,  
     1036                                           qmin= qmin, 
     1037                                           qmax= qmax, 
     1038                                           name= name, 
     1039                                           data=None, 
     1040                                        smearer=None, 
     1041                                completefn= self.complete1D, 
     1042                                updatefn= self.update1D) 
     1043                self.calc_thread.queue() 
    9441044                 
    9451045            except: 
    946                 msg= " Error occurred when drawing %s Model 1D: "%new_plot.name 
     1046                msg= " Error occurred when drawing %s Model 1D: "%self.model.name 
    9471047                msg+= " %s"%sys.exc_value 
    9481048                wx.PostEvent( self.parent, StatusEvent(status= msg )) 
    949                 return 
    950  
    951  
    952      
    953     def update(self, output,time): 
     1049                return   
     1050                 
     1051 
     1052 
     1053         
     1054    def update2D(self, output,time=None): 
    9541055        """ 
    9551056            Update the output of plotting model 
    9561057        """ 
    957         pass 
    958      
    959     def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS): 
     1058        wx.PostEvent(self.parent, StatusEvent(status="Plot \ 
     1059        #updating ... ",type="update")) 
     1060        self.calc_thread.ready(0.01) 
     1061         
     1062         
     1063    def complete2D(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS): 
    9601064        """ 
    9611065            Complete get the result of modelthread and create model 2D 
     
    9711075     
    9721076        from DataLoader.data_info import Detector, Source 
     1077         
    9731078        detector = Detector() 
    9741079        theory.detector=[] 
     
    10471152        if enable2D: 
    10481153            try: 
    1049                 from sans.guiframe.model_thread import Calc2D 
    1050                 self.calc_thread = Calc2D(parent =self.parent,x=x, 
    1051                                            y=y,model= self.model,  
    1052                                            qmin=qmin, 
    1053                                            qmax=qmax, 
    1054                                            qstep=qstep, 
    1055                                 completefn=self.complete, 
    1056                                 updatefn=None) 
     1154                from model_thread import Calc2D 
     1155                ## If a thread is already started, stop it 
     1156                if self.calc_thread != None and self.calc_thread.isrunning(): 
     1157                    self.calc_thread.stop() 
     1158                self.calc_thread = Calc2D( x= x, 
     1159                                           y= y, model= self.model,  
     1160                                           qmin= qmin, 
     1161                                           qmax= qmax, 
     1162                                           qstep= qstep, 
     1163                                completefn= self.complete2D, 
     1164                                updatefn= self.update2D ) 
    10571165                self.calc_thread.queue() 
    1058                 self.calc_thread.ready(2.5) 
     1166                 
    10591167            except: 
    1060                 msg= "Draw model 2D error: " 
    1061                 wx.PostEvent(self.parent, StatusEvent(status="%s %s" % sys.exc_value)) 
    1062                 return 
    1063              
    1064    
    1065             
     1168                raise 
     1169     
    10661170    
    10671171if __name__ == "__main__": 
  • sansview/perspectives/fitting/modelpage.py

    raae8d23 rbb18ef1  
    11import sys 
    22import wx 
    3 import wx.lib 
     3import wx.lib.newevent 
    44import numpy 
    55import copy 
     
    2828    window_caption = "Fit Page" 
    2929    name="" 
    30      
    3130    def __init__(self, parent,model,name, *args, **kwargs): 
    3231        wx.ScrolledWindow.__init__(self, parent, *args, **kwargs) 
     
    3635        # model on which the fit would be performed 
    3736        self.model=model 
    38          
    39         ## Data member to store the dispersion object created 
     37        # Data member to store the dispersion object created 
    4038        self._disp_obj_dict = {} 
    41  
     39        self.back_up_model= model.clone() 
    4240        #list of dispersion paramaters 
    4341        self.disp_list=[] 
     
    8684        #------------------ sizer 4  draw------------------------   
    8785        
    88         
     86        ## structure combox box 
     87        self.structbox = wx.ComboBox(self, -1) 
    8988        # define combox box 
    9089        self.modelbox = wx.ComboBox(self, -1) 
    91          # preview selected model name 
    92         self.prevmodel_name=name 
    93         #print "model view prev_model",name 
    94         self.modelbox.SetValue(self.prevmodel_name) 
     90         
    9591        #enable model 2D draw 
    9692        self.enable2D= False 
     93        self.fitrange= True 
    9794        #filling sizer2 
    9895        ix = 0 
     
    10299        ix += 1 
    103100        self.sizer4.Add(self.modelbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     101        ix +=1 
     102        self.text_mult= wx.StaticText(self,-1,' x ') 
     103        self.sizer4.Add(self.text_mult,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     104        ix += 1 
     105        self.sizer4.Add(self.structbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     106         
     107        if hasattr(model ,"model2"): 
     108            name= model.model2.name 
     109 
     110            self.structbox.SetValue(name)           
     111        if hasattr(model ,"model1"): 
     112            name= model.model1.name 
     113            items = self.modelbox.GetItems() 
     114            self.modelbox.SetValue(name) 
     115        else: 
     116            #print "model view prev_model",name 
     117            self.modelbox.SetValue( name ) 
    104118        ix += 1 
    105119        id = wx.NewId() 
     
    190204        iy+=1  
    191205        self.sizer9.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    192         #----------sizer 10 draw------------------------------------------------------ 
    193         """ 
    194         id = wx.NewId() 
    195         self.btClose =wx.Button(self,id,'Close') 
    196         self.btClose.Bind(wx.EVT_BUTTON, self.onClose,id=id) 
    197         self.btClose.SetToolTipString("Close page.") 
    198          
    199         ix= 3 
    200         iy= 1 
    201         self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    202         ix +=1 
    203         self.sizer10.Add( self.btClose,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    204         ix =0 
    205         iy+=1 
    206         self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    207         """ 
     206         
    208207        # contains link between  model ,all its parameters, and panel organization 
    209208        self.parameters=[] 
     
    221220            self.set_panel(self.model) 
    222221        self.theta_cb=None 
    223         
     222         
    224223        
    225224        self.vbox.Layout() 
     
    231230        self.Layout() 
    232231        self.parent.GetSizer().Layout() 
    233          
    234     def _set_dispersion(self, par, disp_model): 
    235         """ 
    236             Utility method to set a dispersion model while making 
    237             sure that the dispersion model object doesn't go out 
    238             of scope. The models should be cleaned up so we don't 
    239             have to do this. 
    240         """ 
    241         # Store the object to make it persist outside the scope of this method 
    242         #TODO: refactor model to clean this up? 
    243         self._disp_obj_dict[par] = disp_model 
    244                      
    245         # Set the new model as the dispersion object for the selected parameter 
    246         self.model.set_dispersion(par, disp_model) 
    247          
    248     def set_model_description(self, model): 
    249          
    250         if model !=None and str(model.description)!=""and self.data==None: 
    251             self.sizer11.Clear(True) 
    252             self.box_description= wx.StaticBox(self, -1, 'Model Description') 
    253             boxsizer1 = wx.StaticBoxSizer(self.box_description, wx.VERTICAL) 
    254             boxsizer1.SetMinSize((320,20)) 
    255             self.description = wx.StaticText(self,-1,str(model.description)) 
    256             boxsizer1.Add(self.description, 0, wx.EXPAND)   
    257             self.sizer11.Add(boxsizer1,1, wx.EXPAND | wx.ALL, 2) 
     232    def set_model_description(self, model=None): 
     233         
     234        if model !=None: 
     235            description="description" 
     236        else: 
     237            description="" 
     238            if hasattr(model,description.lower())and self.data==None: 
     239                self.sizer11.Clear(True) 
     240                self.box_description= wx.StaticBox(self, -1, 'Model Description') 
     241                boxsizer1 = wx.StaticBoxSizer(self.box_description, wx.VERTICAL) 
     242                boxsizer1.SetMinSize((320,20)) 
     243                self.description = wx.StaticText(self,-1,str(model.description)) 
     244                boxsizer1.Add(self.description, 0, wx.EXPAND)   
     245                self.sizer11.Add(boxsizer1,1, wx.EXPAND | wx.ALL, 2) 
    258246       
    259247         
     
    278266            @param page: the page to populate 
    279267        """ 
    280         id=0 
    281         self.model_list_box=dict 
    282         list_name=[] 
    283         for item in  self.model_list_box.itervalues(): 
    284             name = item.__name__ 
    285             if hasattr(item, "name"): 
    286                 name = item.name 
    287             list_name.append(name) 
    288         list_name.sort()  
    289           
    290         for name in list_name: 
    291             self.modelbox.Insert(name,int(id)) 
    292             id+=1 
    293         wx.EVT_COMBOBOX(self.modelbox,-1, self._on_select_model)  
     268         
     269        self.model_list_box = dict.get_list() 
     270        
     271        for item , mylist in self.model_list_box.iteritems(): 
     272            separator= "---%s---"%item 
     273            self.modelbox.Append(separator,"separator") 
     274             
     275            for models in mylist: 
     276                model= models() 
     277                name = model.__class__.__name__ 
     278                if hasattr(model, "name"): 
     279                    name = model.name 
     280                self.modelbox.Append(name,models) 
     281            wx.EVT_COMBOBOX(self.modelbox,-1, self._on_select_model) 
     282            if item == "Structure Factors" : 
     283                for structs in mylist: 
     284                    struct= structs() 
     285                    name = struct.__class__.__name__ 
     286                    if hasattr(struct, "name"): 
     287                        name = struct.name 
     288                    self.structbox.Append(name,structs) 
     289                wx.EVT_COMBOBOX(self.structbox,-1, self._on_select_model) 
     290         
     291         
    294292        return 0 
    295293     
    296294 
    297295    def Set_DipersParam(self, event): 
    298         """ 
    299             This method is called when the user changes the state  
    300             of the "dispersity" radio buttons. 
    301              
    302             #TODO: correct the spelling mistake in the name of this method, start name with lowercase. 
    303         """ 
     296        if self.model ==None: 
     297            msg= " Select non - model value:%s !"%self.model 
     298            wx.PostEvent(self.parent.parent, StatusEvent(status= msg)) 
     299            return  
    304300        if self.enable_disp.GetValue(): 
    305             # The user selected to use dispersion/averaging 
    306301            if len(self.disp_list)==0: 
    307                 # This model contains no parameter to which we can apply dispersion/averaging 
    308302                ix=0 
    309303                iy=1 
     
    319313                return  
    320314            else: 
    321                 # Show the default dispersion/averaging sub-panel 
     315                if self.data !=None and self.model !=None: # allow to recognize data panel from model panel 
     316                     
     317                 
     318                    self.cb1.SetValue(False) 
     319                    self.select_all_param_helper() 
     320                 
    322321                self.populate_disp_box() 
    323322                self.set_panel_dispers(self.disp_list) 
    324323                 
    325324        else: 
    326             # The user selected not to use dispersion/averaging             
    327             # Make sure all parameters have the default Gaussian 
    328             # dispersion object with only a single point (no dispersion). 
    329             for p in self.model.dispersion.keys(): 
    330                 disp_model = GaussianDispersion() 
    331                 self._set_dispersion(p, disp_model) 
    332                      
    333             # Redraw the model 
    334             self._draw_model() 
     325            if self.data !=None and self.model!=None: 
     326                if self.cb1.GetValue(): 
     327                    self.select_all_param_helper() 
     328             
     329            if self.back_up_model!=None: 
     330                keys = self.back_up_model.getDispParamList() 
     331                keys.sort() 
     332                #disperse param into the initial state 
     333                for item in keys: 
     334                    value= self.back_up_model.getParam(item) 
     335                    self.model.setParam(item, value) 
     336                self._draw_model()  
     337             
    335338                 
    336339            self.fittable_param=[]         
     
    359362            for k,v in self.polydisp.iteritems(): 
    360363                if str(v)=="MyModel": 
    361                     # Remove the option until the rest of the code is ready for it 
     364                                # Remove the option until the rest of the code is ready for it 
    362365                    #self.disp_box.Insert("Select customized Model",id) 
    363366                    pass   
     
    433436        # If the 2D display is not currently enabled, plot the model in 2D  
    434437        # and set the enable2D flag. 
    435         if self.enable2D==False: 
    436             self.enable2D=True 
     438        if self.fitrange: 
     439            self.enable2D = True 
     440             
     441        if self.enable2D: 
    437442            self._draw_model() 
    438443            self.model_view.Disable() 
     444        
    439445             
    440446     
     
    449455         
    450456        self.set_panel(model) 
    451         self._draw_model(name) 
    452          
    453         # Select the model from the combo box 
    454         items = self.modelbox.GetItems() 
    455         for i in range(len(items)): 
    456             if items[i]==name: 
    457                 self.modelbox.SetSelection(i) 
    458                 self.model_view.SetFocus() 
     457        self._draw_model() 
     458        
     459        if hasattr(model ,"model2"): 
     460            name= model.model2.name 
     461            items = self.structbox.GetItems() 
     462            for i in range(len(items)): 
     463                if items[i]==name: 
     464                    self.structbox.SetSelection(i) 
     465                     
     466        if hasattr(model ,"model1"): 
     467            name= model.model1.name 
     468            items = self.modelbox.GetItems() 
     469            for i in range(len(items)): 
     470                if items[i]==name: 
     471                    self.modelbox.SetSelection(i) 
     472        else: 
     473            # Select the model from the combo box 
     474            items = self.modelbox.GetItems() 
     475            for i in range(len(items)): 
     476                if items[i]==name: 
     477                    self.modelbox.SetSelection(i) 
     478            self.structbox.SetValue("No Structure") 
     479                     
     480        self.model_view.SetFocus() 
    459481                 
    460482    def _on_select_Disp(self,event): 
     
    478500        self.Layout() 
    479501        self.parent.GetSizer().Layout() 
    480         for item in self.model_list_box.itervalues(): 
    481             name = item.__name__ 
    482             if hasattr(item, "name"): 
    483                 name = item.name 
    484             if name ==event.GetString(): 
    485                 model=item() 
    486                 self.model= model 
    487                 self.set_panel(model) 
    488                 self.name= name 
    489                 self.model_view.SetFocus() 
    490                 self.parent.model_page.name=name 
    491                 self.parent.draw_model_name=name 
     502        form_factor =self.modelbox.GetClientData(self.modelbox.GetCurrentSelection()) 
     503        struct_factor =self.structbox.GetClientData(self.structbox.GetCurrentSelection()) 
     504        
     505        if form_factor!="separator": 
     506            if struct_factor != None and struct_factor.__name__ != "NoStructure": 
     507                from sans.models.MultiplicationModel import MultiplicationModel 
     508                self.model= MultiplicationModel(form_factor(),struct_factor()) 
     509            else: 
     510                 self.model= form_factor() 
     511        else: 
     512            self.model=None  
     513            msg= " Select non - model value:%s !Please select another model"%name  
     514            wx.PostEvent(self.parent.parent, StatusEvent(status= msg)) 
    492515                
    493                 self._draw_model(name) 
    494              
     516        self.set_model_description(self.model) 
     517        self.set_panel(self.model) 
     518        self.name= self.model.name 
     519        self.model_view.SetFocus() 
     520        self.parent.model_page.name= self.name 
     521        self.parent.draw_model_name= self.name 
     522        self._draw_model() 
    495523             
    496524    def get_model_box(self):  
     
    522550        self.param_toFit=[] 
    523551        self.fixed_param=[] 
    524         self.model = model 
    525          
    526         self.set_model_description( self.model)  
    527          
    528         keys = self.model.getParamList() 
    529         #list of dispersion paramaters 
    530         self.disp_list=self.model.getDispParamList() 
    531         
    532         keys.sort() 
    533         ik=0 
    534         im=1 
    535          
    536         iy = 1 
    537         ix = 0 
    538         self.cb1 = wx.CheckBox(self, -1,"Select all", (10, 10)) 
    539         if self.data!=None: 
    540             wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param) 
    541             self.cb1.SetValue(False) 
    542         else: 
    543             self.cb1.Disable() 
    544             self.cb1.Hide() 
    545         
    546         self.sizer5.Add(self.cb1,(iy, ix),(1,1),\ 
    547                           wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    548         ix +=1 
    549         self.text2_2 = wx.StaticText(self, -1, 'Values') 
    550         self.sizer5.Add(self.text2_2,(iy, ix),(1,1),\ 
    551                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    552         ix +=2 
    553         self.text2_3 = wx.StaticText(self, -1, 'Errors') 
    554         self.sizer5.Add(self.text2_3,(iy, ix),(1,1),\ 
    555                             wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    556         self.text2_3.Hide()  
    557          
    558         
    559         ix +=1 
    560         self.text2_4 = wx.StaticText(self, -1, 'Units') 
    561         self.sizer5.Add(self.text2_4,(iy, ix),(1,1),\ 
    562                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    563         self.text2_4.Hide() 
    564         disp_list=self.model.getDispParamList() 
    565         for item in keys: 
    566             if not item in disp_list: 
    567                 iy += 1 
    568                 ix = 0 
    569      
    570                 cb = wx.CheckBox(self, -1, item, (10, 10)) 
    571                 if self.data!=None: 
    572                     cb.SetValue(False) 
    573                     wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) 
     552        if model !=None: 
     553            self.model = model 
     554             
     555            self.set_model_description( self.model)  
     556             
     557            keys = self.model.getParamList() 
     558            #list of dispersion paramaters 
     559            self.disp_list=self.model.getDispParamList() 
     560            
     561            keys.sort() 
     562            ik=0 
     563            im=1 
     564             
     565            iy = 1 
     566            ix = 0 
     567            self.cb1 = wx.CheckBox(self, -1,"Select all", (10, 10)) 
     568            if self.data!=None: 
     569                wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param) 
     570                self.cb1.SetValue(False) 
     571            else: 
     572                self.cb1.Disable() 
     573                self.cb1.Hide() 
     574            
     575            self.sizer5.Add(self.cb1,(iy, ix),(1,1),\ 
     576                              wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     577            ix +=1 
     578            self.text2_2 = wx.StaticText(self, -1, 'Values') 
     579            self.sizer5.Add(self.text2_2,(iy, ix),(1,1),\ 
     580                                wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     581            ix +=2 
     582            self.text2_3 = wx.StaticText(self, -1, 'Errors') 
     583            self.sizer5.Add(self.text2_3,(iy, ix),(1,1),\ 
     584                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     585            self.text2_3.Hide()  
     586             
     587            
     588            ix +=1 
     589            self.text2_4 = wx.StaticText(self, -1, 'Units') 
     590            self.sizer5.Add(self.text2_4,(iy, ix),(1,1),\ 
     591                                wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     592            self.text2_4.Hide() 
     593            disp_list=self.model.getDispParamList() 
     594            for item in keys: 
     595                if not item in disp_list: 
     596                    iy += 1 
     597                    ix = 0 
     598         
     599                    cb = wx.CheckBox(self, -1, item, (10, 10)) 
     600                    if self.data!=None: 
     601                        cb.SetValue(False) 
     602                        wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) 
     603                    else: 
     604                        cb.Disable() 
     605                    self.sizer5.Add( cb,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     606                    
     607                    ix += 1 
     608                    value= self.model.getParam(item) 
     609                    ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER) 
     610                    ctl1.SetValue(str (format_number(value))) 
     611                    ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter) 
     612                    ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter) 
     613                    self.sizer5.Add(ctl1, (iy,ix),(1,1), wx.EXPAND) 
     614                     
     615                    ix += 1 
     616                    text2=wx.StaticText(self, -1, '+/-') 
     617                    self.sizer5.Add(text2,(iy, ix),(1,1),\ 
     618                                    wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     619                    text2.Hide()   
     620                    ix += 1 
     621                    ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER) 
     622                    self.sizer5.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     623                    ctl2.Hide() 
     624                    
     625                    ix +=1 
     626                    # Units 
     627                    try: 
     628                        units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT) 
     629                    except: 
     630                        units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT) 
     631                    self.sizer5.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     632                
     633                    self.parameters.append([cb,ctl1,text2,ctl2]) 
     634                     
     635            iy+=1 
     636            self.sizer5.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     637             
     638            #Display units text on panel 
     639            for item in keys:    
     640                if self.model.details[item][0]!='': 
     641                    self.text2_4.Show() 
     642                    break 
    574643                else: 
    575                     cb.Disable() 
    576                 self.sizer5.Add( cb,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    577                 
    578                 ix += 1 
    579                 value= self.model.getParam(item) 
    580                 ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER) 
    581                 ctl1.SetValue(str (format_number(value))) 
    582                 ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter) 
    583                 ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter) 
    584                 self.sizer5.Add(ctl1, (iy,ix),(1,1), wx.EXPAND) 
    585                  
    586                 ix += 1 
    587                 text2=wx.StaticText(self, -1, '+/-') 
    588                 self.sizer5.Add(text2,(iy, ix),(1,1),\ 
    589                                 wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    590                 text2.Hide()   
    591                 ix += 1 
    592                 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER) 
    593                 self.sizer5.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    594                 ctl2.Hide() 
    595                 
    596                 ix +=1 
    597                 # Units 
    598                 try: 
    599                     units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT) 
    600                 except: 
    601                     units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT) 
    602                 self.sizer5.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    603             
    604                 self.parameters.append([cb,ctl1,text2,ctl2]) 
    605                  
    606         iy+=1 
    607         self.sizer5.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    608          
    609         #Display units text on panel 
    610         for item in keys:    
    611             if self.model.details[item][0]!='': 
    612                 self.text2_4.Show() 
    613                 break 
    614             else: 
    615                 self.text2_4.Hide() 
    616          
     644                    self.text2_4.Hide() 
     645             
    617646        self.vbox.Layout() 
    618647        self.SetScrollbars(20,20,55,40) 
     
    700729                     
    701730                    # Create the dispersion objects 
    702                     # Store the objects to make them persist outside the scope of this method 
    703                                 #TODO: refactor model to clean this up? 
    704                     self._disp_obj_dict[p+'values']  = values 
    705                     self._disp_obj_dict[p+'weights'] = weights 
    706731                    disp_model = ArrayDispersion() 
    707732                    disp_model.set_weights(values, weights) 
    708                     self._set_dispersion(p, disp_model) 
     733                    # Store the object to make it persist outside the scope of this method 
     734                    #TODO: refactor model to clean this up? 
     735                    self._disp_obj_dict[p] = disp_model 
     736                     
     737                    # Set the new model as the dispersion object for the selected parameter 
     738                    self.model.set_dispersion(p, disp_model) 
     739                     
    709740                     
    710741                    # Redraw the model 
     
    714745                    # The parameter was un-selected. Go back to Gaussian model (with 0 pts) 
    715746                    disp_model = GaussianDispersion() 
    716                     self._set_dispersion(p, disp_model) 
     747                    # Store the object to make it persist outside the scope of this method 
     748                    #TODO: refactor model to clean this up? 
     749                    self._disp_obj_dict[p] = disp_model 
     750                     
     751                    # Set the new model as the dispersion object for the selected parameter 
     752                    self.model.set_dispersion(p, disp_model) 
    717753                     
    718754                    # Redraw the model 
     
    733769        iy=1 
    734770                ### this will become a separate method 
    735         #TODO: don't hard code text values to be shown on the interface 
    736771        if type== "Select customized Model": 
    737772            ix=0 
     
    787822                name3=item+".nsigmas" 
    788823                iy += 1 
    789                  
    790                 # Make sure the dispersion model is Gaussian 
    791                 if not self.model.dispersion[item]['type'] == 'gaussian':  
    792                     disp_model = GaussianDispersion() 
    793                     self._set_dispersion(item, disp_model) 
    794                  
    795                 # Create the interface 
    796824                for p in self.model.dispersion[item].keys(): 
    797825                    #print "name 1 2 3", name1, name2, name3 
     
    966994            # If qmin and qmax have been modified, update qmin and qmax and  
    967995            # set the is_modified flag to True 
    968             if float(self.qmin.GetValue()) != self.qmin_x: 
    969                 self.qmin_x = float(self.qmin.GetValue()) 
    970                 is_modified = True 
    971             if float(self.qmax.GetValue()) != self.qmax_x: 
    972                 self.qmax_x = float(self.qmax.GetValue()) 
    973                 is_modified = True 
    974              
     996            from sans.guiframe.utils import check_value 
     997            if check_value( self.qmin, self.qmax): 
     998                if float(self.qmin.GetValue()) != self.qmin_x: 
     999                    self.qmin_x = float(self.qmin.GetValue()) 
     1000                    is_modified = True 
     1001                if float(self.qmax.GetValue()) != self.qmax_x: 
     1002                    self.qmax_x = float(self.qmax.GetValue()) 
     1003                    is_modified = True 
     1004                self.fitrange = True 
     1005            else: 
     1006                self.fitrange = False 
    9751007            if float(self.npts.GetValue()) !=  self.num_points: 
    9761008                self.num_points = float(self.npts.GetValue()) 
     
    9801012                self._draw_model()             
    9811013             
    982     def _draw_model(self, name=None): 
     1014    def _draw_model(self): 
    9831015        """ 
    9841016            Method to draw or refresh a plotted model. 
     
    9881020            [Note to coder: This way future changes will be done in only one place.]  
    9891021        """ 
    990         if name==None: 
    991             name= self.model.name 
    992         
    993         self.manager.draw_model(self.model, name, data=self.data, 
    994                                 qmin=self.qmin_x, qmax=self.qmax_x, 
    995                                 qstep= self.num_points, 
    996                                 enable2D=self.enable2D) 
     1022        if self.model !=None: 
     1023            self.manager.draw_model(self.model, self.model.name, data=self.data, 
     1024                                    qmin=self.qmin_x, qmax=self.qmax_x, 
     1025                                    qstep= self.num_points, 
     1026                                    enable2D=self.enable2D) 
    9971027        
    9981028    def select_param(self,event): 
  • sansview/perspectives/fitting/models.py

    r43eb424 rbb18ef1  
    1010 
    1111import wx 
     12import wx.lib.newevent 
    1213import imp 
    1314import os,sys,math 
     
    6667        pass 
    6768    return plugins 
     69 
     70class ModelList(object): 
     71    """ 
     72        Contains dictionary of model and their type 
     73    """ 
     74    def __init__(self): 
     75        self.mydict={} 
     76         
     77    def set_list(self, name, mylist): 
     78        """ 
     79            @param name: the type of the list 
     80            @param mylist: the list to add 
     81        """ 
     82        if name not in self.mydict.keys(): 
     83            self.mydict[name] = mylist 
     84             
     85             
     86    def get_list(self): 
     87        """ 
     88         return all the list stored in a dictionary object 
     89        """ 
     90        return self.mydict 
     91         
    6892class ModelManager: 
    69      
    70     ## Dictionary of models 
    71     model_list = {} 
    72     indep_model_list = {} 
    73     model_list_box = {} 
    74     custom_models={} 
     93    ## external dict for models 
     94    model_combobox = ModelList() 
     95    ## Dictionary of form models 
     96    form_factor_dict = {} 
     97    ## dictionary of other 
     98    struct_factor_dict = {} 
     99    ##list of form factors 
     100    shape_list =[] 
     101    ## independent shape model list 
     102    shape_indep_list = [] 
     103    ##list of structure factors  
     104    struct_list= [] 
     105    ## list of added models 
    75106    plugins=[] 
    76     indep_model=[] 
    77     ## Event owner 
     107    ## Event owner (guiframe) 
    78108    event_owner = None 
    79109     
     
    86116            @return: the next free event ID following the new menu events 
    87117        """ 
    88         self.model_list = {} 
    89         self.model_list_box = {} 
    90         
    91          
     118        ## form factor 
    92119        from sans.models.SphereModel import SphereModel 
    93         self.model_list[str(wx.NewId())] =  SphereModel 
     120        self.shape_list.append(SphereModel) 
    94121         
    95122        from sans.models.CylinderModel import CylinderModel 
    96         self.model_list[str(wx.NewId())] =CylinderModel 
     123        self.shape_list.append(CylinderModel) 
    97124       
    98125        from sans.models.CoreShellModel import CoreShellModel 
    99         self.model_list[str(wx.NewId())] = CoreShellModel  
     126        self.shape_list.append(CoreShellModel) 
    100127         
    101128        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel 
    102         self.model_list[str(wx.NewId())] =CoreShellCylinderModel 
     129        self.shape_list.append(CoreShellCylinderModel) 
    103130         
    104131        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel 
    105         self.model_list[str(wx.NewId())] =EllipticalCylinderModel 
     132        self.shape_list.append(EllipticalCylinderModel) 
    106133         
    107134        from sans.models.EllipsoidModel import EllipsoidModel 
    108         self.model_list[str(wx.NewId())] = EllipsoidModel  
     135        self.shape_list.append(EllipsoidModel) 
     136          
     137        from sans.models.LineModel import LineModel 
     138        self.shape_list.append(LineModel) 
     139         
     140        ## Structure factor  
     141        from sans.models.NoStructure import NoStructure 
     142        self.struct_list.append(NoStructure) 
    109143         
    110144        from sans.models.SquareWellStructure import SquareWellStructure 
    111         self.model_list[str(wx.NewId())] =  SquareWellStructure 
     145        self.struct_list.append(SquareWellStructure) 
    112146         
    113147        from sans.models.HardsphereStructure import HardsphereStructure 
    114         self.model_list[str(wx.NewId())] =  HardsphereStructure 
    115          
     148        self.struct_list.append(HardsphereStructure) 
     149          
    116150        from sans.models.StickyHSStructure import StickyHSStructure 
    117         self.model_list[str(wx.NewId())] =  StickyHSStructure 
     151        self.struct_list.append(StickyHSStructure) 
    118152         
    119153        from sans.models.HayterMSAStructure import HayterMSAStructure 
    120         self.model_list[str(wx.NewId())] =  HayterMSAStructure 
    121          
    122         from sans.models.LineModel import LineModel 
    123         self.model_list[str(wx.NewId())]  = LineModel 
    124          
    125          
    126         model_info="shape-independent models" 
    127          
     154        self.struct_list.append(HayterMSAStructure) 
     155         
     156         
     157        ##shape-independent models 
    128158        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte 
    129         self.indep_model.append(BEPolyelectrolyte ) 
    130          
     159        self.shape_indep_list.append(BEPolyelectrolyte ) 
     160        self.form_factor_dict[str(wx.NewId())] =  [SphereModel] 
    131161        from sans.models.DABModel import DABModel 
    132         self.indep_model.append(DABModel ) 
     162        self.shape_indep_list.append(DABModel ) 
    133163         
    134164        from sans.models.GuinierModel import GuinierModel 
    135         self.indep_model.append(GuinierModel ) 
     165        self.shape_indep_list.append(GuinierModel ) 
    136166         
    137167        from sans.models.DebyeModel import DebyeModel 
    138         self.indep_model.append(DebyeModel ) 
     168        self.shape_indep_list.append(DebyeModel ) 
     169         
     170        from sans.models.PorodModel import PorodModel 
     171        self.shape_indep_list.append(PorodModel ) 
    139172         
    140173        from sans.models.FractalModel import FractalModel 
     
    142175            def _Fractal(self, x): 
    143176                return FractalModel._Fractal(self, math.fabs(x)) 
    144         self.indep_model.append(FractalAbsModel) 
     177        self.shape_indep_list.append(FractalAbsModel) 
    145178         
    146179        from sans.models.LorentzModel import LorentzModel 
    147         self.indep_model.append( LorentzModel)  
     180        self.shape_indep_list.append( LorentzModel)  
    148181             
    149182        from sans.models.PowerLawModel import PowerLawModel 
     
    154187                except: 
    155188                    print sys.exc_value   
    156         self.indep_model.append( PowerLawAbsModel ) 
     189        self.shape_indep_list.append( PowerLawAbsModel ) 
    157190        from sans.models.TeubnerStreyModel import TeubnerStreyModel 
    158         self.indep_model.append(TeubnerStreyModel ) 
     191        self.shape_indep_list.append(TeubnerStreyModel ) 
    159192     
    160193        #Looking for plugins 
     
    173206            @return: the next free event ID following the new menu events 
    174207        """ 
     208        ## Fill model lists 
    175209        self._getModelList() 
     210        ## store reference to model menu of guiframe 
     211        self.modelmenu = modelmenu 
     212        ## guiframe reference 
    176213        self.event_owner = event_owner 
    177         shape_submenu= wx.Menu()  
    178         indep_submenu = wx.Menu() 
     214         
     215         
     216        shape_submenu = wx.Menu() 
     217        shape_indep_submenu = wx.Menu() 
     218        structure_factor = wx.Menu() 
    179219        added_models = wx.Menu() 
    180         for id_str,value in self.model_list.iteritems(): 
    181             item = self.model_list[id_str]() 
    182             name = item.__class__.__name__ 
    183             if hasattr(item, "name"): 
    184                 name = item.name 
    185             self.model_list_box[name] =value 
    186             shape_submenu.Append(int(id_str), name, name) 
    187             wx.EVT_MENU(event_owner, int(id_str), self._on_model) 
    188         modelmenu.AppendMenu(wx.NewId(), "Shapes...", shape_submenu, "List of shape-based models") 
    189         id = wx.NewId() 
    190         if len(self.indep_model_list) == 0: 
    191             for items in self.indep_model: 
    192                 #if item not in self.indep_model_list.values(): 
    193                     #self.indep_model_list[str(id)] = item 
    194                 self.model_list[str(id)]=items 
    195                 item=items() 
    196                 name = item.__class__.__name__ 
    197                 if hasattr(item, "name"): 
    198                     name = item.name 
    199                 indep_submenu.Append(id,name, name) 
    200                 self.model_list_box[name] =items 
    201                 wx.EVT_MENU(event_owner, int(id), self._on_model) 
    202                 id = wx.NewId()          
    203         modelmenu.AppendMenu(wx.NewId(), "Shape-independent...", indep_submenu, "List of shape-independent models") 
    204         id = wx.NewId() 
    205         if len(self.custom_models) == 0: 
    206             for items in self.plugins: 
    207                 #if item not in self.custom_models.values(): 
    208                     #self.custom_models[str(id)] = item 
    209                 self.model_list[str(id)]=items 
    210                 name = items.__name__ 
    211                 if hasattr(items, "name"): 
    212                     name = items.name 
    213                 added_models.Append(id, name, name) 
    214                 self.model_list_box[name] =items 
    215                 wx.EVT_MENU(event_owner, int(id), self._on_model) 
    216                 id = wx.NewId() 
    217         modelmenu.AppendMenu(wx.NewId(),"Added models...", added_models, "List of additional models") 
     220        ## create menu with shape 
     221        self._fill_menu( menuinfo = ["shapes",shape_submenu," simple shape"], 
     222                         list1 = self.shape_list, 
     223                         list2 = self.struct_list ) 
     224        self._fill_menu( menuinfo = ["Shape-independent",shape_indep_submenu, 
     225                                    "List of shape-independent models"], 
     226                         list1 = self.shape_indep_list, 
     227                         list2 = self.struct_list ) 
     228         
     229        self._fill_simple_menu( menuinfo= ["Structure Factors",structure_factor, 
     230                                          "List of Structure factors models" ], 
     231                                list1= self.struct_list ) 
     232         
     233        self._fill_simple_menu( menuinfo = ["Added models", added_models, 
     234                                            "List of additional models"], 
     235                                 list1= self.plugins) 
    218236        return 0 
    219237     
     238    def _fill_simple_menu(self,menuinfo, list1): 
     239        """ 
     240            Fill the menu with list item 
     241            @param modelmenu: the menu to fill 
     242            @param menuinfo: submenu item for the first column of this modelmenu 
     243                             with info.Should be a list : 
     244                             [name(string) , menu(wx.menu), help(string)] 
     245            @param list1: contains item (form factor )to fill modelmenu second column 
     246        """ 
     247        if len(list1)>0: 
     248            self.model_combobox.set_list(menuinfo[0],list1) 
     249               
     250            for item in list1: 
     251                id = wx.NewId()  
     252                struct_factor=item() 
     253                struct_name = struct_factor.__class__.__name__ 
     254                if hasattr(struct_factor, "name"): 
     255                    struct_name = struct_factor.name 
     256                     
     257                menuinfo[1].Append(int(id),struct_name,struct_name) 
     258                if not  item in self.struct_factor_dict.itervalues(): 
     259                    self.struct_factor_dict[str(id)]= item 
     260                wx.EVT_MENU(self.event_owner, int(id), self._on_model) 
     261                 
     262        id = wx.NewId()          
     263        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2]) 
     264         
     265         
     266         
     267    def _fill_menu(self,menuinfo, list1,list2  ): 
     268        """ 
     269            Fill the menu with list item 
     270            @param menuinfo: submenu item for the first column of this modelmenu 
     271                             with info.Should be a list : 
     272                             [name(string) , menu(wx.menu), help(string)] 
     273            @param list1: contains item (form factor )to fill modelmenu second column 
     274            @param list2: contains item (Structure factor )to fill modelmenu third column 
     275        """ 
     276        if len(list1)>0: 
     277            self.model_combobox.set_list(menuinfo[0],list1) 
     278             
     279            for item in list1:    
     280                form_factor= item() 
     281                form_name = form_factor.__class__.__name__ 
     282                if hasattr(form_factor, "name"): 
     283                    form_name = form_factor.name 
     284                ### store form factor to return to other users    
     285                newmenu= wx.Menu() 
     286                if len(list2)>0: 
     287                    for model  in list2: 
     288                        id = wx.NewId() 
     289                        struct_factor = model() 
     290                        name = struct_factor.__class__.__name__ 
     291                        if hasattr(struct_factor, "name"): 
     292                            name = struct_factor.name 
     293                        newmenu.Append(id,name, name) 
     294                        wx.EVT_MENU(self.event_owner, int(id), self._on_model) 
     295                        ## save form_fact and struct_fact 
     296                        self.form_factor_dict[int(id)] = [form_factor,struct_factor] 
     297                         
     298                form_id= wx.NewId()     
     299                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2]) 
     300        id=wx.NewId() 
     301        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2]) 
     302         
     303         
     304         
     305         
    220306    def _on_model(self, evt): 
    221307        """ 
     
    223309            @param event: wx menu event 
    224310        """ 
    225         if str(evt.GetId()) in self.model_list.keys(): 
    226             # Notify the application manager that a new model has been set 
    227             #self.app_manager.set_model(self.model_list[str(evt.GetId())]()) 
    228              
    229             #TODO: post a model event to update all panels that need 
    230             #evt = ModelEvent(model=self.model_list[str(evt.GetId())]()) 
    231             
    232             model = self.model_list[str(evt.GetId())] 
    233             evt = ModelEvent(model= model ) 
    234             wx.PostEvent(self.event_owner, evt) 
     311        if int(evt.GetId()) in self.form_factor_dict.keys(): 
     312            from sans.models.MultiplicationModel import MultiplicationModel 
     313            model1, model2 = self.form_factor_dict[int(evt.GetId())] 
     314            model = MultiplicationModel(model1, model2) 
     315                
     316        else: 
     317            model= self.struct_factor_dict[str(evt.GetId())]() 
     318             
     319        evt = ModelEvent( model= model ) 
     320        wx.PostEvent(self.event_owner, evt) 
    235321         
    236322    def get_model_list(self):     
    237323        """ @ return dictionary of models for fitpanel use """ 
    238         return self.model_list_box 
    239      
    240      
    241      
    242   
     324        return self.model_combobox 
     325     
     326     
     327    def get_form_struct(self): 
     328        """ retunr list of form structures""" 
     329        return self.struct_list 
     330         
     331     
     332     
     333   
Note: See TracChangeset for help on using the changeset viewer.