source: sasview/fittingview/src/sans/perspectives/fitting/models.py @ 7415cbe

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 7415cbe was 543d1bd, checked in by Jae Cho <jhjcho@…>, 12 years ago

Added coreshellbicelle model

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