source: sasview/sansview/perspectives/fitting/models.py @ 2fc9243

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 2fc9243 was 81bece4, checked in by Gervaise Alina <gervyh@…>, 15 years ago

refactor models.py

  • Property mode set to 100644
File size: 17.1 KB
RevLine 
[33afff7]1#TODO: add comments to document this module
2#TODO: clean-up the exception handling.
[e7b1ccf]3
[33afff7]4#TODO: clean-up the FractalAbsModel and PowerLawAbsModel menu items. Those
5#      model definitions do not belong here. They belong with the rest of the
6#      models.
7
[d89f09b]8import wx
[bb18ef1]9import wx.lib.newevent
[b30f001]10import imp
[442895f]11import os,sys,math
[d89f09b]12import os.path
[8d78399]13
[d89f09b]14(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
[e7b1ccf]15from sans.guicomm.events import StatusEvent 
[33afff7]16# Time is needed by the log method
17import time
[2dbb681]18
[33afff7]19# Explicitly import from the pluginmodel module so that py2exe
20# places it in the distribution. The Model1DPlugin class is used
21# as the base class of plug-in models.
22from sans.models.pluginmodel import Model1DPlugin
[00561739]23   
[b30f001]24def log(message):
25    out = open("plugins.log", 'a')
26    out.write("%10g%s\n" % (time.clock(), message))
27    out.close()
28
[aa92772]29def findModels():
[33afff7]30    log("looking for models in: %s/plugins" % os.getcwd())
[b30f001]31    if os.path.isdir('plugins'):
32        return _findModels('plugins')
33    return []
[aa92772]34   
[bfe4644]35def _check_plugin(model, name):
36    """
37        Do some checking before model adding plugins in the list
38        @param model: class model to add into the plugin list
39        @param name:name of the module plugin
[8d78399]40        @return model: model if valid model or None if not valid
[bfe4644]41    """
42    #Check is the plugin is of type Model1DPlugin
43    if not issubclass(model, Model1DPlugin):
44        msg= "Plugin %s must be of type Model1DPlugin \n"%str(name)
45        log(msg)
[8d78399]46        return None
[bfe4644]47    if model.__name__!="Model":
48        msg= "Plugin %s class name must be Model \n"%str(name)
49        log(msg)
[8d78399]50        return None
[bfe4644]51    try:
52        new_instance= model()
53    except:
54        msg="Plugin %s error in __init__ \n\t: %s %s\n"%(str(name),
55                                    str(sys.exc_type),sys.exc_value)
56        log(msg)
[8d78399]57        return None
[bfe4644]58   
59    new_instance= model() 
60    if hasattr(new_instance,"function"):
61        try:
62           value=new_instance.function()
63        except:
64           msg="Plugin %s: error writing function \n\t :%s %s\n "%(str(name),
65                                    str(sys.exc_type),sys.exc_value)
66           log(msg)
[8d78399]67           return None
[bfe4644]68    else:
69       msg="Plugin  %s needs a method called function \n"%str(name)
70       log(msg)
[8d78399]71       return None
[bfe4644]72    return model
73 
74 
[1c66bc5]75def _findModels(dir):
76    # List of plugin objects
77    plugins = []
78    # Go through files in plug-in directory
79    try:
80        list = os.listdir(dir)
81        for item in list:
82            toks = os.path.splitext(os.path.basename(item))
83            if toks[1]=='.py' and not toks[0]=='__init__':
84                name = toks[0]
85           
86                path = [os.path.abspath(dir)]
87                file = None
88                try:
89                    (file, path, info) = imp.find_module(name, path)
90                    module = imp.load_module( name, file, item, info )
91                    if hasattr(module, "Model"):
92                        try:
[bfe4644]93                            if _check_plugin(module.Model, name)!=None:
94                                plugins.append(module.Model)
[1c66bc5]95                        except:
[bfe4644]96                            msg="Error accessing Model"
97                            msg+="in %s\n  %s %s\n" % (name,
98                                    str(sys.exc_type), sys.exc_value)
99                            log(msg)
[1c66bc5]100                except:
[bfe4644]101                    msg="Error accessing Model"
102                    msg +=" in %s\n  %s %s \n" %(name,
103                                    str(sys.exc_type), sys.exc_value)
104                    log(msg)
[1c66bc5]105                finally:
[a92d51b]106             
[1c66bc5]107                    if not file==None:
108                        file.close()
109    except:
[33afff7]110        # Don't deal with bad plug-in imports. Just skip.
[1c66bc5]111        pass
112    return plugins
[bb18ef1]113
114class ModelList(object):
115    """
116        Contains dictionary of model and their type
117    """
118    def __init__(self):
119        self.mydict={}
120       
121    def set_list(self, name, mylist):
122        """
123            @param name: the type of the list
124            @param mylist: the list to add
125        """
126        if name not in self.mydict.keys():
127            self.mydict[name] = mylist
128           
129           
130    def get_list(self):
131        """
132         return all the list stored in a dictionary object
133        """
134        return self.mydict
135       
[d89f09b]136class ModelManager:
[bb18ef1]137    ## external dict for models
138    model_combobox = ModelList()
139    ## Dictionary of form models
140    form_factor_dict = {}
141    ## dictionary of other
142    struct_factor_dict = {}
143    ##list of form factors
144    shape_list =[]
145    ## independent shape model list
146    shape_indep_list = []
147    ##list of structure factors
148    struct_list= []
[376916c]149    ##list of model allowing multiplication
150    multiplication_factor=[]
[bb18ef1]151    ## list of added models
[b30f001]152    plugins=[]
[bb18ef1]153    ## Event owner (guiframe)
[d89f09b]154    event_owner = None
155   
156    def _getModelList(self):
157        """
158            List of models we want to make available by default
159            for this application
[e7b1ccf]160       
[d89f09b]161            @return: the next free event ID following the new menu events
162        """
[bb18ef1]163        ## form factor
[442895f]164        from sans.models.SphereModel import SphereModel
[bb18ef1]165        self.shape_list.append(SphereModel)
[376916c]166        self.multiplication_factor.append(SphereModel)
[442895f]167       
168        from sans.models.CoreShellModel import CoreShellModel
[bb18ef1]169        self.shape_list.append(CoreShellModel)
[5eb9154]170        self.multiplication_factor.append(CoreShellModel)
[cee6867]171       
[eddff027]172        from sans.models.VesicleModel import VesicleModel
173        self.shape_list.append(VesicleModel)
[5eb9154]174        self.multiplication_factor.append(VesicleModel)
175       
176        from sans.models.MultiShellModel import MultiShellModel
177        self.shape_list.append(MultiShellModel)
178        self.multiplication_factor.append(MultiShellModel)
[eddff027]179       
[cee6867]180        from sans.models.BinaryHSModel import BinaryHSModel
181        self.shape_list.append(BinaryHSModel)
182       
[eddff027]183        from sans.models.CylinderModel import CylinderModel
184        self.shape_list.append(CylinderModel)
185        self.multiplication_factor.append(CylinderModel)
186       
187        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
188        self.shape_list.append(CoreShellCylinderModel)
[5eb9154]189        self.multiplication_factor.append(CoreShellCylinderModel)
[cee6867]190       
191        from sans.models.HollowCylinderModel import HollowCylinderModel
192        self.shape_list.append(HollowCylinderModel)
[5eb9154]193        self.multiplication_factor.append(HollowCylinderModel)
[eddff027]194             
195        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
196        self.shape_list.append(FlexibleCylinderModel)
[72f719b]197
[eddff027]198       
199        from sans.models.StackedDisksModel import StackedDisksModel
200        self.shape_list.append(StackedDisksModel)
[5eb9154]201        self.multiplication_factor.append(StackedDisksModel)
[eddff027]202       
203        from sans.models.ParallelepipedModel import ParallelepipedModel
204        self.shape_list.append(ParallelepipedModel)
[72f719b]205        self.multiplication_factor.append(ParallelepipedModel)
[cee6867]206       
[442895f]207        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
[bb18ef1]208        self.shape_list.append(EllipticalCylinderModel)
[72f719b]209        self.multiplication_factor.append(EllipticalCylinderModel)
210               
[442895f]211        from sans.models.EllipsoidModel import EllipsoidModel
[bb18ef1]212        self.shape_list.append(EllipsoidModel)
[376916c]213        self.multiplication_factor.append(EllipsoidModel)
[eddff027]214     
215        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
216        self.shape_list.append(CoreShellEllipsoidModel)
[5eb9154]217        self.multiplication_factor.append(CoreShellEllipsoidModel)
[bb18ef1]218         
[e65050e]219        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
220        self.shape_list.append(TriaxialEllipsoidModel)
[9002927]221        self.multiplication_factor.append(TriaxialEllipsoidModel)
[e65050e]222       
223        from sans.models.LamellarModel import LamellarModel
224        self.shape_list.append(LamellarModel)
225       
226        from sans.models.LamellarFFHGModel import LamellarFFHGModel
227        self.shape_list.append(LamellarFFHGModel)
228       
229        from sans.models.LamellarPSModel import LamellarPSModel
230        self.shape_list.append(LamellarPSModel)
[7a69683]231     
[e65050e]232        from sans.models.LamellarPSHGModel import LamellarPSHGModel
233        self.shape_list.append(LamellarPSHGModel)
[7a69683]234     
[376916c]235        ## Structure factor
[8346667]236        from sans.models.SquareWellStructure import SquareWellStructure
[bb18ef1]237        self.struct_list.append(SquareWellStructure)
[8346667]238       
239        from sans.models.HardsphereStructure import HardsphereStructure
[bb18ef1]240        self.struct_list.append(HardsphereStructure)
241         
[8346667]242        from sans.models.StickyHSStructure import StickyHSStructure
[bb18ef1]243        self.struct_list.append(StickyHSStructure)
[8346667]244       
245        from sans.models.HayterMSAStructure import HayterMSAStructure
[bb18ef1]246        self.struct_list.append(HayterMSAStructure)
[43eb424]247       
248       
[bb18ef1]249        ##shape-independent models
[442895f]250        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
[bb18ef1]251        self.shape_indep_list.append(BEPolyelectrolyte )
252        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
[442895f]253        from sans.models.DABModel import DABModel
[bb18ef1]254        self.shape_indep_list.append(DABModel )
[442895f]255       
[f39511b]256        from sans.models.GuinierModel import GuinierModel
[bb18ef1]257        self.shape_indep_list.append(GuinierModel )
[f39511b]258       
[442895f]259        from sans.models.DebyeModel import DebyeModel
[bb18ef1]260        self.shape_indep_list.append(DebyeModel )
261       
262        from sans.models.PorodModel import PorodModel
263        self.shape_indep_list.append(PorodModel )
[442895f]264       
[cee6867]265        from sans.models.PeakGaussModel import PeakGaussModel
266        self.shape_indep_list.append(PeakGaussModel)
267       
268        from sans.models.PeakLorentzModel import PeakLorentzModel
269        self.shape_indep_list.append(PeakLorentzModel)
270       
[81bece4]271        from sans.models.FractalAbsModel import FractalAbsModel
[bb18ef1]272        self.shape_indep_list.append(FractalAbsModel)
[442895f]273       
274        from sans.models.LorentzModel import LorentzModel
[bb18ef1]275        self.shape_indep_list.append( LorentzModel) 
[442895f]276           
[81bece4]277        from sans.models.PowerLawAbsModel import PowerLawAbsModel
[bb18ef1]278        self.shape_indep_list.append( PowerLawAbsModel )
[81bece4]279       
[442895f]280        from sans.models.TeubnerStreyModel import TeubnerStreyModel
[bb18ef1]281        self.shape_indep_list.append(TeubnerStreyModel )
[eddff027]282       
283        from sans.models.LineModel import LineModel
284        self.shape_indep_list.append(LineModel)
[2dbb681]285   
[49b7efa]286        #Looking for plugins
287        self.plugins = findModels()
288       
[d89f09b]289        return 0
290
291   
292    def populate_menu(self, modelmenu, event_owner):
293        """
294            Populate a menu with our models
295           
296            @param id: first menu event ID to use when binding the menu events
297            @param modelmenu: wx.Menu object to populate
298            @param event_owner: wx object to bind the menu events to
299            @return: the next free event ID following the new menu events
300        """
[bb18ef1]301        ## Fill model lists
[d89f09b]302        self._getModelList()
[bb18ef1]303        ## store reference to model menu of guiframe
304        self.modelmenu = modelmenu
305        ## guiframe reference
[d89f09b]306        self.event_owner = event_owner
[bb18ef1]307       
308       
309        shape_submenu = wx.Menu()
310        shape_indep_submenu = wx.Menu()
311        structure_factor = wx.Menu()
[b30f001]312        added_models = wx.Menu()
[376916c]313        multip_models = wx.Menu()
[bb18ef1]314        ## create menu with shape
[376916c]315        self._fill_simple_menu( menuinfo = ["Shapes",shape_submenu," simple shape"],
316                         list1 = self.shape_list )
317       
318        self._fill_simple_menu( menuinfo = ["Shape-Independent",shape_indep_submenu,
[bb18ef1]319                                    "List of shape-independent models"],
[376916c]320                         list1 = self.shape_indep_list )
[bb18ef1]321       
322        self._fill_simple_menu( menuinfo= ["Structure Factors",structure_factor,
323                                          "List of Structure factors models" ],
324                                list1= self.struct_list )
325       
[bfe4644]326        self._fill_plugin_menu( menuinfo = ["Customized Models", added_models,
[376916c]327                                            "List of additional models"],
328                                 list1= self.plugins )
329       
330        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
331                                  "mulplication of 2 models"],
332                                   list1 = self.multiplication_factor ,
333                                   list2 =  self.struct_list)
334       
[c77d859]335       
[d89f09b]336        return 0
337   
[bfe4644]338    def _fill_plugin_menu(self,menuinfo, list1):
339        """
340            fill the plugin menu with costumized models
341        """
342        if len(list1)==0:
343            id = wx.NewId() 
344            msg= "No model available check plugins.log for errors to fix problem"
345            menuinfo[1].Append(int(id),"Empty",msg)
346        self._fill_simple_menu( menuinfo,list1)
347       
348       
[bb18ef1]349    def _fill_simple_menu(self,menuinfo, list1):
350        """
351            Fill the menu with list item
352            @param modelmenu: the menu to fill
353            @param menuinfo: submenu item for the first column of this modelmenu
354                             with info.Should be a list :
355                             [name(string) , menu(wx.menu), help(string)]
356            @param list1: contains item (form factor )to fill modelmenu second column
357        """
358        if len(list1)>0:
359            self.model_combobox.set_list(menuinfo[0],list1)
[e7b1ccf]360           
[bb18ef1]361            for item in list1:
[e7b1ccf]362                try:
363                    id = wx.NewId() 
364                    struct_factor=item()
365                    struct_name = struct_factor.__class__.__name__
366                    if hasattr(struct_factor, "name"):
367                        struct_name = struct_factor.name
368                       
369                    menuinfo[1].Append(int(id),struct_name,struct_name)
370                    if not  item in self.struct_factor_dict.itervalues():
371                        self.struct_factor_dict[str(id)]= item
372                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
373                except:
374                    msg= "Error Occured: %s"%sys.exc_value
375                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
[bb18ef1]376               
377        id = wx.NewId()         
378        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
379       
380       
381       
382    def _fill_menu(self,menuinfo, list1,list2  ):
383        """
384            Fill the menu with list item
385            @param menuinfo: submenu item for the first column of this modelmenu
386                             with info.Should be a list :
387                             [name(string) , menu(wx.menu), help(string)]
388            @param list1: contains item (form factor )to fill modelmenu second column
389            @param list2: contains item (Structure factor )to fill modelmenu third column
390        """
391        if len(list1)>0:
392            self.model_combobox.set_list(menuinfo[0],list1)
393           
394            for item in list1:   
395                form_factor= item()
396                form_name = form_factor.__class__.__name__
397                if hasattr(form_factor, "name"):
398                    form_name = form_factor.name
399                ### store form factor to return to other users   
400                newmenu= wx.Menu()
401                if len(list2)>0:
402                    for model  in list2:
403                        id = wx.NewId()
404                        struct_factor = model()
405                        name = struct_factor.__class__.__name__
406                        if hasattr(struct_factor, "name"):
407                            name = struct_factor.name
408                        newmenu.Append(id,name, name)
409                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
410                        ## save form_fact and struct_fact
411                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
412                       
413                form_id= wx.NewId()   
414                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
415        id=wx.NewId()
416        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
417       
418       
419       
420       
[d89f09b]421    def _on_model(self, evt):
422        """
423            React to a model menu event
424            @param event: wx menu event
425        """
[bb18ef1]426        if int(evt.GetId()) in self.form_factor_dict.keys():
427            from sans.models.MultiplicationModel import MultiplicationModel
428            model1, model2 = self.form_factor_dict[int(evt.GetId())]
429            model = MultiplicationModel(model1, model2)
430               
431        else:
432            model= self.struct_factor_dict[str(evt.GetId())]()
[d89f09b]433           
[bb18ef1]434        evt = ModelEvent( model= model )
435        wx.PostEvent(self.event_owner, evt)
[d89f09b]436       
437    def get_model_list(self):   
438        """ @ return dictionary of models for fitpanel use """
[376916c]439        self.model_combobox.set_list("multiplication", self.multiplication_factor)
[bb18ef1]440        return self.model_combobox
[d89f09b]441   
[376916c]442 
[bb18ef1]443       
444   
[d89f09b]445   
[bb18ef1]446 
Note: See TracBrowser for help on using the repository browser.