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

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 b7e6bd3 was 9466f2d6, checked in by Gervaise Alina <gervyh@…>, 14 years ago

make sure plugin model are recompile online when the plugin dir has changed

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