source: sasview/sansview/perspectives/fitting/models.py @ 852354c8

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 852354c8 was 9a22655, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on plugin update

  • Property mode set to 100644
File size: 22.7 KB
Line 
1
2import wx
3import wx.lib.newevent
4import imp
5import os,sys,math
6import os.path
7
8(ModelEvent, EVT_MODEL) = wx.lib.newevent.NewEvent()
9from sans.guiframe.events import StatusEvent 
10# Time is needed by the log method
11import time
12
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
17   
18def log(message):
19    """
20    """
21    out = open("plugins.log", 'a')
22    out.write("%10g%s\n" % (time.clock(), message))
23    out.close()
24
25def findModels():
26    """
27    """
28    log("looking for models in: %s/plugins" % os.getcwd())
29    if os.path.isdir('plugins'):
30        return _findModels('plugins')
31    return []
32   
33def _check_plugin(model, name):
34    """
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   
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)
47        return None
48    if model.__name__!="Model":
49        msg= "Plugin %s class name must be Model \n"%str(name)
50        log(msg)
51        return None
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)
58        return None
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)
68           return None
69    else:
70       msg="Plugin  %s needs a method called function \n"%str(name)
71       log(msg)
72       return None
73    return model
74 
75 
76def _findModels(dir):
77    """
78    """
79    # List of plugin objects
80    plugins = {}
81    # Go through files in plug-in directory
82    try:
83        list = os.listdir(dir)
84        #always recompile the folder plugin
85        import compileall
86        compileall.compile_dir(dir, force=1)
87        for item in list:
88            toks = os.path.splitext(os.path.basename(item))
89            if toks[1]=='.py' and not toks[0]=='__init__':
90                name = toks[0]
91           
92                path = [os.path.abspath(dir)]
93                file = None
94                try:
95                    (file, path, info) = imp.find_module(name, path)
96                    module = imp.load_module( name, file, item, info )
97                    if hasattr(module, "Model"):
98                        try:
99                            if _check_plugin(module.Model, name)!=None:
100                                plugins[name] = module.Model
101                        except:
102                            msg="Error accessing Model"
103                            msg+="in %s\n  %s %s\n" % (name,
104                                    str(sys.exc_type), sys.exc_value)
105                            log(msg)
106                except:
107                    msg="Error accessing Model"
108                    msg +=" in %s\n  %s %s \n" %(name,
109                                    str(sys.exc_type), sys.exc_value)
110                    log(msg)
111                finally:
112             
113                    if not file==None:
114                        file.close()
115    except:
116        # Don't deal with bad plug-in imports. Just skip.
117        pass
118    return plugins
119
120class ModelList(object):
121    """
122    Contains dictionary of model and their type
123    """
124    def __init__(self):
125        """
126        """
127        self.mydict = {}
128       
129    def set_list(self, name, mylist):
130        """
131        :param name: the type of the list
132        :param mylist: the list to add
133       
134        """
135        if name not in self.mydict.keys():
136            self.mydict[name] = mylist
137           
138           
139    def get_list(self):
140        """
141        return all the list stored in a dictionary object
142        """
143        return self.mydict
144       
145class ModelManager:
146    """
147    """
148    ## external dict for models
149    model_combobox = ModelList()
150    ## Dictionary of form models
151    form_factor_dict = {}
152    ## dictionary of other
153    struct_factor_dict = {}
154    ##list of form factors
155    shape_list = []
156    ## independent shape model list
157    shape_indep_list = []
158    ##list of structure factors
159    struct_list = []
160    ##list of model allowing multiplication
161    multiplication_factor = []
162    ##list of multifunctional shapes
163    multi_func_list = []
164    ## list of added models
165    plugins = []
166    ## Event owner (guiframe)
167    event_owner = None
168    def __init__(self):
169        """
170        """
171        self.stored_plugins = {}
172        self._getModelList()
173       
174    def _getModelList(self):
175        """
176        List of models we want to make available by default
177        for this application
178   
179        :return: the next free event ID following the new menu events
180       
181        """
182        from sans.models.SphereModel import SphereModel
183        self.shape_list.append(SphereModel)
184        self.multiplication_factor.append(SphereModel)
185       
186        from sans.models.BinaryHSModel import BinaryHSModel
187        self.shape_list.append(BinaryHSModel)
188                       
189        from sans.models.FuzzySphereModel import FuzzySphereModel
190        self.shape_list.append(FuzzySphereModel)
191        self.multiplication_factor.append(FuzzySphereModel)
192           
193        from sans.models.CoreShellModel import CoreShellModel
194        self.shape_list.append(CoreShellModel)
195        self.multiplication_factor.append(CoreShellModel)
196       
197        from sans.models.CoreMultiShellModel import CoreMultiShellModel
198        self.shape_list.append(CoreMultiShellModel)
199        self.multiplication_factor.append(CoreMultiShellModel)
200        self.multi_func_list.append(CoreMultiShellModel)
201
202        from sans.models.VesicleModel import VesicleModel
203        self.shape_list.append(VesicleModel)
204        self.multiplication_factor.append(VesicleModel)
205       
206        from sans.models.MultiShellModel import MultiShellModel
207        self.shape_list.append(MultiShellModel)
208        self.multiplication_factor.append(MultiShellModel)
209       
210        from sans.models.OnionExpShellModel import OnionExpShellModel
211        self.shape_list.append(OnionExpShellModel)
212        self.multiplication_factor.append(OnionExpShellModel)
213        self.multi_func_list.append(OnionExpShellModel)
214                       
215        from sans.models.SphericalSLDModel import SphericalSLDModel
216        self.shape_list.append(SphericalSLDModel)
217        self.multiplication_factor.append(SphericalSLDModel)
218        self.multi_func_list.append(SphericalSLDModel)
219       
220        from sans.models.CylinderModel import CylinderModel
221        self.shape_list.append(CylinderModel)
222        self.multiplication_factor.append(CylinderModel)
223       
224        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
225        self.shape_list.append(CoreShellCylinderModel)
226        self.multiplication_factor.append(CoreShellCylinderModel)
227       
228        from sans.models.HollowCylinderModel import HollowCylinderModel
229        self.shape_list.append(HollowCylinderModel)
230        self.multiplication_factor.append(HollowCylinderModel)
231             
232        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
233        self.shape_list.append(FlexibleCylinderModel)
234
235        from sans.models.FlexCylEllipXModel import FlexCylEllipXModel
236        self.shape_list.append(FlexCylEllipXModel)
237       
238        from sans.models.StackedDisksModel import StackedDisksModel
239        self.shape_list.append(StackedDisksModel)
240        self.multiplication_factor.append(StackedDisksModel)
241       
242        from sans.models.ParallelepipedModel import ParallelepipedModel
243        self.shape_list.append(ParallelepipedModel)
244        self.multiplication_factor.append(ParallelepipedModel)
245       
246        from sans.models.CSParallelepipedModel import CSParallelepipedModel
247        self.shape_list.append(CSParallelepipedModel)
248        self.multiplication_factor.append(CSParallelepipedModel)
249       
250        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
251        self.shape_list.append(EllipticalCylinderModel)
252        self.multiplication_factor.append(EllipticalCylinderModel)
253       
254        from sans.models.BarBellModel import BarBellModel
255        self.shape_list.append(BarBellModel)
256        # not implemeted yet!
257        #self.multiplication_factor.append(BarBellModel)
258       
259        from sans.models.CappedCylinderModel import CappedCylinderModel
260        self.shape_list.append(CappedCylinderModel)
261        # not implemeted yet!
262        #self.multiplication_factor.append(CappedCylinderModel)
263       
264        from sans.models.EllipsoidModel import EllipsoidModel
265        self.shape_list.append(EllipsoidModel)
266        self.multiplication_factor.append(EllipsoidModel)
267     
268        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
269        self.shape_list.append(CoreShellEllipsoidModel)
270        self.multiplication_factor.append(CoreShellEllipsoidModel)
271         
272        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
273        self.shape_list.append(TriaxialEllipsoidModel)
274        self.multiplication_factor.append(TriaxialEllipsoidModel)
275       
276        from sans.models.LamellarModel import LamellarModel
277        self.shape_list.append(LamellarModel)
278       
279        from sans.models.LamellarFFHGModel import LamellarFFHGModel
280        self.shape_list.append(LamellarFFHGModel)
281       
282        from sans.models.LamellarPSModel import LamellarPSModel
283        self.shape_list.append(LamellarPSModel)
284     
285        from sans.models.LamellarPSHGModel import LamellarPSHGModel
286        self.shape_list.append(LamellarPSHGModel)
287       
288        from sans.models.LamellarPCrystalModel import LamellarPCrystalModel
289        self.shape_list.append(LamellarPCrystalModel)
290       
291        from sans.models.SCCrystalModel import SCCrystalModel
292        self.shape_list.append(SCCrystalModel)
293       
294        from sans.models.FCCrystalModel import FCCrystalModel
295        self.shape_list.append(FCCrystalModel)
296       
297        from sans.models.BCCrystalModel import BCCrystalModel
298        self.shape_list.append(BCCrystalModel)
299     
300        ## Structure factor
301        from sans.models.SquareWellStructure import SquareWellStructure
302        self.struct_list.append(SquareWellStructure)
303       
304        from sans.models.HardsphereStructure import HardsphereStructure
305        self.struct_list.append(HardsphereStructure)
306         
307        from sans.models.StickyHSStructure import StickyHSStructure
308        self.struct_list.append(StickyHSStructure)
309       
310        from sans.models.HayterMSAStructure import HayterMSAStructure
311        self.struct_list.append(HayterMSAStructure)
312       
313        ##shape-independent models
314        from sans.models.PowerLawAbsModel import PowerLawAbsModel
315        self.shape_indep_list.append( PowerLawAbsModel )
316       
317        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
318        self.shape_indep_list.append(BEPolyelectrolyte )
319        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
320       
321        from sans.models.BroadPeakModel import BroadPeakModel
322        self.shape_indep_list.append(BroadPeakModel)
323       
324        from sans.models.CorrLengthModel import CorrLengthModel
325        self.shape_indep_list.append(CorrLengthModel)
326       
327        from sans.models.DABModel import DABModel
328        self.shape_indep_list.append(DABModel )
329       
330        from sans.models.DebyeModel import DebyeModel
331        self.shape_indep_list.append(DebyeModel )
332       
333        #FractalModel (a c-model)is now being used instead of FractalAbsModel.
334        from sans.models.FractalModel import FractalModel
335        self.shape_indep_list.append(FractalModel )
336       
337        from sans.models.FractalCoreShellModel import FractalCoreShellModel
338        self.shape_indep_list.append(FractalCoreShellModel )
339       
340        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
341        self.shape_indep_list.append(GaussLorentzGelModel) 
342               
343        from sans.models.GuinierModel import GuinierModel
344        self.shape_indep_list.append(GuinierModel )
345       
346        from sans.models.GuinierPorodModel import GuinierPorodModel
347        self.shape_indep_list.append(GuinierPorodModel )
348
349        from sans.models.LorentzModel import LorentzModel
350        self.shape_indep_list.append( LorentzModel) 
351       
352        from sans.models.PeakGaussModel import PeakGaussModel
353        self.shape_indep_list.append(PeakGaussModel)
354       
355        from sans.models.PeakLorentzModel import PeakLorentzModel
356        self.shape_indep_list.append(PeakLorentzModel)
357       
358        from sans.models.Poly_GaussCoil import Poly_GaussCoil
359        self.shape_indep_list.append(Poly_GaussCoil)
360       
361        from sans.models.PolymerExclVolume import PolymerExclVolume
362        self.shape_indep_list.append(PolymerExclVolume)
363       
364        from sans.models.PorodModel import PorodModel
365        self.shape_indep_list.append(PorodModel )     
366       
367        from sans.models.RPA10Model import RPA10Model
368        self.shape_indep_list.append(RPA10Model)
369        self.multi_func_list.append(RPA10Model)
370       
371        from sans.models.TeubnerStreyModel import TeubnerStreyModel
372        self.shape_indep_list.append(TeubnerStreyModel )
373       
374        from sans.models.TwoLorentzianModel import TwoLorentzianModel
375        self.shape_indep_list.append(TwoLorentzianModel )
376       
377        from sans.models.TwoPowerLawModel import TwoPowerLawModel
378        self.shape_indep_list.append(TwoPowerLawModel )
379       
380        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
381        self.shape_indep_list.append(UnifiedPowerRgModel )
382        self.multi_func_list.append(UnifiedPowerRgModel)
383       
384        from sans.models.LineModel import LineModel
385        self.shape_indep_list.append(LineModel)
386       
387        from sans.models.ReflectivityModel import ReflectivityModel
388        self.multi_func_list.append(ReflectivityModel)
389       
390        from sans.models.ReflectivityIIModel import ReflectivityIIModel
391        self.multi_func_list.append(ReflectivityIIModel)
392   
393        #Looking for plugins
394        self.stored_plugins = findModels()
395        self.plugins = self.stored_plugins.values()
396        self.plugins.append(ReflectivityModel)
397        self.plugins.append(ReflectivityIIModel)
398        self._get_multifunc_models()
399       
400        return 0
401
402   
403    def update(self):
404        """
405        """
406        new_plugins = findModels()
407        for name, plug in  new_plugins.iteritems():
408            if name not in self.stored_plugins.keys():
409                self.stored_plugins[name] = plug
410                self.plugins.append(plug)
411        self.model_combobox.set_list("Customized Models", self.plugins)
412        return self.model_combobox.get_list()
413       
414    def populate_menu(self, modelmenu, event_owner):
415        """
416        Populate a menu with our models
417       
418        :param id: first menu event ID to use when binding the menu events
419        :param modelmenu: wx.Menu object to populate
420        :param event_owner: wx object to bind the menu events to
421       
422        :return: the next free event ID following the new menu events
423       
424        """
425        ## Fill model lists
426        self._getModelList()
427        ## store reference to model menu of guiframe
428        self.modelmenu = modelmenu
429        ## guiframe reference
430        self.event_owner = event_owner
431       
432        shape_submenu = wx.Menu()
433        shape_indep_submenu = wx.Menu()
434        structure_factor = wx.Menu()
435        added_models = wx.Menu()
436        multip_models = wx.Menu()
437        ## create menu with shape
438        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
439                         list1=self.shape_list)
440       
441        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
442                                    "List of shape-independent models"],
443                         list1=self.shape_indep_list )
444       
445        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
446                                          "List of Structure factors models" ],
447                                list1=self.struct_list)
448       
449        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
450                                            "List of additional models"],
451                                 list1=self.plugins)
452       
453        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
454                                  "mulplication of 2 models"],
455                                   list1=self.multiplication_factor ,
456                                   list2= self.struct_list)
457        return 0
458   
459    def _fill_plugin_menu(self, menuinfo, list1):
460        """
461        fill the plugin menu with costumized models
462        """
463        if len(list1)==0:
464            id = wx.NewId() 
465            msg= "No model available check plugins.log for errors to fix problem"
466            menuinfo[1].Append(int(id),"Empty",msg)
467        self._fill_simple_menu( menuinfo,list1)
468       
469    def _fill_simple_menu(self, menuinfo, list1):
470        """
471        Fill the menu with list item
472       
473        :param modelmenu: the menu to fill
474        :param menuinfo: submenu item for the first column of this modelmenu
475                         with info.Should be a list :
476                         [name(string) , menu(wx.menu), help(string)]
477        :param list1: contains item (form factor )to fill modelmenu second column
478       
479        """
480        if len(list1)>0:
481            self.model_combobox.set_list(menuinfo[0],list1)
482           
483            for item in list1:
484                try:
485                    id = wx.NewId() 
486                    struct_factor=item()
487                    struct_name = struct_factor.__class__.__name__
488                    if hasattr(struct_factor, "name"):
489                        struct_name = struct_factor.name
490                       
491                    menuinfo[1].Append(int(id),struct_name,struct_name)
492                    if not  item in self.struct_factor_dict.itervalues():
493                        self.struct_factor_dict[str(id)]= item
494                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
495                except:
496                    msg= "Error Occured: %s"%sys.exc_value
497                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
498               
499        id = wx.NewId()         
500        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
501       
502    def _fill_menu(self, menuinfo, list1, list2):
503        """
504        Fill the menu with list item
505       
506        :param menuinfo: submenu item for the first column of this modelmenu
507                         with info.Should be a list :
508                         [name(string) , menu(wx.menu), help(string)]
509        :param list1: contains item (form factor )to fill modelmenu second column
510        :param list2: contains item (Structure factor )to fill modelmenu
511                third column
512               
513        """
514        if len(list1)>0:
515            self.model_combobox.set_list(menuinfo[0],list1)
516           
517            for item in list1:   
518                form_factor= item()
519                form_name = form_factor.__class__.__name__
520                if hasattr(form_factor, "name"):
521                    form_name = form_factor.name
522                ### store form factor to return to other users   
523                newmenu= wx.Menu()
524                if len(list2)>0:
525                    for model  in list2:
526                        id = wx.NewId()
527                        struct_factor = model()
528                        name = struct_factor.__class__.__name__
529                        if hasattr(struct_factor, "name"):
530                            name = struct_factor.name
531                        newmenu.Append(id,name, name)
532                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
533                        ## save form_fact and struct_fact
534                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
535                       
536                form_id= wx.NewId()   
537                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
538        id=wx.NewId()
539        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
540       
541    def _on_model(self, evt):
542        """
543        React to a model menu event
544       
545        :param event: wx menu event
546       
547        """
548        if int(evt.GetId()) in self.form_factor_dict.keys():
549            from sans.models.MultiplicationModel import MultiplicationModel
550            model1, model2 = self.form_factor_dict[int(evt.GetId())]
551            model = MultiplicationModel(model1, model2)   
552        else:
553            model= self.struct_factor_dict[str(evt.GetId())]()
554        evt = ModelEvent(model=model)
555        wx.PostEvent(self.event_owner, evt)
556       
557    def _get_multifunc_models(self):
558        """
559        Get the multifunctional models
560        """
561        for item in self.plugins:
562            try:
563                # check the multiplicity if any
564                if item.multiplicity_info[0] > 1:
565                    self.multi_func_list.append(item)
566            except:
567                # pass to other items
568                pass
569                   
570    def get_model_list(self):   
571        """
572        return dictionary of models for fitpanel use
573       
574        """
575        self.model_combobox.set_list("Shapes", self.shape_list)
576        self.model_combobox.set_list("Shape-Independent", self.shape_indep_list)
577        self.model_combobox.set_list("Structure Factors", self.struct_list)
578        self.model_combobox.set_list("Customized Models", self.plugins)
579        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
580        self.model_combobox.set_list("multiplication", self.multiplication_factor)
581        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
582        return self.model_combobox.get_list()
583   
584 
585       
586   
587   
588 
Note: See TracBrowser for help on using the repository browser.