source: sasview/sansview/perspectives/fitting/models.py @ 52d3fd1

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 52d3fd1 was b2d9826, checked in by Gervaise Alina <gervyh@…>, 14 years ago

update plugin

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