source: sasview/sansview/perspectives/fitting/models.py @ 1868cf3

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 1868cf3 was cd0d039, checked in by Gervaise Alina <gervyh@…>, 13 years ago

remove print statement

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