source: sasview/sansview/perspectives/fitting/models.py @ 67ae937

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 67ae937 was 5618f92, checked in by Jae Cho <jhjcho@…>, 13 years ago

disabled multi_factor for pearl

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