source: sasview/fittingview/src/sans/perspectives/fitting/models.py @ 61184df

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 61184df was 61184df, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Fixing code style problems and bugs

  • Property mode set to 100644
File size: 33.5 KB
Line 
1"""
2    Utilities to manage models
3"""
4import wx
5import wx.lib.newevent
6import imp
7import os
8import sys
9import math
10import os.path
11# Time is needed by the log method
12import time
13import logging
14import py_compile
15import shutil
16from sans.guiframe.events import StatusEvent 
17# Explicitly import from the pluginmodel module so that py2exe
18# places it in the distribution. The Model1DPlugin class is used
19# as the base class of plug-in models.
20from sans.models.pluginmodel import Model1DPlugin
21   
22PLUGIN_DIR = 'plugin_models' 
23
24def log(message):
25    """
26        Log a message in a file located in the user's home directory
27    """
28    dir = os.path.join(os.path.expanduser("~"), '.sansview', PLUGIN_DIR)
29    out = open(os.path.join(dir, "plugins.log"), 'a')
30    out.write("%10g%s\n" % (time.clock(), message))
31    out.close()
32
33
34def _check_plugin(model, name):
35    """
36    Do some checking before model adding plugins in the list
37   
38    :param model: class model to add into the plugin list
39    :param name:name of the module plugin
40   
41    :return model: model if valid model or None if not valid
42   
43    """
44    #Check is the plugin is of type Model1DPlugin
45    if not issubclass(model, Model1DPlugin):
46        msg = "Plugin %s must be of type Model1DPlugin \n" % str(name)
47        log(msg)
48        return None
49    if model.__name__!="Model":
50        msg= "Plugin %s class name must be Model \n" % str(name)
51        log(msg)
52        return None
53    try:
54        new_instance= model()
55    except:
56        msg="Plugin %s error in __init__ \n\t: %s %s\n" % (str(name),
57                                    str(sys.exc_type), sys.exc_value)
58        log(msg)
59        return None
60   
61    new_instance= model() 
62    if hasattr(new_instance,"function"):
63        try:
64           value=new_instance.function()
65        except:
66           msg="Plugin %s: error writing function \n\t :%s %s\n " % (str(name),
67                                    str(sys.exc_type), sys.exc_value)
68           log(msg)
69           return None
70    else:
71       msg="Plugin  %s needs a method called function \n" % str(name)
72       log(msg)
73       return None
74    return model
75 
76def find_plugins_dir():
77    """
78        Find path of the plugins directory.
79        The plugin directory is located in the user's home directory.
80    """
81    dir = os.path.join(os.path.expanduser("~"), '.sansview', PLUGIN_DIR)
82   
83    # If the plugin directory doesn't exist, create it
84    if not os.path.isdir(dir):
85        os.makedirs(dir)
86       
87    # Find paths needed
88    try:
89        # For source
90        if os.path.isdir(os.path.dirname(__file__)):
91            p_dir =  os.path.join(os.path.dirname(__file__), PLUGIN_DIR)
92        else:
93            raise
94    except:
95        # Check for data path next to exe/zip file.
96        #Look for maximum n_dir up of the current dir to find plugins dir
97        n_dir = 12
98        p_dir = None
99        f_dir = os.path.join(os.path.dirname(__file__))
100        for i in range(n_dir):
101            if i > 1:
102                f_dir, _ = os.path.split(f_dir)
103            plugin_path = os.path.join(f_dir, PLUGIN_DIR)
104            if os.path.isdir(plugin_path):
105                p_dir = plugin_path
106                break
107        if not p_dir:
108            raise
109
110    # Place example user models as needed
111    for file in os.listdir(p_dir): 
112        file_path = os.path.join(p_dir, file)
113        if os.path.isfile(file_path):
114            if file.split(".")[-1] == 'py' and\
115                file.split(".")[0] != '__init__':
116                if not os.path.isfile(os.path.join(dir, file)):
117                    shutil.copy(file_path, dir)
118    return dir
119
120class ReportProblem:
121    def __nonzero__(self):
122        type, value, traceback = sys.exc_info()
123        if type is not None and issubclass(type, py_compile.PyCompileError):
124            print "Problem with", repr(value)
125            raise type, value, traceback
126        return 1
127   
128report_problem = ReportProblem()
129
130def compile_file(dir):
131    """
132    Compile a py file
133    """
134    try:
135        import compileall
136        compileall.compile_dir(dir=dir, ddir=dir, force=1, quiet=report_problem)
137    except:
138        type, value, traceback = sys.exc_info()
139        return value
140    return None
141
142def _findModels(dir):
143    """
144    """
145    # List of plugin objects
146    plugins = {}
147    # Go through files in plug-in directory
148    #always recompile the folder plugin
149    dir = find_plugins_dir()
150    if not os.path.isdir(dir):
151        msg = "SansView couldn't locate Model plugin folder."
152        msg += """ "%s" does not exist""" % dir
153        logging.warning(msg)
154        return plugins
155    else:
156        log("looking for models in: %s" % str(dir))
157        compile_file(dir)
158        logging.info("pluging model dir: %s\n" % str(dir))
159    try:
160        list = os.listdir(dir)
161        for item in list:
162            toks = os.path.splitext(os.path.basename(item))
163            if toks[1]=='.py' and not toks[0]=='__init__':
164                name = toks[0]
165           
166                path = [os.path.abspath(dir)]
167                file = None
168                try:
169                    (file, path, info) = imp.find_module(name, path)
170                    module = imp.load_module( name, file, item, info )
171                    if hasattr(module, "Model"):
172                        try:
173                            if _check_plugin(module.Model, name)!=None:
174                                plugins[name] = module.Model
175                        except:
176                            msg="Error accessing Model"
177                            msg+="in %s\n  %s %s\n" % (name,
178                                    str(sys.exc_type), sys.exc_value)
179                            log(msg)
180                except:
181                    msg="Error accessing Model"
182                    msg +=" in %s\n  %s %s \n" %(name,
183                                    str(sys.exc_type), sys.exc_value)
184                    log(msg)
185                finally:
186             
187                    if not file==None:
188                        file.close()
189    except:
190        # Don't deal with bad plug-in imports. Just skip.
191        msg = "Could not import model plugin: %s\n" % sys.exc_value
192        log(msg)
193        pass
194    return plugins
195
196class ModelList(object):
197    """
198    Contains dictionary of model and their type
199    """
200    def __init__(self):
201        """
202        """
203        self.mydict = {}
204       
205    def set_list(self, name, mylist):
206        """
207        :param name: the type of the list
208        :param mylist: the list to add
209       
210        """
211        if name not in self.mydict.keys():
212            self.reset_list(name, mylist)
213           
214    def reset_list(self, name, mylist):
215        """
216        :param name: the type of the list
217        :param mylist: the list to add
218        """
219        self.mydict[name] = mylist         
220           
221    def get_list(self):
222        """
223        return all the list stored in a dictionary object
224        """
225        return self.mydict
226       
227class ModelManagerBase:
228    """
229        Base class for the model manager
230    """
231    ## external dict for models
232    model_combobox = ModelList()
233    ## Dictionary of form models
234    form_factor_dict = {}
235    ## dictionary of other
236    struct_factor_dict = {}
237    ##list of form factors
238    shape_list = []
239    ## independent shape model list
240    shape_indep_list = []
241    ##list of structure factors
242    struct_list = []
243    ##list of model allowing multiplication
244    multiplication_factor = []
245    ##list of multifunctional shapes
246    multi_func_list = []
247    ## list of added models
248    plugins = []
249    ## Event owner (guiframe)
250    event_owner = None
251    last_time_dir_modified = 0
252    def __init__(self):
253        """
254        """
255        self.stored_plugins = {}
256        self._getModelList()
257       
258    def findModels(self):
259        """
260        find  plugin model in directory of plugin .recompile all file
261        in the directory if file were modified
262        """
263        temp = {}
264        if self.is_changed():
265            return  _findModels(dir)
266        logging.info("pluging model : %s\n" % str(temp))
267        return temp
268       
269    def _getModelList(self):
270        """
271        List of models we want to make available by default
272        for this application
273   
274        :return: the next free event ID following the new menu events
275       
276        """
277        # regular model names only
278        self.model_name_list = []
279        from sans.models.SphereModel import SphereModel
280        self.shape_list.append(SphereModel)
281        self.multiplication_factor.append(SphereModel)
282        self.model_name_list.append(SphereModel.__name__)
283       
284        from sans.models.BinaryHSModel import BinaryHSModel
285        self.shape_list.append(BinaryHSModel)
286        self.model_name_list.append(BinaryHSModel.__name__)
287                       
288        from sans.models.FuzzySphereModel import FuzzySphereModel
289        self.shape_list.append(FuzzySphereModel)
290        self.multiplication_factor.append(FuzzySphereModel)
291        self.model_name_list.append(FuzzySphereModel.__name__)
292       
293        from sans.models.CoreShellModel import CoreShellModel
294        self.shape_list.append(CoreShellModel)
295        self.multiplication_factor.append(CoreShellModel)
296        self.model_name_list.append(CoreShellModel.__name__)
297       
298        from sans.models.Core2ndMomentModel import Core2ndMomentModel
299        self.shape_list.append(Core2ndMomentModel)
300        self.model_name_list.append(Core2ndMomentModel.__name__)
301       
302        from sans.models.CoreMultiShellModel import CoreMultiShellModel
303        self.shape_list.append(CoreMultiShellModel)
304        self.multiplication_factor.append(CoreMultiShellModel)
305        self.multi_func_list.append(CoreMultiShellModel)
306
307        from sans.models.VesicleModel import VesicleModel
308        self.shape_list.append(VesicleModel)
309        self.multiplication_factor.append(VesicleModel)
310        self.model_name_list.append(VesicleModel.__name__)
311       
312        from sans.models.MultiShellModel import MultiShellModel
313        self.shape_list.append(MultiShellModel)
314        self.multiplication_factor.append(MultiShellModel)
315        self.model_name_list.append(MultiShellModel.__name__)
316       
317        from sans.models.OnionExpShellModel import OnionExpShellModel
318        self.shape_list.append(OnionExpShellModel)
319        self.multiplication_factor.append(OnionExpShellModel)
320        self.multi_func_list.append(OnionExpShellModel)
321                         
322        from sans.models.SphericalSLDModel import SphericalSLDModel
323        self.shape_list.append(SphericalSLDModel)
324        self.multiplication_factor.append(SphericalSLDModel)
325        self.multi_func_list.append(SphericalSLDModel)
326       
327        from sans.models.LinearPearlsModel import LinearPearlsModel
328        self.shape_list.append(LinearPearlsModel)
329        self.model_name_list.append(LinearPearlsModel.__name__)
330         
331        from sans.models.PearlNecklaceModel import PearlNecklaceModel
332        self.shape_list.append(PearlNecklaceModel)
333        self.model_name_list.append(PearlNecklaceModel.__name__)
334        #self.multiplication_factor.append(PearlNecklaceModel)
335       
336        from sans.models.CylinderModel import CylinderModel
337        self.shape_list.append(CylinderModel)
338        self.multiplication_factor.append(CylinderModel)
339        self.model_name_list.append(CylinderModel.__name__)
340       
341        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
342        self.shape_list.append(CoreShellCylinderModel)
343        self.multiplication_factor.append(CoreShellCylinderModel)
344        self.model_name_list.append(CoreShellCylinderModel.__name__)
345       
346        from sans.models.CoreShellBicelleModel import CoreShellBicelleModel
347        self.shape_list.append(CoreShellBicelleModel)
348        self.multiplication_factor.append(CoreShellBicelleModel)
349        self.model_name_list.append(CoreShellBicelleModel.__name__)
350               
351        from sans.models.HollowCylinderModel import HollowCylinderModel
352        self.shape_list.append(HollowCylinderModel)
353        self.multiplication_factor.append(HollowCylinderModel)
354        self.model_name_list.append(HollowCylinderModel.__name__)
355             
356        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
357        self.shape_list.append(FlexibleCylinderModel)
358        self.model_name_list.append(FlexibleCylinderModel.__name__)
359
360        from sans.models.FlexCylEllipXModel import FlexCylEllipXModel
361        self.shape_list.append(FlexCylEllipXModel)
362        self.model_name_list.append(FlexCylEllipXModel.__name__)
363       
364        from sans.models.StackedDisksModel import StackedDisksModel
365        self.shape_list.append(StackedDisksModel)
366        self.multiplication_factor.append(StackedDisksModel)
367        self.model_name_list.append(StackedDisksModel.__name__)
368       
369        from sans.models.ParallelepipedModel import ParallelepipedModel
370        self.shape_list.append(ParallelepipedModel)
371        self.multiplication_factor.append(ParallelepipedModel)
372        self.model_name_list.append(ParallelepipedModel.__name__)
373       
374        from sans.models.CSParallelepipedModel import CSParallelepipedModel
375        self.shape_list.append(CSParallelepipedModel)
376        self.multiplication_factor.append(CSParallelepipedModel)
377        self.model_name_list.append(CSParallelepipedModel.__name__)
378       
379        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
380        self.shape_list.append(EllipticalCylinderModel)
381        self.multiplication_factor.append(EllipticalCylinderModel)
382        self.model_name_list.append(EllipticalCylinderModel.__name__)
383       
384        from sans.models.BarBellModel import BarBellModel
385        self.shape_list.append(BarBellModel)
386        self.model_name_list.append(BarBellModel.__name__)
387        # not implemeted yet!
388        #self.multiplication_factor.append(BarBellModel)
389       
390        from sans.models.CappedCylinderModel import CappedCylinderModel
391        self.shape_list.append(CappedCylinderModel)
392        self.model_name_list.append(CappedCylinderModel.__name__)
393        # not implemeted yet!
394        #self.multiplication_factor.append(CappedCylinderModel)
395       
396        from sans.models.EllipsoidModel import EllipsoidModel
397        self.shape_list.append(EllipsoidModel)
398        self.multiplication_factor.append(EllipsoidModel)
399        self.model_name_list.append(EllipsoidModel.__name__)
400     
401        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
402        self.shape_list.append(CoreShellEllipsoidModel)
403        self.multiplication_factor.append(CoreShellEllipsoidModel)
404        self.model_name_list.append(CoreShellEllipsoidModel.__name__)
405         
406        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
407        self.shape_list.append(TriaxialEllipsoidModel)
408        self.multiplication_factor.append(TriaxialEllipsoidModel)
409        self.model_name_list.append(TriaxialEllipsoidModel.__name__)
410       
411        from sans.models.LamellarModel import LamellarModel
412        self.shape_list.append(LamellarModel)
413        self.model_name_list.append(LamellarModel.__name__)
414       
415        from sans.models.LamellarFFHGModel import LamellarFFHGModel
416        self.shape_list.append(LamellarFFHGModel)
417        self.model_name_list.append(LamellarFFHGModel.__name__)
418       
419        from sans.models.LamellarPSModel import LamellarPSModel
420        self.shape_list.append(LamellarPSModel)
421        self.model_name_list.append(LamellarPSModel.__name__)
422     
423        from sans.models.LamellarPSHGModel import LamellarPSHGModel
424        self.shape_list.append(LamellarPSHGModel)
425        self.model_name_list.append(LamellarPSHGModel.__name__)
426       
427        from sans.models.LamellarPCrystalModel import LamellarPCrystalModel
428        self.shape_list.append(LamellarPCrystalModel)
429        self.model_name_list.append(LamellarPCrystalModel.__name__)
430       
431        from sans.models.SCCrystalModel import SCCrystalModel
432        self.shape_list.append(SCCrystalModel)
433        self.model_name_list.append(SCCrystalModel.__name__)
434       
435        from sans.models.FCCrystalModel import FCCrystalModel
436        self.shape_list.append(FCCrystalModel)
437        self.model_name_list.append(FCCrystalModel.__name__)
438       
439        from sans.models.BCCrystalModel import BCCrystalModel
440        self.shape_list.append(BCCrystalModel)
441        self.model_name_list.append(BCCrystalModel.__name__)
442     
443        ## Structure factor
444        from sans.models.SquareWellStructure import SquareWellStructure
445        self.struct_list.append(SquareWellStructure)
446        self.model_name_list.append(SquareWellStructure.__name__)
447       
448        from sans.models.HardsphereStructure import HardsphereStructure
449        self.struct_list.append(HardsphereStructure)
450        self.model_name_list.append(HardsphereStructure.__name__)
451         
452        from sans.models.StickyHSStructure import StickyHSStructure
453        self.struct_list.append(StickyHSStructure)
454        self.model_name_list.append(StickyHSStructure.__name__)
455       
456        from sans.models.HayterMSAStructure import HayterMSAStructure
457        self.struct_list.append(HayterMSAStructure)
458        self.model_name_list.append(HayterMSAStructure.__name__)
459       
460        ##shape-independent models
461        from sans.models.PowerLawAbsModel import PowerLawAbsModel
462        self.shape_indep_list.append( PowerLawAbsModel )
463        self.model_name_list.append(PowerLawAbsModel.__name__)
464       
465        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
466        self.shape_indep_list.append(BEPolyelectrolyte )
467        self.model_name_list.append(BEPolyelectrolyte.__name__)
468        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
469       
470        from sans.models.BroadPeakModel import BroadPeakModel
471        self.shape_indep_list.append(BroadPeakModel)
472        self.model_name_list.append(BroadPeakModel.__name__)
473       
474        from sans.models.CorrLengthModel import CorrLengthModel
475        self.shape_indep_list.append(CorrLengthModel)
476        self.model_name_list.append(CorrLengthModel.__name__)
477       
478        from sans.models.DABModel import DABModel
479        self.shape_indep_list.append(DABModel )
480        self.model_name_list.append(DABModel.__name__)
481       
482        from sans.models.DebyeModel import DebyeModel
483        self.shape_indep_list.append(DebyeModel )
484        self.model_name_list.append(DebyeModel.__name__)
485       
486        #FractalModel (a c-model)is now being used instead of FractalAbsModel.
487        from sans.models.FractalModel import FractalModel
488        self.shape_indep_list.append(FractalModel )
489        self.model_name_list.append(FractalModel.__name__)
490       
491        from sans.models.FractalCoreShellModel import FractalCoreShellModel
492        self.shape_indep_list.append(FractalCoreShellModel )
493        self.model_name_list.append(FractalCoreShellModel.__name__)
494       
495        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
496        self.shape_indep_list.append(GaussLorentzGelModel) 
497        self.model_name_list.append(GaussLorentzGelModel.__name__)
498               
499        from sans.models.GuinierModel import GuinierModel
500        self.shape_indep_list.append(GuinierModel )
501        self.model_name_list.append(GuinierModel.__name__)
502       
503        from sans.models.GuinierPorodModel import GuinierPorodModel
504        self.shape_indep_list.append(GuinierPorodModel )
505        self.model_name_list.append(GuinierPorodModel.__name__)
506
507        from sans.models.LorentzModel import LorentzModel
508        self.shape_indep_list.append( LorentzModel) 
509        self.model_name_list.append(LorentzModel.__name__)
510
511        from sans.models.MassFractalModel import MassFractalModel
512        self.shape_indep_list.append(MassFractalModel)
513        self.model_name_list.append(MassFractalModel.__name__)
514       
515        from sans.models.MassSurfaceFractal import MassSurfaceFractal
516        self.shape_indep_list.append(MassSurfaceFractal)
517        self.model_name_list.append(MassSurfaceFractal.__name__)
518       
519        from sans.models.PeakGaussModel import PeakGaussModel
520        self.shape_indep_list.append(PeakGaussModel)
521        self.model_name_list.append(PeakGaussModel.__name__)
522       
523        from sans.models.PeakLorentzModel import PeakLorentzModel
524        self.shape_indep_list.append(PeakLorentzModel)
525        self.model_name_list.append( PeakLorentzModel.__name__)
526       
527        from sans.models.Poly_GaussCoil import Poly_GaussCoil
528        self.shape_indep_list.append(Poly_GaussCoil)
529        self.model_name_list.append(Poly_GaussCoil.__name__)
530       
531        from sans.models.PolymerExclVolume import PolymerExclVolume
532        self.shape_indep_list.append(PolymerExclVolume)
533        self.model_name_list.append(PolymerExclVolume.__name__)
534       
535        from sans.models.PorodModel import PorodModel
536        self.shape_indep_list.append(PorodModel ) 
537        self.model_name_list.append(PorodModel.__name__)   
538       
539        from sans.models.RPA10Model import RPA10Model
540        self.shape_indep_list.append(RPA10Model)
541        self.multi_func_list.append(RPA10Model)
542
543        from sans.models.SurfaceFractalModel import SurfaceFractalModel
544        self.shape_indep_list.append(SurfaceFractalModel)
545        self.model_name_list.append(SurfaceFractalModel.__name__)
546       
547        from sans.models.TeubnerStreyModel import TeubnerStreyModel
548        self.shape_indep_list.append(TeubnerStreyModel )
549        self.model_name_list.append(TeubnerStreyModel.__name__)
550       
551        from sans.models.TwoLorentzianModel import TwoLorentzianModel
552        self.shape_indep_list.append(TwoLorentzianModel )
553        self.model_name_list.append(TwoLorentzianModel.__name__)
554       
555        from sans.models.TwoPowerLawModel import TwoPowerLawModel
556        self.shape_indep_list.append(TwoPowerLawModel )
557        self.model_name_list.append(TwoPowerLawModel.__name__)
558       
559        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
560        self.shape_indep_list.append(UnifiedPowerRgModel )
561        self.multi_func_list.append(UnifiedPowerRgModel)
562       
563        from sans.models.LineModel import LineModel
564        self.shape_indep_list.append(LineModel)
565        self.model_name_list.append(LineModel.__name__)
566       
567        from sans.models.ReflectivityModel import ReflectivityModel
568        self.multi_func_list.append(ReflectivityModel)
569       
570        from sans.models.ReflectivityIIModel import ReflectivityIIModel
571        self.multi_func_list.append(ReflectivityIIModel)
572   
573        #Looking for plugins
574        self.stored_plugins = self.findModels()
575        self.plugins = self.stored_plugins.values()
576        self.plugins.append(ReflectivityModel)
577        self.plugins.append(ReflectivityIIModel)
578        self._get_multifunc_models()
579       
580        return 0
581
582    def is_changed(self):
583        """
584        check the last time the plugin dir has changed and return true
585         is the directory was modified else return false
586        """
587        is_modified = False
588        plugin_dir = find_plugins_dir()
589        if os.path.isdir(plugin_dir):
590            temp =  os.path.getmtime(plugin_dir)
591            if  self.last_time_dir_modified != temp:
592                is_modified = True
593                self.last_time_dir_modified = temp
594       
595        return is_modified
596   
597    def update(self):
598        """
599        return a dictionary of model if
600        new models were added else return empty dictionary
601        """
602        new_plugins = self.findModels()
603        if len(new_plugins) > 0:
604            for name, plug in  new_plugins.iteritems():
605                if name not in self.stored_plugins.keys():
606                    self.stored_plugins[name] = plug
607                    self.plugins.append(plug)
608            self.model_combobox.set_list("Customized Models", self.plugins)
609            return self.model_combobox.get_list()
610        else:
611            return {}
612   
613    def pulgins_reset(self):
614        """
615        return a dictionary of model
616        """
617        self.plugins = []
618        new_plugins = _findModels(dir)
619        for name, plug in  new_plugins.iteritems():
620            for stored_name, stored_plug in self.stored_plugins.iteritems():
621                if name == stored_name:
622                    del self.stored_plugins[name]
623                    break
624            self.stored_plugins[name] = plug
625            self.plugins.append(plug)
626        from sans.models.ReflectivityModel import ReflectivityModel
627        from sans.models.ReflectivityIIModel import ReflectivityIIModel
628        self.plugins.append(ReflectivityModel)
629        self.plugins.append(ReflectivityIIModel)
630        self.model_combobox.reset_list("Customized Models", self.plugins)
631        return self.model_combobox.get_list()
632       
633    def populate_menu(self, modelmenu, event_owner):
634        """
635        Populate a menu with our models
636       
637        :param id: first menu event ID to use when binding the menu events
638        :param modelmenu: wx.Menu object to populate
639        :param event_owner: wx object to bind the menu events to
640       
641        :return: the next free event ID following the new menu events
642       
643        """
644        ## Fill model lists
645        self._getModelList()
646        ## store reference to model menu of guiframe
647        self.modelmenu = modelmenu
648        ## guiframe reference
649        self.event_owner = event_owner
650       
651        shape_submenu = wx.Menu()
652        shape_indep_submenu = wx.Menu()
653        structure_factor = wx.Menu()
654        added_models = wx.Menu()
655        multip_models = wx.Menu()
656        ## create menu with shape
657        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
658                         list1=self.shape_list)
659       
660        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
661                                    "List of shape-independent models"],
662                         list1=self.shape_indep_list )
663       
664        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
665                                          "List of Structure factors models" ],
666                                list1=self.struct_list)
667       
668        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
669                                            "List of additional models"],
670                                 list1=self.plugins)
671       
672        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
673                                  "mulplication of 2 models"],
674                                   list1=self.multiplication_factor ,
675                                   list2= self.struct_list)
676        return 0
677   
678    def _fill_plugin_menu(self, menuinfo, list1):
679        """
680        fill the plugin menu with costumized models
681        """
682        if len(list1)==0:
683            id = wx.NewId() 
684            msg= "No model available check plugins.log for errors to fix problem"
685            menuinfo[1].Append(int(id),"Empty",msg)
686        self._fill_simple_menu( menuinfo,list1)
687       
688    def _fill_simple_menu(self, menuinfo, list1):
689        """
690        Fill the menu with list item
691       
692        :param modelmenu: the menu to fill
693        :param menuinfo: submenu item for the first column of this modelmenu
694                         with info.Should be a list :
695                         [name(string) , menu(wx.menu), help(string)]
696        :param list1: contains item (form factor )to fill modelmenu second column
697       
698        """
699        if len(list1)>0:
700            self.model_combobox.set_list(menuinfo[0],list1)
701           
702            for item in list1:
703                try:
704                    id = wx.NewId() 
705                    struct_factor=item()
706                    struct_name = struct_factor.__class__.__name__
707                    if hasattr(struct_factor, "name"):
708                        struct_name = struct_factor.name
709                       
710                    menuinfo[1].Append(int(id),struct_name,struct_name)
711                    if not  item in self.struct_factor_dict.itervalues():
712                        self.struct_factor_dict[str(id)]= item
713                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
714                except:
715                    msg= "Error Occured: %s"%sys.exc_value
716                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
717               
718        id = wx.NewId()         
719        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
720       
721    def _fill_menu(self, menuinfo, list1, list2):
722        """
723        Fill the menu with list item
724       
725        :param menuinfo: submenu item for the first column of this modelmenu
726                         with info.Should be a list :
727                         [name(string) , menu(wx.menu), help(string)]
728        :param list1: contains item (form factor )to fill modelmenu second column
729        :param list2: contains item (Structure factor )to fill modelmenu
730                third column
731               
732        """
733        if len(list1)>0:
734            self.model_combobox.set_list(menuinfo[0],list1)
735           
736            for item in list1:   
737                form_factor= item()
738                form_name = form_factor.__class__.__name__
739                if hasattr(form_factor, "name"):
740                    form_name = form_factor.name
741                ### store form factor to return to other users   
742                newmenu= wx.Menu()
743                if len(list2)>0:
744                    for model  in list2:
745                        id = wx.NewId()
746                        struct_factor = model()
747                        name = struct_factor.__class__.__name__
748                        if hasattr(struct_factor, "name"):
749                            name = struct_factor.name
750                        newmenu.Append(id,name, name)
751                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
752                        ## save form_fact and struct_fact
753                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
754                       
755                form_id= wx.NewId()   
756                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
757        id=wx.NewId()
758        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
759       
760    def _on_model(self, evt):
761        """
762        React to a model menu event
763       
764        :param event: wx menu event
765       
766        """
767        if int(evt.GetId()) in self.form_factor_dict.keys():
768            from sans.models.MultiplicationModel import MultiplicationModel
769            model1, model2 = self.form_factor_dict[int(evt.GetId())]
770            model = MultiplicationModel(model1, model2)   
771        else:
772            model= self.struct_factor_dict[str(evt.GetId())]()
773       
774        #TODO: investigate why the following two lines were left in the code
775        #      even though the ModelEvent class doesn't exist
776        #evt = ModelEvent(model=model)
777        #wx.PostEvent(self.event_owner, evt)
778       
779    def _get_multifunc_models(self):
780        """
781        Get the multifunctional models
782        """
783        for item in self.plugins:
784            try:
785                # check the multiplicity if any
786                if item.multiplicity_info[0] > 1:
787                    self.multi_func_list.append(item)
788            except:
789                # pass to other items
790                pass
791                   
792    def get_model_list(self):   
793        """
794        return dictionary of models for fitpanel use
795       
796        """
797        self.model_combobox.set_list("Shapes", self.shape_list)
798        self.model_combobox.set_list("Shape-Independent", self.shape_indep_list)
799        self.model_combobox.set_list("Structure Factors", self.struct_list)
800        self.model_combobox.set_list("Customized Models", self.plugins)
801        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
802        self.model_combobox.set_list("multiplication", self.multiplication_factor)
803        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
804        return self.model_combobox.get_list()
805   
806    def get_model_name_list(self):
807        """
808        return regular model name list
809        """
810        return self.model_name_list
811 
812       
813class ModelManager(object):
814    """
815    implement model
816    """
817    __modelmanager = ModelManagerBase()
818   
819    def findModels(self):
820        return self.__modelmanager.findModels()
821   
822    def _getModelList(self):
823        return self.__modelmanager._getModelList()
824   
825    def is_changed(self):
826        return self.__modelmanager.is_changed()
827   
828    def update(self):
829        return self.__modelmanager.update()
830   
831    def pulgins_reset(self):
832        return self.__modelmanager.pulgins_reset()
833   
834    def populate_menu(self, modelmenu, event_owner):
835        return self.__modelmanager.populate_menu(modelmenu, event_owner)
836   
837    def _on_model(self, evt):
838        return self.__modelmanager._on_model(evt)
839   
840    def _get_multifunc_models(self):
841        return self.__modelmanager._get_multifunc_models()
842   
843    def get_model_list(self): 
844        return self.__modelmanager.get_model_list()
845   
846    def get_model_name_list(self):
847        return self.__modelmanager.get_model_name_list()
848   
849   
850 
Note: See TracBrowser for help on using the repository browser.