source: sasview/sansview/perspectives/fitting/models.py @ 8d78399

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 8d78399 was 8d78399, checked in by Mathieu Doucet <doucetm@…>, 15 years ago

sansview: minor cosmetics

  • Property mode set to 100644
File size: 17.5 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.FractalModel import FractalModel
272        class FractalAbsModel(FractalModel):
273            def _Fractal(self, x):
274                return FractalModel._Fractal(self, math.fabs(x))
275        self.shape_indep_list.append(FractalAbsModel)
276       
277        from sans.models.LorentzModel import LorentzModel
278        self.shape_indep_list.append( LorentzModel) 
279           
280        from sans.models.PowerLawModel import PowerLawModel
281        class PowerLawAbsModel(PowerLawModel):
282            def _PowerLaw(self, x):
283                try:
284                    return PowerLawModel._PowerLaw(self, math.fabs(x))
285                except:
286                    print sys.exc_value 
287        self.shape_indep_list.append( PowerLawAbsModel )
288        from sans.models.TeubnerStreyModel import TeubnerStreyModel
289        self.shape_indep_list.append(TeubnerStreyModel )
290       
291        from sans.models.LineModel import LineModel
292        self.shape_indep_list.append(LineModel)
293   
294        #Looking for plugins
295        self.plugins = findModels()
296       
297        return 0
298
299   
300    def populate_menu(self, modelmenu, event_owner):
301        """
302            Populate a menu with our models
303           
304            @param id: first menu event ID to use when binding the menu events
305            @param modelmenu: wx.Menu object to populate
306            @param event_owner: wx object to bind the menu events to
307            @return: the next free event ID following the new menu events
308        """
309        ## Fill model lists
310        self._getModelList()
311        ## store reference to model menu of guiframe
312        self.modelmenu = modelmenu
313        ## guiframe reference
314        self.event_owner = event_owner
315       
316       
317        shape_submenu = wx.Menu()
318        shape_indep_submenu = wx.Menu()
319        structure_factor = wx.Menu()
320        added_models = wx.Menu()
321        multip_models = wx.Menu()
322        ## create menu with shape
323        self._fill_simple_menu( menuinfo = ["Shapes",shape_submenu," simple shape"],
324                         list1 = self.shape_list )
325       
326        self._fill_simple_menu( menuinfo = ["Shape-Independent",shape_indep_submenu,
327                                    "List of shape-independent models"],
328                         list1 = self.shape_indep_list )
329       
330        self._fill_simple_menu( menuinfo= ["Structure Factors",structure_factor,
331                                          "List of Structure factors models" ],
332                                list1= self.struct_list )
333       
334        self._fill_plugin_menu( menuinfo = ["Customized Models", added_models,
335                                            "List of additional models"],
336                                 list1= self.plugins )
337       
338        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
339                                  "mulplication of 2 models"],
340                                   list1 = self.multiplication_factor ,
341                                   list2 =  self.struct_list)
342       
343       
344        return 0
345   
346    def _fill_plugin_menu(self,menuinfo, list1):
347        """
348            fill the plugin menu with costumized models
349        """
350        if len(list1)==0:
351            id = wx.NewId() 
352            msg= "No model available check plugins.log for errors to fix problem"
353            menuinfo[1].Append(int(id),"Empty",msg)
354        self._fill_simple_menu( menuinfo,list1)
355       
356       
357    def _fill_simple_menu(self,menuinfo, list1):
358        """
359            Fill the menu with list item
360            @param modelmenu: the menu to fill
361            @param menuinfo: submenu item for the first column of this modelmenu
362                             with info.Should be a list :
363                             [name(string) , menu(wx.menu), help(string)]
364            @param list1: contains item (form factor )to fill modelmenu second column
365        """
366        if len(list1)>0:
367            self.model_combobox.set_list(menuinfo[0],list1)
368           
369            for item in list1:
370                try:
371                    id = wx.NewId() 
372                    struct_factor=item()
373                    struct_name = struct_factor.__class__.__name__
374                    if hasattr(struct_factor, "name"):
375                        struct_name = struct_factor.name
376                       
377                    menuinfo[1].Append(int(id),struct_name,struct_name)
378                    if not  item in self.struct_factor_dict.itervalues():
379                        self.struct_factor_dict[str(id)]= item
380                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
381                except:
382                    msg= "Error Occured: %s"%sys.exc_value
383                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
384               
385        id = wx.NewId()         
386        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
387       
388       
389       
390    def _fill_menu(self,menuinfo, list1,list2  ):
391        """
392            Fill the menu with list item
393            @param menuinfo: submenu item for the first column of this modelmenu
394                             with info.Should be a list :
395                             [name(string) , menu(wx.menu), help(string)]
396            @param list1: contains item (form factor )to fill modelmenu second column
397            @param list2: contains item (Structure factor )to fill modelmenu third column
398        """
399        if len(list1)>0:
400            self.model_combobox.set_list(menuinfo[0],list1)
401           
402            for item in list1:   
403                form_factor= item()
404                form_name = form_factor.__class__.__name__
405                if hasattr(form_factor, "name"):
406                    form_name = form_factor.name
407                ### store form factor to return to other users   
408                newmenu= wx.Menu()
409                if len(list2)>0:
410                    for model  in list2:
411                        id = wx.NewId()
412                        struct_factor = model()
413                        name = struct_factor.__class__.__name__
414                        if hasattr(struct_factor, "name"):
415                            name = struct_factor.name
416                        newmenu.Append(id,name, name)
417                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
418                        ## save form_fact and struct_fact
419                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
420                       
421                form_id= wx.NewId()   
422                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
423        id=wx.NewId()
424        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
425       
426       
427       
428       
429    def _on_model(self, evt):
430        """
431            React to a model menu event
432            @param event: wx menu event
433        """
434        if int(evt.GetId()) in self.form_factor_dict.keys():
435            from sans.models.MultiplicationModel import MultiplicationModel
436            model1, model2 = self.form_factor_dict[int(evt.GetId())]
437            model = MultiplicationModel(model1, model2)
438               
439        else:
440            model= self.struct_factor_dict[str(evt.GetId())]()
441           
442        evt = ModelEvent( model= model )
443        wx.PostEvent(self.event_owner, evt)
444       
445    def get_model_list(self):   
446        """ @ return dictionary of models for fitpanel use """
447        self.model_combobox.set_list("multiplication", self.multiplication_factor)
448        return self.model_combobox
449   
450 
451       
452   
453   
454 
Note: See TracBrowser for help on using the repository browser.