source: sasview/fittingview/src/sans/perspectives/fitting/models.py @ 2ee5c61

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 2ee5c61 was 279e371, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Fixing code style problems

  • 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        from sans.models.FractalModel import FractalModel
487        self.shape_indep_list.append(FractalModel )
488        self.model_name_list.append(FractalModel.__name__)
489       
490        from sans.models.FractalCoreShellModel import FractalCoreShellModel
491        self.shape_indep_list.append(FractalCoreShellModel )
492        self.model_name_list.append(FractalCoreShellModel.__name__)
493       
494        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
495        self.shape_indep_list.append(GaussLorentzGelModel) 
496        self.model_name_list.append(GaussLorentzGelModel.__name__)
497               
498        from sans.models.GuinierModel import GuinierModel
499        self.shape_indep_list.append(GuinierModel )
500        self.model_name_list.append(GuinierModel.__name__)
501       
502        from sans.models.GuinierPorodModel import GuinierPorodModel
503        self.shape_indep_list.append(GuinierPorodModel )
504        self.model_name_list.append(GuinierPorodModel.__name__)
505
506        from sans.models.LorentzModel import LorentzModel
507        self.shape_indep_list.append( LorentzModel) 
508        self.model_name_list.append(LorentzModel.__name__)
509
510        from sans.models.MassFractalModel import MassFractalModel
511        self.shape_indep_list.append(MassFractalModel)
512        self.model_name_list.append(MassFractalModel.__name__)
513       
514        from sans.models.MassSurfaceFractal import MassSurfaceFractal
515        self.shape_indep_list.append(MassSurfaceFractal)
516        self.model_name_list.append(MassSurfaceFractal.__name__)
517       
518        from sans.models.PeakGaussModel import PeakGaussModel
519        self.shape_indep_list.append(PeakGaussModel)
520        self.model_name_list.append(PeakGaussModel.__name__)
521       
522        from sans.models.PeakLorentzModel import PeakLorentzModel
523        self.shape_indep_list.append(PeakLorentzModel)
524        self.model_name_list.append( PeakLorentzModel.__name__)
525       
526        from sans.models.Poly_GaussCoil import Poly_GaussCoil
527        self.shape_indep_list.append(Poly_GaussCoil)
528        self.model_name_list.append(Poly_GaussCoil.__name__)
529       
530        from sans.models.PolymerExclVolume import PolymerExclVolume
531        self.shape_indep_list.append(PolymerExclVolume)
532        self.model_name_list.append(PolymerExclVolume.__name__)
533       
534        from sans.models.PorodModel import PorodModel
535        self.shape_indep_list.append(PorodModel ) 
536        self.model_name_list.append(PorodModel.__name__)   
537       
538        from sans.models.RPA10Model import RPA10Model
539        self.shape_indep_list.append(RPA10Model)
540        self.multi_func_list.append(RPA10Model)
541
542        from sans.models.SurfaceFractalModel import SurfaceFractalModel
543        self.shape_indep_list.append(SurfaceFractalModel)
544        self.model_name_list.append(SurfaceFractalModel.__name__)
545       
546        from sans.models.TeubnerStreyModel import TeubnerStreyModel
547        self.shape_indep_list.append(TeubnerStreyModel )
548        self.model_name_list.append(TeubnerStreyModel.__name__)
549       
550        from sans.models.TwoLorentzianModel import TwoLorentzianModel
551        self.shape_indep_list.append(TwoLorentzianModel )
552        self.model_name_list.append(TwoLorentzianModel.__name__)
553       
554        from sans.models.TwoPowerLawModel import TwoPowerLawModel
555        self.shape_indep_list.append(TwoPowerLawModel )
556        self.model_name_list.append(TwoPowerLawModel.__name__)
557       
558        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
559        self.shape_indep_list.append(UnifiedPowerRgModel )
560        self.multi_func_list.append(UnifiedPowerRgModel)
561       
562        from sans.models.LineModel import LineModel
563        self.shape_indep_list.append(LineModel)
564        self.model_name_list.append(LineModel.__name__)
565       
566        from sans.models.ReflectivityModel import ReflectivityModel
567        self.multi_func_list.append(ReflectivityModel)
568       
569        from sans.models.ReflectivityIIModel import ReflectivityIIModel
570        self.multi_func_list.append(ReflectivityIIModel)
571   
572        #Looking for plugins
573        self.stored_plugins = self.findModels()
574        self.plugins = self.stored_plugins.values()
575        self.plugins.append(ReflectivityModel)
576        self.plugins.append(ReflectivityIIModel)
577        self._get_multifunc_models()
578       
579        return 0
580
581    def is_changed(self):
582        """
583        check the last time the plugin dir has changed and return true
584         is the directory was modified else return false
585        """
586        is_modified = False
587        plugin_dir = find_plugins_dir()
588        if os.path.isdir(plugin_dir):
589            temp =  os.path.getmtime(plugin_dir)
590            if  self.last_time_dir_modified != temp:
591                is_modified = True
592                self.last_time_dir_modified = temp
593       
594        return is_modified
595   
596    def update(self):
597        """
598        return a dictionary of model if
599        new models were added else return empty dictionary
600        """
601        new_plugins = self.findModels()
602        if len(new_plugins) > 0:
603            for name, plug in  new_plugins.iteritems():
604                if name not in self.stored_plugins.keys():
605                    self.stored_plugins[name] = plug
606                    self.plugins.append(plug)
607            self.model_combobox.set_list("Customized Models", self.plugins)
608            return self.model_combobox.get_list()
609        else:
610            return {}
611   
612    def pulgins_reset(self):
613        """
614        return a dictionary of model
615        """
616        self.plugins = []
617        new_plugins = _findModels(dir)
618        for name, plug in  new_plugins.iteritems():
619            for stored_name, stored_plug in self.stored_plugins.iteritems():
620                if name == stored_name:
621                    del self.stored_plugins[name]
622                    break
623            self.stored_plugins[name] = plug
624            self.plugins.append(plug)
625        from sans.models.ReflectivityModel import ReflectivityModel
626        from sans.models.ReflectivityIIModel import ReflectivityIIModel
627        self.plugins.append(ReflectivityModel)
628        self.plugins.append(ReflectivityIIModel)
629        self.model_combobox.reset_list("Customized Models", self.plugins)
630        return self.model_combobox.get_list()
631       
632    def populate_menu(self, modelmenu, event_owner):
633        """
634        Populate a menu with our models
635       
636        :param id: first menu event ID to use when binding the menu events
637        :param modelmenu: wx.Menu object to populate
638        :param event_owner: wx object to bind the menu events to
639       
640        :return: the next free event ID following the new menu events
641       
642        """
643        ## Fill model lists
644        self._getModelList()
645        ## store reference to model menu of guiframe
646        self.modelmenu = modelmenu
647        ## guiframe reference
648        self.event_owner = event_owner
649       
650        shape_submenu = wx.Menu()
651        shape_indep_submenu = wx.Menu()
652        structure_factor = wx.Menu()
653        added_models = wx.Menu()
654        multip_models = wx.Menu()
655        ## create menu with shape
656        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
657                         list1=self.shape_list)
658       
659        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
660                                    "List of shape-independent models"],
661                         list1=self.shape_indep_list )
662       
663        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
664                                          "List of Structure factors models" ],
665                                list1=self.struct_list)
666       
667        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
668                                            "List of additional models"],
669                                 list1=self.plugins)
670       
671        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
672                                  "mulplication of 2 models"],
673                                   list1=self.multiplication_factor ,
674                                   list2= self.struct_list)
675        return 0
676   
677    def _fill_plugin_menu(self, menuinfo, list1):
678        """
679        fill the plugin menu with costumized models
680        """
681        if len(list1)==0:
682            id = wx.NewId() 
683            msg= "No model available check plugins.log for errors to fix problem"
684            menuinfo[1].Append(int(id),"Empty",msg)
685        self._fill_simple_menu( menuinfo,list1)
686       
687    def _fill_simple_menu(self, menuinfo, list1):
688        """
689        Fill the menu with list item
690       
691        :param modelmenu: the menu to fill
692        :param menuinfo: submenu item for the first column of this modelmenu
693                         with info.Should be a list :
694                         [name(string) , menu(wx.menu), help(string)]
695        :param list1: contains item (form factor )to fill modelmenu second column
696       
697        """
698        if len(list1)>0:
699            self.model_combobox.set_list(menuinfo[0],list1)
700           
701            for item in list1:
702                try:
703                    id = wx.NewId() 
704                    struct_factor=item()
705                    struct_name = struct_factor.__class__.__name__
706                    if hasattr(struct_factor, "name"):
707                        struct_name = struct_factor.name
708                       
709                    menuinfo[1].Append(int(id),struct_name,struct_name)
710                    if not  item in self.struct_factor_dict.itervalues():
711                        self.struct_factor_dict[str(id)]= item
712                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
713                except:
714                    msg= "Error Occured: %s"%sys.exc_value
715                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
716               
717        id = wx.NewId()         
718        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
719       
720    def _fill_menu(self, menuinfo, list1, list2):
721        """
722        Fill the menu with list item
723       
724        :param menuinfo: submenu item for the first column of this modelmenu
725                         with info.Should be a list :
726                         [name(string) , menu(wx.menu), help(string)]
727        :param list1: contains item (form factor )to fill modelmenu second column
728        :param list2: contains item (Structure factor )to fill modelmenu
729                third column
730               
731        """
732        if len(list1)>0:
733            self.model_combobox.set_list(menuinfo[0],list1)
734           
735            for item in list1:   
736                form_factor= item()
737                form_name = form_factor.__class__.__name__
738                if hasattr(form_factor, "name"):
739                    form_name = form_factor.name
740                ### store form factor to return to other users   
741                newmenu= wx.Menu()
742                if len(list2)>0:
743                    for model  in list2:
744                        id = wx.NewId()
745                        struct_factor = model()
746                        name = struct_factor.__class__.__name__
747                        if hasattr(struct_factor, "name"):
748                            name = struct_factor.name
749                        newmenu.Append(id,name, name)
750                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
751                        ## save form_fact and struct_fact
752                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
753                       
754                form_id= wx.NewId()   
755                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
756        id=wx.NewId()
757        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
758       
759    def _on_model(self, evt):
760        """
761        React to a model menu event
762       
763        :param event: wx menu event
764       
765        """
766        if int(evt.GetId()) in self.form_factor_dict.keys():
767            from sans.models.MultiplicationModel import MultiplicationModel
768            model1, model2 = self.form_factor_dict[int(evt.GetId())]
769            model = MultiplicationModel(model1, model2)   
770        else:
771            model= self.struct_factor_dict[str(evt.GetId())]()
772       
773        #TODO: investigate why the following two lines were left in the code
774        #      even though the ModelEvent class doesn't exist
775        #evt = ModelEvent(model=model)
776        #wx.PostEvent(self.event_owner, evt)
777       
778    def _get_multifunc_models(self):
779        """
780        Get the multifunctional models
781        """
782        for item in self.plugins:
783            try:
784                # check the multiplicity if any
785                if item.multiplicity_info[0] > 1:
786                    self.multi_func_list.append(item)
787            except:
788                # pass to other items
789                pass
790                   
791    def get_model_list(self):   
792        """
793        return dictionary of models for fitpanel use
794       
795        """
796        self.model_combobox.set_list("Shapes", self.shape_list)
797        self.model_combobox.set_list("Shape-Independent", self.shape_indep_list)
798        self.model_combobox.set_list("Structure Factors", self.struct_list)
799        self.model_combobox.set_list("Customized Models", self.plugins)
800        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
801        self.model_combobox.set_list("multiplication", self.multiplication_factor)
802        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
803        return self.model_combobox.get_list()
804   
805    def get_model_name_list(self):
806        """
807        return regular model name list
808        """
809        return self.model_name_list
810 
811       
812class ModelManager(object):
813    """
814    implement model
815    """
816    __modelmanager = ModelManagerBase()
817   
818    def findModels(self):
819        return self.__modelmanager.findModels()
820   
821    def _getModelList(self):
822        return self.__modelmanager._getModelList()
823   
824    def is_changed(self):
825        return self.__modelmanager.is_changed()
826   
827    def update(self):
828        return self.__modelmanager.update()
829   
830    def pulgins_reset(self):
831        return self.__modelmanager.pulgins_reset()
832   
833    def populate_menu(self, modelmenu, event_owner):
834        return self.__modelmanager.populate_menu(modelmenu, event_owner)
835   
836    def _on_model(self, evt):
837        return self.__modelmanager._on_model(evt)
838   
839    def _get_multifunc_models(self):
840        return self.__modelmanager._get_multifunc_models()
841   
842    def get_model_list(self): 
843        return self.__modelmanager.get_model_list()
844   
845    def get_model_name_list(self):
846        return self.__modelmanager.get_model_name_list()
847   
848   
849 
Note: See TracBrowser for help on using the repository browser.