source: sasview/fittingview/src/sans/perspectives/fitting/models.py @ 9ede123

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 9ede123 was d9547e7, checked in by Jae Cho <jhjcho@…>, 13 years ago

Added linearpearlsmodel and a test

  • Property mode set to 100644
File size: 32.2 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.CoreMultiShellModel import CoreMultiShellModel
296        self.shape_list.append(CoreMultiShellModel)
297        self.multiplication_factor.append(CoreMultiShellModel)
298        self.multi_func_list.append(CoreMultiShellModel)
299
300        from sans.models.VesicleModel import VesicleModel
301        self.shape_list.append(VesicleModel)
302        self.multiplication_factor.append(VesicleModel)
303        self.model_name_list.append(VesicleModel.__name__)
304       
305        from sans.models.MultiShellModel import MultiShellModel
306        self.shape_list.append(MultiShellModel)
307        self.multiplication_factor.append(MultiShellModel)
308        self.model_name_list.append(MultiShellModel.__name__)
309       
310        from sans.models.OnionExpShellModel import OnionExpShellModel
311        self.shape_list.append(OnionExpShellModel)
312        self.multiplication_factor.append(OnionExpShellModel)
313        self.multi_func_list.append(OnionExpShellModel)
314                         
315        from sans.models.SphericalSLDModel import SphericalSLDModel
316        self.shape_list.append(SphericalSLDModel)
317        self.multiplication_factor.append(SphericalSLDModel)
318        self.multi_func_list.append(SphericalSLDModel)
319       
320        from sans.models.LinearPearlsModel import LinearPearlsModel
321        self.shape_list.append(LinearPearlsModel)
322        self.model_name_list.append(LinearPearlsModel.__name__)
323         
324        from sans.models.PearlNecklaceModel import PearlNecklaceModel
325        self.shape_list.append(PearlNecklaceModel)
326        self.model_name_list.append(PearlNecklaceModel.__name__)
327        #self.multiplication_factor.append(PearlNecklaceModel)
328       
329        from sans.models.CylinderModel import CylinderModel
330        self.shape_list.append(CylinderModel)
331        self.multiplication_factor.append(CylinderModel)
332        self.model_name_list.append(CylinderModel.__name__)
333       
334        from sans.models.CoreShellCylinderModel import CoreShellCylinderModel
335        self.shape_list.append(CoreShellCylinderModel)
336        self.multiplication_factor.append(CoreShellCylinderModel)
337        self.model_name_list.append(CoreShellCylinderModel.__name__)
338       
339        from sans.models.HollowCylinderModel import HollowCylinderModel
340        self.shape_list.append(HollowCylinderModel)
341        self.multiplication_factor.append(HollowCylinderModel)
342        self.model_name_list.append(HollowCylinderModel.__name__)
343             
344        from sans.models.FlexibleCylinderModel import FlexibleCylinderModel
345        self.shape_list.append(FlexibleCylinderModel)
346        self.model_name_list.append(FlexibleCylinderModel.__name__)
347
348        from sans.models.FlexCylEllipXModel import FlexCylEllipXModel
349        self.shape_list.append(FlexCylEllipXModel)
350        self.model_name_list.append(FlexCylEllipXModel.__name__)
351       
352        from sans.models.StackedDisksModel import StackedDisksModel
353        self.shape_list.append(StackedDisksModel)
354        self.multiplication_factor.append(StackedDisksModel)
355        self.model_name_list.append(StackedDisksModel.__name__)
356       
357        from sans.models.ParallelepipedModel import ParallelepipedModel
358        self.shape_list.append(ParallelepipedModel)
359        self.multiplication_factor.append(ParallelepipedModel)
360        self.model_name_list.append(ParallelepipedModel.__name__)
361       
362        from sans.models.CSParallelepipedModel import CSParallelepipedModel
363        self.shape_list.append(CSParallelepipedModel)
364        self.multiplication_factor.append(CSParallelepipedModel)
365        self.model_name_list.append(CSParallelepipedModel.__name__)
366       
367        from sans.models.EllipticalCylinderModel import EllipticalCylinderModel
368        self.shape_list.append(EllipticalCylinderModel)
369        self.multiplication_factor.append(EllipticalCylinderModel)
370        self.model_name_list.append(EllipticalCylinderModel.__name__)
371       
372        from sans.models.BarBellModel import BarBellModel
373        self.shape_list.append(BarBellModel)
374        self.model_name_list.append(BarBellModel.__name__)
375        # not implemeted yet!
376        #self.multiplication_factor.append(BarBellModel)
377       
378        from sans.models.CappedCylinderModel import CappedCylinderModel
379        self.shape_list.append(CappedCylinderModel)
380        self.model_name_list.append(CappedCylinderModel.__name__)
381        # not implemeted yet!
382        #self.multiplication_factor.append(CappedCylinderModel)
383       
384        from sans.models.EllipsoidModel import EllipsoidModel
385        self.shape_list.append(EllipsoidModel)
386        self.multiplication_factor.append(EllipsoidModel)
387        self.model_name_list.append(EllipsoidModel.__name__)
388     
389        from sans.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
390        self.shape_list.append(CoreShellEllipsoidModel)
391        self.multiplication_factor.append(CoreShellEllipsoidModel)
392        self.model_name_list.append(CoreShellEllipsoidModel.__name__)
393         
394        from sans.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
395        self.shape_list.append(TriaxialEllipsoidModel)
396        self.multiplication_factor.append(TriaxialEllipsoidModel)
397        self.model_name_list.append(TriaxialEllipsoidModel.__name__)
398       
399        from sans.models.LamellarModel import LamellarModel
400        self.shape_list.append(LamellarModel)
401        self.model_name_list.append(LamellarModel.__name__)
402       
403        from sans.models.LamellarFFHGModel import LamellarFFHGModel
404        self.shape_list.append(LamellarFFHGModel)
405        self.model_name_list.append(LamellarFFHGModel.__name__)
406       
407        from sans.models.LamellarPSModel import LamellarPSModel
408        self.shape_list.append(LamellarPSModel)
409        self.model_name_list.append(LamellarPSModel.__name__)
410     
411        from sans.models.LamellarPSHGModel import LamellarPSHGModel
412        self.shape_list.append(LamellarPSHGModel)
413        self.model_name_list.append(LamellarPSHGModel.__name__)
414       
415        from sans.models.LamellarPCrystalModel import LamellarPCrystalModel
416        self.shape_list.append(LamellarPCrystalModel)
417        self.model_name_list.append(LamellarPCrystalModel.__name__)
418       
419        from sans.models.SCCrystalModel import SCCrystalModel
420        self.shape_list.append(SCCrystalModel)
421        self.model_name_list.append(SCCrystalModel.__name__)
422       
423        from sans.models.FCCrystalModel import FCCrystalModel
424        self.shape_list.append(FCCrystalModel)
425        self.model_name_list.append(FCCrystalModel.__name__)
426       
427        from sans.models.BCCrystalModel import BCCrystalModel
428        self.shape_list.append(BCCrystalModel)
429        self.model_name_list.append(BCCrystalModel.__name__)
430     
431        ## Structure factor
432        from sans.models.SquareWellStructure import SquareWellStructure
433        self.struct_list.append(SquareWellStructure)
434        self.model_name_list.append(SquareWellStructure.__name__)
435       
436        from sans.models.HardsphereStructure import HardsphereStructure
437        self.struct_list.append(HardsphereStructure)
438        self.model_name_list.append(HardsphereStructure.__name__)
439         
440        from sans.models.StickyHSStructure import StickyHSStructure
441        self.struct_list.append(StickyHSStructure)
442        self.model_name_list.append(StickyHSStructure.__name__)
443       
444        from sans.models.HayterMSAStructure import HayterMSAStructure
445        self.struct_list.append(HayterMSAStructure)
446        self.model_name_list.append(HayterMSAStructure.__name__)
447       
448        ##shape-independent models
449        from sans.models.PowerLawAbsModel import PowerLawAbsModel
450        self.shape_indep_list.append( PowerLawAbsModel )
451        self.model_name_list.append(PowerLawAbsModel.__name__)
452       
453        from sans.models.BEPolyelectrolyte import BEPolyelectrolyte
454        self.shape_indep_list.append(BEPolyelectrolyte )
455        self.model_name_list.append(BEPolyelectrolyte.__name__)
456        self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
457       
458        from sans.models.BroadPeakModel import BroadPeakModel
459        self.shape_indep_list.append(BroadPeakModel)
460        self.model_name_list.append(BroadPeakModel.__name__)
461       
462        from sans.models.CorrLengthModel import CorrLengthModel
463        self.shape_indep_list.append(CorrLengthModel)
464        self.model_name_list.append(CorrLengthModel.__name__)
465       
466        from sans.models.DABModel import DABModel
467        self.shape_indep_list.append(DABModel )
468        self.model_name_list.append(DABModel.__name__)
469       
470        from sans.models.DebyeModel import DebyeModel
471        self.shape_indep_list.append(DebyeModel )
472        self.model_name_list.append(DebyeModel.__name__)
473       
474        #FractalModel (a c-model)is now being used instead of FractalAbsModel.
475        from sans.models.FractalModel import FractalModel
476        self.shape_indep_list.append(FractalModel )
477        self.model_name_list.append(FractalModel.__name__)
478       
479        from sans.models.FractalCoreShellModel import FractalCoreShellModel
480        self.shape_indep_list.append(FractalCoreShellModel )
481        self.model_name_list.append(FractalCoreShellModel.__name__)
482       
483        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
484        self.shape_indep_list.append(GaussLorentzGelModel) 
485        self.model_name_list.append(GaussLorentzGelModel.__name__)
486               
487        from sans.models.GuinierModel import GuinierModel
488        self.shape_indep_list.append(GuinierModel )
489        self.model_name_list.append(GuinierModel.__name__)
490       
491        from sans.models.GuinierPorodModel import GuinierPorodModel
492        self.shape_indep_list.append(GuinierPorodModel )
493        self.model_name_list.append(GuinierPorodModel.__name__)
494
495        from sans.models.LorentzModel import LorentzModel
496        self.shape_indep_list.append( LorentzModel) 
497        self.model_name_list.append(LorentzModel.__name__)
498       
499        from sans.models.PeakGaussModel import PeakGaussModel
500        self.shape_indep_list.append(PeakGaussModel)
501        self.model_name_list.append(PeakGaussModel.__name__)
502       
503        from sans.models.PeakLorentzModel import PeakLorentzModel
504        self.shape_indep_list.append(PeakLorentzModel)
505        self.model_name_list.append( PeakLorentzModel.__name__)
506       
507        from sans.models.Poly_GaussCoil import Poly_GaussCoil
508        self.shape_indep_list.append(Poly_GaussCoil)
509        self.model_name_list.append(Poly_GaussCoil.__name__)
510       
511        from sans.models.PolymerExclVolume import PolymerExclVolume
512        self.shape_indep_list.append(PolymerExclVolume)
513        self.model_name_list.append(PolymerExclVolume.__name__)
514       
515        from sans.models.PorodModel import PorodModel
516        self.shape_indep_list.append(PorodModel ) 
517        self.model_name_list.append(PorodModel.__name__)   
518       
519        from sans.models.RPA10Model import RPA10Model
520        self.shape_indep_list.append(RPA10Model)
521        self.multi_func_list.append(RPA10Model)
522       
523        from sans.models.TeubnerStreyModel import TeubnerStreyModel
524        self.shape_indep_list.append(TeubnerStreyModel )
525        self.model_name_list.append(TeubnerStreyModel.__name__)
526       
527        from sans.models.TwoLorentzianModel import TwoLorentzianModel
528        self.shape_indep_list.append(TwoLorentzianModel )
529        self.model_name_list.append(TwoLorentzianModel.__name__)
530       
531        from sans.models.TwoPowerLawModel import TwoPowerLawModel
532        self.shape_indep_list.append(TwoPowerLawModel )
533        self.model_name_list.append(TwoPowerLawModel.__name__)
534       
535        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
536        self.shape_indep_list.append(UnifiedPowerRgModel )
537        self.multi_func_list.append(UnifiedPowerRgModel)
538       
539        from sans.models.LineModel import LineModel
540        self.shape_indep_list.append(LineModel)
541        self.model_name_list.append(LineModel.__name__)
542       
543        from sans.models.ReflectivityModel import ReflectivityModel
544        self.multi_func_list.append(ReflectivityModel)
545       
546        from sans.models.ReflectivityIIModel import ReflectivityIIModel
547        self.multi_func_list.append(ReflectivityIIModel)
548   
549        #Looking for plugins
550        self.stored_plugins = self.findModels()
551        self.plugins = self.stored_plugins.values()
552        self.plugins.append(ReflectivityModel)
553        self.plugins.append(ReflectivityIIModel)
554        self._get_multifunc_models()
555       
556        return 0
557
558    def is_changed(self):
559        """
560        check the last time the plugin dir has changed and return true
561         is the directory was modified else return false
562        """
563        is_modified = False
564        plugin_dir = find_plugins_dir()
565        if os.path.isdir(plugin_dir):
566            temp =  os.path.getmtime(plugin_dir)
567            if  self.last_time_dir_modified != temp:
568                is_modified = True
569                self.last_time_dir_modified = temp
570       
571        return is_modified
572   
573    def update(self):
574        """
575        return a dictionary of model if
576        new models were added else return empty dictionary
577        """
578        new_plugins = self.findModels()
579        if len(new_plugins) > 0:
580            for name, plug in  new_plugins.iteritems():
581                if name not in self.stored_plugins.keys():
582                    self.stored_plugins[name] = plug
583                    self.plugins.append(plug)
584            self.model_combobox.set_list("Customized Models", self.plugins)
585            return self.model_combobox.get_list()
586        else:
587            return {}
588   
589    def pulgins_reset(self):
590        """
591        return a dictionary of model
592        """
593        self.plugins = []
594        new_plugins = _findModels(dir)
595        for name, plug in  new_plugins.iteritems():
596            for stored_name, stored_plug in self.stored_plugins.iteritems():
597                if name == stored_name:
598                    del self.stored_plugins[name]
599                    break
600            self.stored_plugins[name] = plug
601            self.plugins.append(plug)
602        from sans.models.ReflectivityModel import ReflectivityModel
603        from sans.models.ReflectivityIIModel import ReflectivityIIModel
604        self.plugins.append(ReflectivityModel)
605        self.plugins.append(ReflectivityIIModel)
606        self.model_combobox.reset_list("Customized Models", self.plugins)
607        return self.model_combobox.get_list()
608       
609    def populate_menu(self, modelmenu, event_owner):
610        """
611        Populate a menu with our models
612       
613        :param id: first menu event ID to use when binding the menu events
614        :param modelmenu: wx.Menu object to populate
615        :param event_owner: wx object to bind the menu events to
616       
617        :return: the next free event ID following the new menu events
618       
619        """
620        ## Fill model lists
621        self._getModelList()
622        ## store reference to model menu of guiframe
623        self.modelmenu = modelmenu
624        ## guiframe reference
625        self.event_owner = event_owner
626       
627        shape_submenu = wx.Menu()
628        shape_indep_submenu = wx.Menu()
629        structure_factor = wx.Menu()
630        added_models = wx.Menu()
631        multip_models = wx.Menu()
632        ## create menu with shape
633        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
634                         list1=self.shape_list)
635       
636        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
637                                    "List of shape-independent models"],
638                         list1=self.shape_indep_list )
639       
640        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
641                                          "List of Structure factors models" ],
642                                list1=self.struct_list)
643       
644        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
645                                            "List of additional models"],
646                                 list1=self.plugins)
647       
648        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
649                                  "mulplication of 2 models"],
650                                   list1=self.multiplication_factor ,
651                                   list2= self.struct_list)
652        return 0
653   
654    def _fill_plugin_menu(self, menuinfo, list1):
655        """
656        fill the plugin menu with costumized models
657        """
658        if len(list1)==0:
659            id = wx.NewId() 
660            msg= "No model available check plugins.log for errors to fix problem"
661            menuinfo[1].Append(int(id),"Empty",msg)
662        self._fill_simple_menu( menuinfo,list1)
663       
664    def _fill_simple_menu(self, menuinfo, list1):
665        """
666        Fill the menu with list item
667       
668        :param modelmenu: the menu to fill
669        :param menuinfo: submenu item for the first column of this modelmenu
670                         with info.Should be a list :
671                         [name(string) , menu(wx.menu), help(string)]
672        :param list1: contains item (form factor )to fill modelmenu second column
673       
674        """
675        if len(list1)>0:
676            self.model_combobox.set_list(menuinfo[0],list1)
677           
678            for item in list1:
679                try:
680                    id = wx.NewId() 
681                    struct_factor=item()
682                    struct_name = struct_factor.__class__.__name__
683                    if hasattr(struct_factor, "name"):
684                        struct_name = struct_factor.name
685                       
686                    menuinfo[1].Append(int(id),struct_name,struct_name)
687                    if not  item in self.struct_factor_dict.itervalues():
688                        self.struct_factor_dict[str(id)]= item
689                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
690                except:
691                    msg= "Error Occured: %s"%sys.exc_value
692                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
693               
694        id = wx.NewId()         
695        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
696       
697    def _fill_menu(self, menuinfo, list1, list2):
698        """
699        Fill the menu with list item
700       
701        :param menuinfo: submenu item for the first column of this modelmenu
702                         with info.Should be a list :
703                         [name(string) , menu(wx.menu), help(string)]
704        :param list1: contains item (form factor )to fill modelmenu second column
705        :param list2: contains item (Structure factor )to fill modelmenu
706                third column
707               
708        """
709        if len(list1)>0:
710            self.model_combobox.set_list(menuinfo[0],list1)
711           
712            for item in list1:   
713                form_factor= item()
714                form_name = form_factor.__class__.__name__
715                if hasattr(form_factor, "name"):
716                    form_name = form_factor.name
717                ### store form factor to return to other users   
718                newmenu= wx.Menu()
719                if len(list2)>0:
720                    for model  in list2:
721                        id = wx.NewId()
722                        struct_factor = model()
723                        name = struct_factor.__class__.__name__
724                        if hasattr(struct_factor, "name"):
725                            name = struct_factor.name
726                        newmenu.Append(id,name, name)
727                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
728                        ## save form_fact and struct_fact
729                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
730                       
731                form_id= wx.NewId()   
732                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
733        id=wx.NewId()
734        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
735       
736    def _on_model(self, evt):
737        """
738        React to a model menu event
739       
740        :param event: wx menu event
741       
742        """
743        if int(evt.GetId()) in self.form_factor_dict.keys():
744            from sans.models.MultiplicationModel import MultiplicationModel
745            model1, model2 = self.form_factor_dict[int(evt.GetId())]
746            model = MultiplicationModel(model1, model2)   
747        else:
748            model= self.struct_factor_dict[str(evt.GetId())]()
749        evt = ModelEvent(model=model)
750        wx.PostEvent(self.event_owner, evt)
751       
752    def _get_multifunc_models(self):
753        """
754        Get the multifunctional models
755        """
756        for item in self.plugins:
757            try:
758                # check the multiplicity if any
759                if item.multiplicity_info[0] > 1:
760                    self.multi_func_list.append(item)
761            except:
762                # pass to other items
763                pass
764                   
765    def get_model_list(self):   
766        """
767        return dictionary of models for fitpanel use
768       
769        """
770        self.model_combobox.set_list("Shapes", self.shape_list)
771        self.model_combobox.set_list("Shape-Independent", self.shape_indep_list)
772        self.model_combobox.set_list("Structure Factors", self.struct_list)
773        self.model_combobox.set_list("Customized Models", self.plugins)
774        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
775        self.model_combobox.set_list("multiplication", self.multiplication_factor)
776        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
777        return self.model_combobox.get_list()
778   
779    def get_model_name_list(self):
780        """
781        return regular model name list
782        """
783        return self.model_name_list
784 
785       
786class ModelManager(object):
787    """
788    implement model
789    """
790    __modelmanager = ModelManagerBase()
791   
792    def findModels(self):
793        return self.__modelmanager.findModels()
794   
795    def _getModelList(self):
796        return self.__modelmanager._getModelList()
797   
798    def is_changed(self):
799        return self.__modelmanager.is_changed()
800   
801    def update(self):
802        return self.__modelmanager.update()
803   
804    def pulgins_reset(self):
805        return self.__modelmanager.pulgins_reset()
806   
807    def populate_menu(self, modelmenu, event_owner):
808        return self.__modelmanager.populate_menu(modelmenu, event_owner)
809   
810    def _on_model(self, evt):
811        return self.__modelmanager._on_model(evt)
812   
813    def _get_multifunc_models(self):
814        return self.__modelmanager._get_multifunc_models()
815   
816    def get_model_list(self): 
817        return self.__modelmanager.get_model_list()
818   
819    def get_model_name_list(self):
820        return self.__modelmanager.get_model_name_list()
821   
822   
823 
Note: See TracBrowser for help on using the repository browser.