source: sasview/sansview/perspectives/fitting/models.py @ 9d091ed

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 9d091ed was 376916c, checked in by Gervaise Alina <gervyh@…>, 15 years ago

resettting gaussian dispersity —fixed
reducing access to molde multplication —-done as request

  • Property mode set to 100644
File size: 13.0 KB
RevLine 
[33afff7]1#TODO: add comments to document this module
2#TODO: clean-up the exception handling.
3#TODO: clean-up existing comments/documentation.
4#      For example, the _getModelList method advertises
5#      an 'id' parameter that is not part of the method's signature.
6#      It also advertises an ID as return value but it always returns zero.
7#TODO: clean-up the FractalAbsModel and PowerLawAbsModel menu items. Those
8#      model definitions do not belong here. They belong with the rest of the
9#      models.
10
[d89f09b]11import wx
[bb18ef1]12import wx.lib.newevent
[b30f001]13import imp
[442895f]14import os,sys,math
[d89f09b]15import os.path
16
17(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
[00561739]18
[33afff7]19# Time is needed by the log method
20import time
[2dbb681]21
[33afff7]22# Explicitly import from the pluginmodel module so that py2exe
23# places it in the distribution. The Model1DPlugin class is used
24# as the base class of plug-in models.
25from sans.models.pluginmodel import Model1DPlugin
[00561739]26   
[b30f001]27def log(message):
28    out = open("plugins.log", 'a')
29    out.write("%10g%s\n" % (time.clock(), message))
30    out.close()
31
[aa92772]32def findModels():
[33afff7]33    log("looking for models in: %s/plugins" % os.getcwd())
[b30f001]34    if os.path.isdir('plugins'):
35        return _findModels('plugins')
36    return []
[aa92772]37   
[1c66bc5]38def _findModels(dir):
39    # List of plugin objects
40    plugins = []
41    # Go through files in plug-in directory
42    try:
43        list = os.listdir(dir)
44        for item in list:
45            toks = os.path.splitext(os.path.basename(item))
46            if toks[1]=='.py' and not toks[0]=='__init__':
47                name = toks[0]
48           
49                path = [os.path.abspath(dir)]
50                file = None
51                try:
52                    (file, path, info) = imp.find_module(name, path)
53                    module = imp.load_module( name, file, item, info )
54                    if hasattr(module, "Model"):
55                        try:
56                            plugins.append(module.Model)
57                        except:
58                            log("Error accessing Model in %s\n  %s" % (name, sys.exc_value))
59                except:
[b30f001]60                    log("Error accessing Model in %s\n  %s" % (name, sys.exc_value))
[1c66bc5]61                finally:
[a92d51b]62             
[1c66bc5]63                    if not file==None:
64                        file.close()
65    except:
[33afff7]66        # Don't deal with bad plug-in imports. Just skip.
[1c66bc5]67        pass
68    return plugins
[bb18ef1]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       
[d89f09b]92class ModelManager:
[bb18ef1]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= []
[376916c]105    ##list of model allowing multiplication
106    multiplication_factor=[]
[bb18ef1]107    ## list of added models
[b30f001]108    plugins=[]
[bb18ef1]109    ## Event owner (guiframe)
[d89f09b]110    event_owner = None
111   
112    def _getModelList(self):
113        """
114            List of models we want to make available by default
115            for this application
116           
117            @param id: first event ID to register the menu events with
118            @return: the next free event ID following the new menu events
119        """
[bb18ef1]120        ## form factor
[442895f]121        from sans.models.SphereModel import SphereModel
[bb18ef1]122        self.shape_list.append(SphereModel)
[376916c]123        self.multiplication_factor.append(SphereModel)
[442895f]124       
[d89f09b]125        from sans.models.CylinderModel import CylinderModel
[bb18ef1]126        self.shape_list.append(CylinderModel)
[376916c]127        self.multiplication_factor.append(CylinderModel)
128       
[442895f]129        from sans.models.CoreShellModel import CoreShellModel
[bb18ef1]130        self.shape_list.append(CoreShellModel)
[442895f]131       
132        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
[bb18ef1]133        self.shape_list.append(CoreShellCylinderModel)
[442895f]134       
135        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
[bb18ef1]136        self.shape_list.append(EllipticalCylinderModel)
[442895f]137       
138        from sans.models.EllipsoidModel import EllipsoidModel
[bb18ef1]139        self.shape_list.append(EllipsoidModel)
[376916c]140        self.multiplication_factor.append(EllipsoidModel)
[bb18ef1]141         
142       
[442895f]143       
[376916c]144        ## Structure factor
145     
[8346667]146        from sans.models.SquareWellStructure import SquareWellStructure
[bb18ef1]147        self.struct_list.append(SquareWellStructure)
[8346667]148       
149        from sans.models.HardsphereStructure import HardsphereStructure
[bb18ef1]150        self.struct_list.append(HardsphereStructure)
151         
[8346667]152        from sans.models.StickyHSStructure import StickyHSStructure
[bb18ef1]153        self.struct_list.append(StickyHSStructure)
[8346667]154       
155        from sans.models.HayterMSAStructure import HayterMSAStructure
[bb18ef1]156        self.struct_list.append(HayterMSAStructure)
[43eb424]157       
158       
[bb18ef1]159        ##shape-independent models
[442895f]160        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
[bb18ef1]161        self.shape_indep_list.append(BEPolyelectrolyte )
162        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
[442895f]163        from sans.models.DABModel import DABModel
[bb18ef1]164        self.shape_indep_list.append(DABModel )
[442895f]165       
[f39511b]166        from sans.models.GuinierModel import GuinierModel
[bb18ef1]167        self.shape_indep_list.append(GuinierModel )
[f39511b]168       
[442895f]169        from sans.models.DebyeModel import DebyeModel
[bb18ef1]170        self.shape_indep_list.append(DebyeModel )
171       
172        from sans.models.PorodModel import PorodModel
173        self.shape_indep_list.append(PorodModel )
[442895f]174       
[376916c]175        from sans.models.LineModel import LineModel
176        self.shape_indep_list.append(LineModel)
177       
[442895f]178        from sans.models.FractalModel import FractalModel
179        class FractalAbsModel(FractalModel):
180            def _Fractal(self, x):
181                return FractalModel._Fractal(self, math.fabs(x))
[bb18ef1]182        self.shape_indep_list.append(FractalAbsModel)
[442895f]183       
184        from sans.models.LorentzModel import LorentzModel
[bb18ef1]185        self.shape_indep_list.append( LorentzModel) 
[442895f]186           
187        from sans.models.PowerLawModel import PowerLawModel
188        class PowerLawAbsModel(PowerLawModel):
189            def _PowerLaw(self, x):
190                try:
191                    return PowerLawModel._PowerLaw(self, math.fabs(x))
192                except:
193                    print sys.exc_value 
[bb18ef1]194        self.shape_indep_list.append( PowerLawAbsModel )
[442895f]195        from sans.models.TeubnerStreyModel import TeubnerStreyModel
[bb18ef1]196        self.shape_indep_list.append(TeubnerStreyModel )
[2dbb681]197   
[49b7efa]198        #Looking for plugins
199        self.plugins = findModels()
200       
[d89f09b]201        return 0
202
203   
204    def populate_menu(self, modelmenu, event_owner):
205        """
206            Populate a menu with our models
207           
208            @param id: first menu event ID to use when binding the menu events
209            @param modelmenu: wx.Menu object to populate
210            @param event_owner: wx object to bind the menu events to
211            @return: the next free event ID following the new menu events
212        """
[bb18ef1]213        ## Fill model lists
[d89f09b]214        self._getModelList()
[bb18ef1]215        ## store reference to model menu of guiframe
216        self.modelmenu = modelmenu
217        ## guiframe reference
[d89f09b]218        self.event_owner = event_owner
[bb18ef1]219       
220       
221        shape_submenu = wx.Menu()
222        shape_indep_submenu = wx.Menu()
223        structure_factor = wx.Menu()
[b30f001]224        added_models = wx.Menu()
[376916c]225        multip_models = wx.Menu()
[bb18ef1]226        ## create menu with shape
[376916c]227        self._fill_simple_menu( menuinfo = ["Shapes",shape_submenu," simple shape"],
228                         list1 = self.shape_list )
229       
230        self._fill_simple_menu( menuinfo = ["Shape-Independent",shape_indep_submenu,
[bb18ef1]231                                    "List of shape-independent models"],
[376916c]232                         list1 = self.shape_indep_list )
[bb18ef1]233       
234        self._fill_simple_menu( menuinfo= ["Structure Factors",structure_factor,
235                                          "List of Structure factors models" ],
236                                list1= self.struct_list )
237       
[376916c]238        self._fill_simple_menu( menuinfo = ["Customized Models", added_models,
239                                            "List of additional models"],
240                                 list1= self.plugins )
241       
242        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
243                                  "mulplication of 2 models"],
244                                   list1 = self.multiplication_factor ,
245                                   list2 =  self.struct_list)
246       
[c77d859]247       
[d89f09b]248        return 0
249   
[bb18ef1]250    def _fill_simple_menu(self,menuinfo, list1):
251        """
252            Fill the menu with list item
253            @param modelmenu: the menu to fill
254            @param menuinfo: submenu item for the first column of this modelmenu
255                             with info.Should be a list :
256                             [name(string) , menu(wx.menu), help(string)]
257            @param list1: contains item (form factor )to fill modelmenu second column
258        """
259        if len(list1)>0:
260            self.model_combobox.set_list(menuinfo[0],list1)
261             
262            for item in list1:
263                id = wx.NewId() 
264                struct_factor=item()
265                struct_name = struct_factor.__class__.__name__
266                if hasattr(struct_factor, "name"):
267                    struct_name = struct_factor.name
268                   
269                menuinfo[1].Append(int(id),struct_name,struct_name)
270                if not  item in self.struct_factor_dict.itervalues():
271                    self.struct_factor_dict[str(id)]= item
272                wx.EVT_MENU(self.event_owner, int(id), self._on_model)
273               
274        id = wx.NewId()         
275        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
276       
277       
278       
279    def _fill_menu(self,menuinfo, list1,list2  ):
280        """
281            Fill the menu with list item
282            @param menuinfo: submenu item for the first column of this modelmenu
283                             with info.Should be a list :
284                             [name(string) , menu(wx.menu), help(string)]
285            @param list1: contains item (form factor )to fill modelmenu second column
286            @param list2: contains item (Structure factor )to fill modelmenu third column
287        """
288        if len(list1)>0:
289            self.model_combobox.set_list(menuinfo[0],list1)
290           
291            for item in list1:   
292                form_factor= item()
293                form_name = form_factor.__class__.__name__
294                if hasattr(form_factor, "name"):
295                    form_name = form_factor.name
296                ### store form factor to return to other users   
297                newmenu= wx.Menu()
298                if len(list2)>0:
299                    for model  in list2:
300                        id = wx.NewId()
301                        struct_factor = model()
302                        name = struct_factor.__class__.__name__
303                        if hasattr(struct_factor, "name"):
304                            name = struct_factor.name
305                        newmenu.Append(id,name, name)
306                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
307                        ## save form_fact and struct_fact
308                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
309                       
310                form_id= wx.NewId()   
311                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
312        id=wx.NewId()
313        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
314       
315       
316       
317       
[d89f09b]318    def _on_model(self, evt):
319        """
320            React to a model menu event
321            @param event: wx menu event
322        """
[bb18ef1]323        if int(evt.GetId()) in self.form_factor_dict.keys():
324            from sans.models.MultiplicationModel import MultiplicationModel
325            model1, model2 = self.form_factor_dict[int(evt.GetId())]
326            model = MultiplicationModel(model1, model2)
327               
328        else:
329            model= self.struct_factor_dict[str(evt.GetId())]()
[d89f09b]330           
[bb18ef1]331        evt = ModelEvent( model= model )
332        wx.PostEvent(self.event_owner, evt)
[d89f09b]333       
334    def get_model_list(self):   
335        """ @ return dictionary of models for fitpanel use """
[376916c]336        self.model_combobox.set_list("multiplication", self.multiplication_factor)
[bb18ef1]337        return self.model_combobox
[d89f09b]338   
[376916c]339 
[bb18ef1]340       
341   
[d89f09b]342   
[bb18ef1]343 
Note: See TracBrowser for help on using the repository browser.