source: sasview/sansview/perspectives/fitting/models.py @ f71c2de

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

refactor models.py

  • Property mode set to 100644
File size: 17.1 KB
Line 
1#TODO: add comments to document this module
2#TODO: clean-up the exception handling.
3
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
8import wx
9import wx.lib.newevent
10import imp
11import os,sys,math
12import os.path
13
14(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
15from sans.guicomm.events import StatusEvent 
16# Time is needed by the log method
17import time
18
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
23   
24def log(message):
25    out = open("plugins.log", 'a')
26    out.write("%10g%s\n" % (time.clock(), message))
27    out.close()
28
29def findModels():
30    log("looking for models in: %s/plugins" % os.getcwd())
31    if os.path.isdir('plugins'):
32        return _findModels('plugins')
33    return []
34   
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
40        @return model: model if valid model or None if not valid
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)
46        return None
47    if model.__name__!="Model":
48        msg= "Plugin %s class name must be Model \n"%str(name)
49        log(msg)
50        return None
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)
57        return None
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)
67           return None
68    else:
69       msg="Plugin  %s needs a method called function \n"%str(name)
70       log(msg)
71       return None
72    return model
73 
74 
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:
93                            if _check_plugin(module.Model, name)!=None:
94                                plugins.append(module.Model)
95                        except:
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)
100                except:
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)
105                finally:
106             
107                    if not file==None:
108                        file.close()
109    except:
110        # Don't deal with bad plug-in imports. Just skip.
111        pass
112    return plugins
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       
136class ModelManager:
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= []
149    ##list of model allowing multiplication
150    multiplication_factor=[]
151    ## list of added models
152    plugins=[]
153    ## Event owner (guiframe)
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
160       
161            @return: the next free event ID following the new menu events
162        """
163        ## form factor
164        from sans.models.SphereModel import SphereModel
165        self.shape_list.append(SphereModel)
166        self.multiplication_factor.append(SphereModel)
167       
168        from sans.models.CoreShellModel import CoreShellModel
169        self.shape_list.append(CoreShellModel)
170        self.multiplication_factor.append(CoreShellModel)
171       
172        from sans.models.VesicleModel import VesicleModel
173        self.shape_list.append(VesicleModel)
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)
179       
180        from sans.models.BinaryHSModel import BinaryHSModel
181        self.shape_list.append(BinaryHSModel)
182       
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)
189        self.multiplication_factor.append(CoreShellCylinderModel)
190       
191        from sans.models.HollowCylinderModel import HollowCylinderModel
192        self.shape_list.append(HollowCylinderModel)
193        self.multiplication_factor.append(HollowCylinderModel)
194             
195        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
196        self.shape_list.append(FlexibleCylinderModel)
197
198       
199        from sans.models.StackedDisksModel import StackedDisksModel
200        self.shape_list.append(StackedDisksModel)
201        self.multiplication_factor.append(StackedDisksModel)
202       
203        from sans.models.ParallelepipedModel import ParallelepipedModel
204        self.shape_list.append(ParallelepipedModel)
205        self.multiplication_factor.append(ParallelepipedModel)
206       
207        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
208        self.shape_list.append(EllipticalCylinderModel)
209        self.multiplication_factor.append(EllipticalCylinderModel)
210               
211        from sans.models.EllipsoidModel import EllipsoidModel
212        self.shape_list.append(EllipsoidModel)
213        self.multiplication_factor.append(EllipsoidModel)
214     
215        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
216        self.shape_list.append(CoreShellEllipsoidModel)
217        self.multiplication_factor.append(CoreShellEllipsoidModel)
218         
219        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
220        self.shape_list.append(TriaxialEllipsoidModel)
221        self.multiplication_factor.append(TriaxialEllipsoidModel)
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)
231     
232        from sans.models.LamellarPSHGModel import LamellarPSHGModel
233        self.shape_list.append(LamellarPSHGModel)
234     
235        ## Structure factor
236        from sans.models.SquareWellStructure import SquareWellStructure
237        self.struct_list.append(SquareWellStructure)
238       
239        from sans.models.HardsphereStructure import HardsphereStructure
240        self.struct_list.append(HardsphereStructure)
241         
242        from sans.models.StickyHSStructure import StickyHSStructure
243        self.struct_list.append(StickyHSStructure)
244       
245        from sans.models.HayterMSAStructure import HayterMSAStructure
246        self.struct_list.append(HayterMSAStructure)
247       
248       
249        ##shape-independent models
250        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
251        self.shape_indep_list.append(BEPolyelectrolyte )
252        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
253        from sans.models.DABModel import DABModel
254        self.shape_indep_list.append(DABModel )
255       
256        from sans.models.GuinierModel import GuinierModel
257        self.shape_indep_list.append(GuinierModel )
258       
259        from sans.models.DebyeModel import DebyeModel
260        self.shape_indep_list.append(DebyeModel )
261       
262        from sans.models.PorodModel import PorodModel
263        self.shape_indep_list.append(PorodModel )
264       
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       
271        from sans.models.FractalAbsModel import FractalAbsModel
272        self.shape_indep_list.append(FractalAbsModel)
273       
274        from sans.models.LorentzModel import LorentzModel
275        self.shape_indep_list.append( LorentzModel) 
276           
277        from sans.models.PowerLawAbsModel import PowerLawAbsModel
278        self.shape_indep_list.append( PowerLawAbsModel )
279       
280        from sans.models.TeubnerStreyModel import TeubnerStreyModel
281        self.shape_indep_list.append(TeubnerStreyModel )
282       
283        from sans.models.LineModel import LineModel
284        self.shape_indep_list.append(LineModel)
285   
286        #Looking for plugins
287        self.plugins = findModels()
288       
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        """
301        ## Fill model lists
302        self._getModelList()
303        ## store reference to model menu of guiframe
304        self.modelmenu = modelmenu
305        ## guiframe reference
306        self.event_owner = event_owner
307       
308       
309        shape_submenu = wx.Menu()
310        shape_indep_submenu = wx.Menu()
311        structure_factor = wx.Menu()
312        added_models = wx.Menu()
313        multip_models = wx.Menu()
314        ## create menu with shape
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,
319                                    "List of shape-independent models"],
320                         list1 = self.shape_indep_list )
321       
322        self._fill_simple_menu( menuinfo= ["Structure Factors",structure_factor,
323                                          "List of Structure factors models" ],
324                                list1= self.struct_list )
325       
326        self._fill_plugin_menu( menuinfo = ["Customized Models", added_models,
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       
335       
336        return 0
337   
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       
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)
360           
361            for item in list1:
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))
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       
421    def _on_model(self, evt):
422        """
423            React to a model menu event
424            @param event: wx menu event
425        """
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())]()
433           
434        evt = ModelEvent( model= model )
435        wx.PostEvent(self.event_owner, evt)
436       
437    def get_model_list(self):   
438        """ @ return dictionary of models for fitpanel use """
439        self.model_combobox.set_list("multiplication", self.multiplication_factor)
440        return self.model_combobox
441   
442 
443       
444   
445   
446 
Note: See TracBrowser for help on using the repository browser.