source: sasview/sansview/perspectives/fitting/models.py @ 1bbf2ac

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 1bbf2ac was 33afff7, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

Fixed plug-in model import for windows executable (py2exe) and added clean-up to-do list

  • Property mode set to 100644
File size: 8.7 KB
Line 
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
11import wx
12import imp
13import os,sys,math
14import os.path
15
16(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
17
18# Time is needed by the log method
19import time
20
21# Explicitly import from the pluginmodel module so that py2exe
22# places it in the distribution. The Model1DPlugin class is used
23# as the base class of plug-in models.
24from sans.models.pluginmodel import Model1DPlugin
25   
26def log(message):
27    out = open("plugins.log", 'a')
28    out.write("%10g%s\n" % (time.clock(), message))
29    out.close()
30
31def findModels():
32    log("looking for models in: %s/plugins" % os.getcwd())
33    if os.path.isdir('plugins'):
34        return _findModels('plugins')
35    return []
36   
37def _findModels(dir):
38    # List of plugin objects
39    plugins = []
40    # Go through files in plug-in directory
41    try:
42        list = os.listdir(dir)
43        for item in list:
44            toks = os.path.splitext(os.path.basename(item))
45            if toks[1]=='.py' and not toks[0]=='__init__':
46                name = toks[0]
47           
48                path = [os.path.abspath(dir)]
49                file = None
50                try:
51                    (file, path, info) = imp.find_module(name, path)
52                    module = imp.load_module( name, file, item, info )
53                    if hasattr(module, "Model"):
54                        try:
55                            plugins.append(module.Model)
56                        except:
57                            log("Error accessing Model in %s\n  %s" % (name, sys.exc_value))
58                except:
59                    log("Error accessing Model in %s\n  %s" % (name, sys.exc_value))
60                finally:
61             
62                    if not file==None:
63                        file.close()
64    except:
65        # Don't deal with bad plug-in imports. Just skip.
66        pass
67    return plugins
68class ModelManager:
69   
70    ## Dictionary of models
71    model_list = {}
72    indep_model_list = {}
73    model_list_box = {}
74    custom_models={}
75    plugins=[]
76    indep_model=[]
77    ## Event owner
78    event_owner = None
79   
80    def _getModelList(self):
81        """
82            List of models we want to make available by default
83            for this application
84           
85            @param id: first event ID to register the menu events with
86            @return: the next free event ID following the new menu events
87        """
88        self.model_list = {}
89        self.model_list_box = {}
90       
91       
92        from sans.models.SphereModel import SphereModel
93        self.model_list[str(wx.NewId())] =  SphereModel
94       
95        from sans.models.CylinderModel import CylinderModel
96        self.model_list[str(wx.NewId())] =CylinderModel
97     
98        from sans.models.CoreShellModel import CoreShellModel
99        self.model_list[str(wx.NewId())] = CoreShellModel
100       
101        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
102        self.model_list[str(wx.NewId())] =CoreShellCylinderModel
103       
104        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
105        self.model_list[str(wx.NewId())] =EllipticalCylinderModel
106       
107        from sans.models.EllipsoidModel import EllipsoidModel
108        self.model_list[str(wx.NewId())] = EllipsoidModel
109       
110        from sans.models.LineModel import LineModel
111        self.model_list[str(wx.NewId())]  = LineModel
112       
113       
114        model_info="shape-independent models"
115       
116        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
117        self.indep_model.append(BEPolyelectrolyte )
118       
119        from sans.models.DABModel import DABModel
120        self.indep_model.append(DABModel )
121       
122        from sans.models.GuinierModel import GuinierModel
123        self.indep_model.append(GuinierModel )
124       
125        from sans.models.DebyeModel import DebyeModel
126        self.indep_model.append(DebyeModel )
127       
128        from sans.models.FractalModel import FractalModel
129        class FractalAbsModel(FractalModel):
130            def _Fractal(self, x):
131                return FractalModel._Fractal(self, math.fabs(x))
132        self.indep_model.append(FractalAbsModel)
133       
134        from sans.models.LorentzModel import LorentzModel
135        self.indep_model.append( LorentzModel) 
136           
137        from sans.models.PowerLawModel import PowerLawModel
138        class PowerLawAbsModel(PowerLawModel):
139            def _PowerLaw(self, x):
140                try:
141                    return PowerLawModel._PowerLaw(self, math.fabs(x))
142                except:
143                    print sys.exc_value 
144        self.indep_model.append( PowerLawAbsModel )
145        from sans.models.TeubnerStreyModel import TeubnerStreyModel
146        self.indep_model.append(TeubnerStreyModel )
147   
148        #Looking for plugins
149        self.plugins = findModels()
150       
151        return 0
152
153   
154    def populate_menu(self, modelmenu, event_owner):
155        """
156            Populate a menu with our models
157           
158            @param id: first menu event ID to use when binding the menu events
159            @param modelmenu: wx.Menu object to populate
160            @param event_owner: wx object to bind the menu events to
161            @return: the next free event ID following the new menu events
162        """
163        self._getModelList()
164        self.event_owner = event_owner
165        shape_submenu= wx.Menu() 
166        indep_submenu = wx.Menu()
167        added_models = wx.Menu()
168        for id_str,value in self.model_list.iteritems():
169            item = self.model_list[id_str]()
170            name = item.__class__.__name__
171            if hasattr(item, "name"):
172                name = item.name
173            self.model_list_box[name] =value
174            shape_submenu.Append(int(id_str), name, name)
175            wx.EVT_MENU(event_owner, int(id_str), self._on_model)
176        modelmenu.AppendMenu(wx.NewId(), "Shapes...", shape_submenu, "List of shape-based models")
177        id = wx.NewId()
178        if len(self.indep_model_list) == 0:
179            for items in self.indep_model:
180                #if item not in self.indep_model_list.values():
181                    #self.indep_model_list[str(id)] = item
182                self.model_list[str(id)]=items
183                item=items()
184                name = item.__class__.__name__
185                if hasattr(item, "name"):
186                    name = item.name
187                indep_submenu.Append(id,name, name)
188                self.model_list_box[name] =items
189                wx.EVT_MENU(event_owner, int(id), self._on_model)
190                id = wx.NewId()         
191        modelmenu.AppendMenu(wx.NewId(), "Shape-independent...", indep_submenu, "List of shape-independent models")
192        id = wx.NewId()
193        if len(self.custom_models) == 0:
194            for items in self.plugins:
195                #if item not in self.custom_models.values():
196                    #self.custom_models[str(id)] = item
197                self.model_list[str(id)]=items
198                name = items.__name__
199                if hasattr(items, "name"):
200                    name = items.name
201                added_models.Append(id, name, name)
202                self.model_list_box[name] =items
203                wx.EVT_MENU(event_owner, int(id), self._on_model)
204                id = wx.NewId()
205        modelmenu.AppendMenu(wx.NewId(),"Added models...", added_models, "List of additional models")
206        return 0
207   
208    def _on_model(self, evt):
209        """
210            React to a model menu event
211            @param event: wx menu event
212        """
213        if str(evt.GetId()) in self.model_list.keys():
214            # Notify the application manager that a new model has been set
215            #self.app_manager.set_model(self.model_list[str(evt.GetId())]())
216           
217            #TODO: post a model event to update all panels that need
218            #evt = ModelEvent(model=self.model_list[str(evt.GetId())]())
219           
220            model = self.model_list[str(evt.GetId())]
221            evt = ModelEvent(model= model )
222            wx.PostEvent(self.event_owner, evt)
223       
224    def get_model_list(self):   
225        """ @ return dictionary of models for fitpanel use """
226        return self.model_list_box
227   
228   
229   
230 
Note: See TracBrowser for help on using the repository browser.