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

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 1b43306 was 5062bbf, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on documentation

  • Property mode set to 100644
File size: 17.6 KB
RevLine 
[33afff7]1
[d89f09b]2import wx
[bb18ef1]3import wx.lib.newevent
[b30f001]4import imp
[442895f]5import os,sys,math
[d89f09b]6import os.path
[8d78399]7
[d89f09b]8(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
[e7b1ccf]9from sans.guicomm.events import StatusEvent 
[33afff7]10# Time is needed by the log method
11import time
[2dbb681]12
[33afff7]13# Explicitly import from the pluginmodel module so that py2exe
14# places it in the distribution. The Model1DPlugin class is used
15# as the base class of plug-in models.
16from sans.models.pluginmodel import Model1DPlugin
[00561739]17   
[b30f001]18def log(message):
[5062bbf]19    """
20    """
[b30f001]21    out = open("plugins.log", 'a')
22    out.write("%10g%s\n" % (time.clock(), message))
23    out.close()
24
[aa92772]25def findModels():
[5062bbf]26    """
27    """
[33afff7]28    log("looking for models in: %s/plugins" % os.getcwd())
[b30f001]29    if os.path.isdir('plugins'):
30        return _findModels('plugins')
31    return []
[aa92772]32   
[bfe4644]33def _check_plugin(model, name):
34    """
[5062bbf]35    Do some checking before model adding plugins in the list
36   
37    :param model: class model to add into the plugin list
38    :param name:name of the module plugin
39   
40    :return model: model if valid model or None if not valid
41   
[bfe4644]42    """
43    #Check is the plugin is of type Model1DPlugin
44    if not issubclass(model, Model1DPlugin):
45        msg= "Plugin %s must be of type Model1DPlugin \n"%str(name)
46        log(msg)
[8d78399]47        return None
[bfe4644]48    if model.__name__!="Model":
49        msg= "Plugin %s class name must be Model \n"%str(name)
50        log(msg)
[8d78399]51        return None
[bfe4644]52    try:
53        new_instance= model()
54    except:
55        msg="Plugin %s error in __init__ \n\t: %s %s\n"%(str(name),
56                                    str(sys.exc_type),sys.exc_value)
57        log(msg)
[8d78399]58        return None
[bfe4644]59   
60    new_instance= model() 
61    if hasattr(new_instance,"function"):
62        try:
63           value=new_instance.function()
64        except:
65           msg="Plugin %s: error writing function \n\t :%s %s\n "%(str(name),
66                                    str(sys.exc_type),sys.exc_value)
67           log(msg)
[8d78399]68           return None
[bfe4644]69    else:
70       msg="Plugin  %s needs a method called function \n"%str(name)
71       log(msg)
[8d78399]72       return None
[bfe4644]73    return model
74 
75 
[1c66bc5]76def _findModels(dir):
[5062bbf]77    """
78    """
[1c66bc5]79    # List of plugin objects
80    plugins = []
81    # Go through files in plug-in directory
82    try:
83        list = os.listdir(dir)
84        for item in list:
85            toks = os.path.splitext(os.path.basename(item))
86            if toks[1]=='.py' and not toks[0]=='__init__':
87                name = toks[0]
88           
89                path = [os.path.abspath(dir)]
90                file = None
91                try:
92                    (file, path, info) = imp.find_module(name, path)
93                    module = imp.load_module( name, file, item, info )
94                    if hasattr(module, "Model"):
95                        try:
[bfe4644]96                            if _check_plugin(module.Model, name)!=None:
97                                plugins.append(module.Model)
[1c66bc5]98                        except:
[bfe4644]99                            msg="Error accessing Model"
100                            msg+="in %s\n  %s %s\n" % (name,
101                                    str(sys.exc_type), sys.exc_value)
102                            log(msg)
[1c66bc5]103                except:
[bfe4644]104                    msg="Error accessing Model"
105                    msg +=" in %s\n  %s %s \n" %(name,
106                                    str(sys.exc_type), sys.exc_value)
107                    log(msg)
[1c66bc5]108                finally:
[a92d51b]109             
[1c66bc5]110                    if not file==None:
111                        file.close()
112    except:
[33afff7]113        # Don't deal with bad plug-in imports. Just skip.
[1c66bc5]114        pass
115    return plugins
[bb18ef1]116
117class ModelList(object):
118    """
[5062bbf]119    Contains dictionary of model and their type
[bb18ef1]120    """
121    def __init__(self):
[5062bbf]122        """
123        """
124        self.mydict = {}
[bb18ef1]125       
126    def set_list(self, name, mylist):
127        """
[5062bbf]128        :param name: the type of the list
129        :param mylist: the list to add
130       
[bb18ef1]131        """
132        if name not in self.mydict.keys():
133            self.mydict[name] = mylist
134           
135           
136    def get_list(self):
137        """
[5062bbf]138        return all the list stored in a dictionary object
[bb18ef1]139        """
140        return self.mydict
141       
[d89f09b]142class ModelManager:
[5062bbf]143    """
144    """
[bb18ef1]145    ## external dict for models
146    model_combobox = ModelList()
147    ## Dictionary of form models
148    form_factor_dict = {}
149    ## dictionary of other
150    struct_factor_dict = {}
151    ##list of form factors
152    shape_list =[]
153    ## independent shape model list
154    shape_indep_list = []
155    ##list of structure factors
156    struct_list= []
[376916c]157    ##list of model allowing multiplication
158    multiplication_factor=[]
[bb18ef1]159    ## list of added models
[b30f001]160    plugins=[]
[bb18ef1]161    ## Event owner (guiframe)
[d89f09b]162    event_owner = None
163   
164    def _getModelList(self):
165        """
[5062bbf]166        List of models we want to make available by default
167        for this application
168   
169        :return: the next free event ID following the new menu events
[e7b1ccf]170       
[d89f09b]171        """
[bb18ef1]172        ## form factor
[442895f]173        from sans.models.SphereModel import SphereModel
[bb18ef1]174        self.shape_list.append(SphereModel)
[376916c]175        self.multiplication_factor.append(SphereModel)
[442895f]176       
[ce07fa8]177        from sans.models.FuzzySphereModel import FuzzySphereModel
178        self.shape_list.append(FuzzySphereModel)
179        self.multiplication_factor.append(FuzzySphereModel)
180       
[442895f]181        from sans.models.CoreShellModel import CoreShellModel
[bb18ef1]182        self.shape_list.append(CoreShellModel)
[5eb9154]183        self.multiplication_factor.append(CoreShellModel)
[ce07fa8]184
185        from sans.models.CoreFourShellModel import CoreFourShellModel
186        self.shape_list.append(CoreFourShellModel)
187        self.multiplication_factor.append(CoreFourShellModel)
[cee6867]188       
[eddff027]189        from sans.models.VesicleModel import VesicleModel
190        self.shape_list.append(VesicleModel)
[5eb9154]191        self.multiplication_factor.append(VesicleModel)
192       
193        from sans.models.MultiShellModel import MultiShellModel
194        self.shape_list.append(MultiShellModel)
195        self.multiplication_factor.append(MultiShellModel)
[eddff027]196       
[cee6867]197        from sans.models.BinaryHSModel import BinaryHSModel
198        self.shape_list.append(BinaryHSModel)
199       
[eddff027]200        from sans.models.CylinderModel import CylinderModel
201        self.shape_list.append(CylinderModel)
202        self.multiplication_factor.append(CylinderModel)
203       
204        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
205        self.shape_list.append(CoreShellCylinderModel)
[5eb9154]206        self.multiplication_factor.append(CoreShellCylinderModel)
[cee6867]207       
208        from sans.models.HollowCylinderModel import HollowCylinderModel
209        self.shape_list.append(HollowCylinderModel)
[5eb9154]210        self.multiplication_factor.append(HollowCylinderModel)
[eddff027]211             
212        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
213        self.shape_list.append(FlexibleCylinderModel)
[72f719b]214
[ce07fa8]215        from sans.models.FlexCylEllipXModel import FlexCylEllipXModel
216        self.shape_list.append(FlexCylEllipXModel)
[eddff027]217       
218        from sans.models.StackedDisksModel import StackedDisksModel
219        self.shape_list.append(StackedDisksModel)
[5eb9154]220        self.multiplication_factor.append(StackedDisksModel)
[eddff027]221       
222        from sans.models.ParallelepipedModel import ParallelepipedModel
223        self.shape_list.append(ParallelepipedModel)
[72f719b]224        self.multiplication_factor.append(ParallelepipedModel)
[cee6867]225       
[442895f]226        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
[bb18ef1]227        self.shape_list.append(EllipticalCylinderModel)
[72f719b]228        self.multiplication_factor.append(EllipticalCylinderModel)
229               
[442895f]230        from sans.models.EllipsoidModel import EllipsoidModel
[bb18ef1]231        self.shape_list.append(EllipsoidModel)
[376916c]232        self.multiplication_factor.append(EllipsoidModel)
[eddff027]233     
234        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
235        self.shape_list.append(CoreShellEllipsoidModel)
[5eb9154]236        self.multiplication_factor.append(CoreShellEllipsoidModel)
[bb18ef1]237         
[e65050e]238        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
239        self.shape_list.append(TriaxialEllipsoidModel)
[9002927]240        self.multiplication_factor.append(TriaxialEllipsoidModel)
[e65050e]241       
242        from sans.models.LamellarModel import LamellarModel
243        self.shape_list.append(LamellarModel)
244       
245        from sans.models.LamellarFFHGModel import LamellarFFHGModel
246        self.shape_list.append(LamellarFFHGModel)
247       
248        from sans.models.LamellarPSModel import LamellarPSModel
249        self.shape_list.append(LamellarPSModel)
[7a69683]250     
[e65050e]251        from sans.models.LamellarPSHGModel import LamellarPSHGModel
252        self.shape_list.append(LamellarPSHGModel)
[7a69683]253     
[376916c]254        ## Structure factor
[8346667]255        from sans.models.SquareWellStructure import SquareWellStructure
[bb18ef1]256        self.struct_list.append(SquareWellStructure)
[8346667]257       
258        from sans.models.HardsphereStructure import HardsphereStructure
[bb18ef1]259        self.struct_list.append(HardsphereStructure)
260         
[8346667]261        from sans.models.StickyHSStructure import StickyHSStructure
[bb18ef1]262        self.struct_list.append(StickyHSStructure)
[8346667]263       
264        from sans.models.HayterMSAStructure import HayterMSAStructure
[bb18ef1]265        self.struct_list.append(HayterMSAStructure)
[5062bbf]266   
267        ##shape-independent models 
[ce07fa8]268        from sans.models.PowerLawAbsModel import PowerLawAbsModel
269        self.shape_indep_list.append( PowerLawAbsModel )
270       
[442895f]271        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
[bb18ef1]272        self.shape_indep_list.append(BEPolyelectrolyte )
273        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
[ce07fa8]274
[442895f]275        from sans.models.DABModel import DABModel
[bb18ef1]276        self.shape_indep_list.append(DABModel )
[442895f]277       
[ce07fa8]278        from sans.models.DebyeModel import DebyeModel
279        self.shape_indep_list.append(DebyeModel )
280       
[f39511b]281        from sans.models.GuinierModel import GuinierModel
[bb18ef1]282        self.shape_indep_list.append(GuinierModel )
[f39511b]283       
[ce07fa8]284        from sans.models.FractalModel import FractalModel
285        self.shape_indep_list.append(FractalModel )
[bb18ef1]286       
[ce07fa8]287        from sans.models.LorentzModel import LorentzModel
288        self.shape_indep_list.append( LorentzModel) 
[442895f]289       
[cee6867]290        from sans.models.PeakGaussModel import PeakGaussModel
291        self.shape_indep_list.append(PeakGaussModel)
292       
293        from sans.models.PeakLorentzModel import PeakLorentzModel
294        self.shape_indep_list.append(PeakLorentzModel)
295       
[ce07fa8]296        from sans.models.Poly_GaussCoil import Poly_GaussCoil
297        self.shape_indep_list.append(Poly_GaussCoil)
298                 
299        from sans.models.PorodModel import PorodModel
300        self.shape_indep_list.append(PorodModel )
[442895f]301       
[ce07fa8]302        #FractalModel (a c-model)will be used.
303        #from sans.models.FractalAbsModel import FractalAbsModel
304        #self.shape_indep_list.append(FractalAbsModel)
[81bece4]305       
[442895f]306        from sans.models.TeubnerStreyModel import TeubnerStreyModel
[bb18ef1]307        self.shape_indep_list.append(TeubnerStreyModel )
[eddff027]308       
309        from sans.models.LineModel import LineModel
310        self.shape_indep_list.append(LineModel)
[5062bbf]311       
[49b7efa]312        #Looking for plugins
313        self.plugins = findModels()
[d89f09b]314        return 0
315
316   
317    def populate_menu(self, modelmenu, event_owner):
318        """
[5062bbf]319        Populate a menu with our models
320       
321        :param id: first menu event ID to use when binding the menu events
322        :param modelmenu: wx.Menu object to populate
323        :param event_owner: wx object to bind the menu events to
324       
325        :return: the next free event ID following the new menu events
326       
[d89f09b]327        """
[bb18ef1]328        ## Fill model lists
[d89f09b]329        self._getModelList()
[bb18ef1]330        ## store reference to model menu of guiframe
331        self.modelmenu = modelmenu
332        ## guiframe reference
[d89f09b]333        self.event_owner = event_owner
[bb18ef1]334       
335        shape_submenu = wx.Menu()
336        shape_indep_submenu = wx.Menu()
337        structure_factor = wx.Menu()
[b30f001]338        added_models = wx.Menu()
[376916c]339        multip_models = wx.Menu()
[bb18ef1]340        ## create menu with shape
[5062bbf]341        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
342                         list1=self.shape_list)
[376916c]343       
[5062bbf]344        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
[bb18ef1]345                                    "List of shape-independent models"],
[5062bbf]346                         list1=self.shape_indep_list )
[bb18ef1]347       
[5062bbf]348        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
[bb18ef1]349                                          "List of Structure factors models" ],
[5062bbf]350                                list1=self.struct_list)
[bb18ef1]351       
[5062bbf]352        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
[376916c]353                                            "List of additional models"],
[5062bbf]354                                 list1=self.plugins)
[376916c]355       
356        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
357                                  "mulplication of 2 models"],
[5062bbf]358                                   list1=self.multiplication_factor ,
359                                   list2= self.struct_list)
[d89f09b]360        return 0
361   
[5062bbf]362    def _fill_plugin_menu(self, menuinfo, list1):
[bfe4644]363        """
[5062bbf]364        fill the plugin menu with costumized models
[bfe4644]365        """
366        if len(list1)==0:
367            id = wx.NewId() 
368            msg= "No model available check plugins.log for errors to fix problem"
369            menuinfo[1].Append(int(id),"Empty",msg)
370        self._fill_simple_menu( menuinfo,list1)
371       
[5062bbf]372    def _fill_simple_menu(self, menuinfo, list1):
[bb18ef1]373        """
[5062bbf]374        Fill the menu with list item
375       
376        :param modelmenu: the menu to fill
377        :param menuinfo: submenu item for the first column of this modelmenu
378                         with info.Should be a list :
379                         [name(string) , menu(wx.menu), help(string)]
380        :param list1: contains item (form factor )to fill modelmenu second column
381       
[bb18ef1]382        """
383        if len(list1)>0:
384            self.model_combobox.set_list(menuinfo[0],list1)
[e7b1ccf]385           
[bb18ef1]386            for item in list1:
[e7b1ccf]387                try:
388                    id = wx.NewId() 
389                    struct_factor=item()
390                    struct_name = struct_factor.__class__.__name__
391                    if hasattr(struct_factor, "name"):
392                        struct_name = struct_factor.name
393                       
394                    menuinfo[1].Append(int(id),struct_name,struct_name)
395                    if not  item in self.struct_factor_dict.itervalues():
396                        self.struct_factor_dict[str(id)]= item
397                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
398                except:
399                    msg= "Error Occured: %s"%sys.exc_value
400                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
[bb18ef1]401               
402        id = wx.NewId()         
403        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
404       
[5062bbf]405    def _fill_menu(self, menuinfo, list1, list2):
[bb18ef1]406        """
[5062bbf]407        Fill the menu with list item
408       
409        :param menuinfo: submenu item for the first column of this modelmenu
410                         with info.Should be a list :
411                         [name(string) , menu(wx.menu), help(string)]
412        :param list1: contains item (form factor )to fill modelmenu second column
413        :param list2: contains item (Structure factor )to fill modelmenu
414                third column
415               
[bb18ef1]416        """
417        if len(list1)>0:
418            self.model_combobox.set_list(menuinfo[0],list1)
419           
420            for item in list1:   
421                form_factor= item()
422                form_name = form_factor.__class__.__name__
423                if hasattr(form_factor, "name"):
424                    form_name = form_factor.name
425                ### store form factor to return to other users   
426                newmenu= wx.Menu()
427                if len(list2)>0:
428                    for model  in list2:
429                        id = wx.NewId()
430                        struct_factor = model()
431                        name = struct_factor.__class__.__name__
432                        if hasattr(struct_factor, "name"):
433                            name = struct_factor.name
434                        newmenu.Append(id,name, name)
435                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
436                        ## save form_fact and struct_fact
437                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
438                       
439                form_id= wx.NewId()   
440                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
441        id=wx.NewId()
442        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
443       
[d89f09b]444    def _on_model(self, evt):
445        """
[5062bbf]446        React to a model menu event
447       
448        :param event: wx menu event
449       
[d89f09b]450        """
[bb18ef1]451        if int(evt.GetId()) in self.form_factor_dict.keys():
452            from sans.models.MultiplicationModel import MultiplicationModel
453            model1, model2 = self.form_factor_dict[int(evt.GetId())]
[5062bbf]454            model = MultiplicationModel(model1, model2)   
[bb18ef1]455        else:
456            model= self.struct_factor_dict[str(evt.GetId())]()
457        evt = ModelEvent( model= model )
458        wx.PostEvent(self.event_owner, evt)
[d89f09b]459       
460    def get_model_list(self):   
[5062bbf]461        """
462        return dictionary of models for fitpanel use
463       
464        """
[376916c]465        self.model_combobox.set_list("multiplication", self.multiplication_factor)
[bb18ef1]466        return self.model_combobox
[d89f09b]467   
[376916c]468 
[bb18ef1]469       
470   
[d89f09b]471   
[bb18ef1]472 
Note: See TracBrowser for help on using the repository browser.