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

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 a7abdb1 was 43eb424, checked in by Gervaise Alina <gervyh@…>, 16 years ago

reverse version

  • Property mode set to 100644
File size: 9.3 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.SquareWellStructure import SquareWellStructure
111        self.model_list[str(wx.NewId())] =  SquareWellStructure
112       
113        from sans.models.HardsphereStructure import HardsphereStructure
114        self.model_list[str(wx.NewId())] =  HardsphereStructure
115       
116        from sans.models.StickyHSStructure import StickyHSStructure
117        self.model_list[str(wx.NewId())] =  StickyHSStructure
118       
119        from sans.models.HayterMSAStructure import HayterMSAStructure
120        self.model_list[str(wx.NewId())] =  HayterMSAStructure
121       
122        from sans.models.LineModel import LineModel
123        self.model_list[str(wx.NewId())]  = LineModel
124       
125       
126        model_info="shape-independent models"
127       
128        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
129        self.indep_model.append(BEPolyelectrolyte )
130       
131        from sans.models.DABModel import DABModel
132        self.indep_model.append(DABModel )
133       
134        from sans.models.GuinierModel import GuinierModel
135        self.indep_model.append(GuinierModel )
136       
137        from sans.models.DebyeModel import DebyeModel
138        self.indep_model.append(DebyeModel )
139       
140        from sans.models.FractalModel import FractalModel
141        class FractalAbsModel(FractalModel):
142            def _Fractal(self, x):
143                return FractalModel._Fractal(self, math.fabs(x))
144        self.indep_model.append(FractalAbsModel)
145       
146        from sans.models.LorentzModel import LorentzModel
147        self.indep_model.append( LorentzModel) 
148           
149        from sans.models.PowerLawModel import PowerLawModel
150        class PowerLawAbsModel(PowerLawModel):
151            def _PowerLaw(self, x):
152                try:
153                    return PowerLawModel._PowerLaw(self, math.fabs(x))
154                except:
155                    print sys.exc_value 
156        self.indep_model.append( PowerLawAbsModel )
157        from sans.models.TeubnerStreyModel import TeubnerStreyModel
158        self.indep_model.append(TeubnerStreyModel )
159   
160        #Looking for plugins
161        self.plugins = findModels()
162       
163        return 0
164
165   
166    def populate_menu(self, modelmenu, event_owner):
167        """
168            Populate a menu with our models
169           
170            @param id: first menu event ID to use when binding the menu events
171            @param modelmenu: wx.Menu object to populate
172            @param event_owner: wx object to bind the menu events to
173            @return: the next free event ID following the new menu events
174        """
175        self._getModelList()
176        self.event_owner = event_owner
177        shape_submenu= wx.Menu() 
178        indep_submenu = wx.Menu()
179        added_models = wx.Menu()
180        for id_str,value in self.model_list.iteritems():
181            item = self.model_list[id_str]()
182            name = item.__class__.__name__
183            if hasattr(item, "name"):
184                name = item.name
185            self.model_list_box[name] =value
186            shape_submenu.Append(int(id_str), name, name)
187            wx.EVT_MENU(event_owner, int(id_str), self._on_model)
188        modelmenu.AppendMenu(wx.NewId(), "Shapes...", shape_submenu, "List of shape-based models")
189        id = wx.NewId()
190        if len(self.indep_model_list) == 0:
191            for items in self.indep_model:
192                #if item not in self.indep_model_list.values():
193                    #self.indep_model_list[str(id)] = item
194                self.model_list[str(id)]=items
195                item=items()
196                name = item.__class__.__name__
197                if hasattr(item, "name"):
198                    name = item.name
199                indep_submenu.Append(id,name, name)
200                self.model_list_box[name] =items
201                wx.EVT_MENU(event_owner, int(id), self._on_model)
202                id = wx.NewId()         
203        modelmenu.AppendMenu(wx.NewId(), "Shape-independent...", indep_submenu, "List of shape-independent models")
204        id = wx.NewId()
205        if len(self.custom_models) == 0:
206            for items in self.plugins:
207                #if item not in self.custom_models.values():
208                    #self.custom_models[str(id)] = item
209                self.model_list[str(id)]=items
210                name = items.__name__
211                if hasattr(items, "name"):
212                    name = items.name
213                added_models.Append(id, name, name)
214                self.model_list_box[name] =items
215                wx.EVT_MENU(event_owner, int(id), self._on_model)
216                id = wx.NewId()
217        modelmenu.AppendMenu(wx.NewId(),"Added models...", added_models, "List of additional models")
218        return 0
219   
220    def _on_model(self, evt):
221        """
222            React to a model menu event
223            @param event: wx menu event
224        """
225        if str(evt.GetId()) in self.model_list.keys():
226            # Notify the application manager that a new model has been set
227            #self.app_manager.set_model(self.model_list[str(evt.GetId())]())
228           
229            #TODO: post a model event to update all panels that need
230            #evt = ModelEvent(model=self.model_list[str(evt.GetId())]())
231           
232            model = self.model_list[str(evt.GetId())]
233            evt = ModelEvent(model= model )
234            wx.PostEvent(self.event_owner, evt)
235       
236    def get_model_list(self):   
237        """ @ return dictionary of models for fitpanel use """
238        return self.model_list_box
239   
240   
241   
242 
Note: See TracBrowser for help on using the repository browser.