source: sasview/src/sas/perspectives/fitting/models.py @ 40c5104

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 40c5104 was 40c5104, checked in by ajj, 10 years ago

updates to models.py to add models to correct lists

  • Property mode set to 100644
File size: 50.6 KB
Line 
1"""
2    Utilities to manage models
3"""
4import wx
5import imp
6import os
7import sys
8import math
9import os.path
10# Time is needed by the log method
11import time
12import logging
13import py_compile
14import shutil
15from sas.guiframe.events import StatusEvent
16# Explicitly import from the pluginmodel module so that py2exe
17# places it in the distribution. The Model1DPlugin class is used
18# as the base class of plug-in models.
19from sas.models.pluginmodel import Model1DPlugin
20from sas.models.BaseComponent import BaseComponent
21from sas.guiframe.CategoryInstaller import CategoryInstaller
22
23from sasmodels.sasview_model import make_class
24   
25PLUGIN_DIR = 'plugin_models'
26
27def get_model_python_path():
28    return os.path.dirname(__file__)
29
30
31def log(message):
32    """
33        Log a message in a file located in the user's home directory
34    """
35    dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR)
36    out = open(os.path.join(dir, "plugins.log"), 'a')
37    out.write("%10g%s\n" % (time.clock(), message))
38    out.close()
39
40
41def _check_plugin(model, name):
42    """
43    Do some checking before model adding plugins in the list
44   
45    :param model: class model to add into the plugin list
46    :param name:name of the module plugin
47   
48    :return model: model if valid model or None if not valid
49   
50    """
51    #Check if the plugin is of type Model1DPlugin
52    if not issubclass(model, Model1DPlugin):
53        msg = "Plugin %s must be of type Model1DPlugin \n" % str(name)
54        log(msg)
55        return None
56    if model.__name__ != "Model":
57        msg = "Plugin %s class name must be Model \n" % str(name)
58        log(msg)
59        return None
60    try:
61        new_instance = model()
62    except:
63        msg = "Plugin %s error in __init__ \n\t: %s %s\n" % (str(name),
64                                    str(sys.exc_type), sys.exc_value)
65        log(msg)
66        return None
67   
68    if hasattr(new_instance, "function"):
69        try:
70            value = new_instance.function()
71        except:
72            msg = "Plugin %s: error writing function \n\t :%s %s\n " % (str(name),
73                                    str(sys.exc_type), sys.exc_value)
74            log(msg)
75            return None
76    else:
77        msg = "Plugin  %s needs a method called function \n" % str(name)
78        log(msg)
79        return None
80    return model
81 
82 
83def find_plugins_dir():
84    """
85        Find path of the plugins directory.
86        The plugin directory is located in the user's home directory.
87    """
88    dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR)
89   
90    # If the plugin directory doesn't exist, create it
91    if not os.path.isdir(dir):
92        os.makedirs(dir)
93       
94    # Find paths needed
95    try:
96        # For source
97        if os.path.isdir(os.path.dirname(__file__)):
98            p_dir = os.path.join(os.path.dirname(__file__), PLUGIN_DIR)
99        else:
100            raise
101    except:
102        # Check for data path next to exe/zip file.
103        #Look for maximum n_dir up of the current dir to find plugins dir
104        n_dir = 12
105        p_dir = None
106        f_dir = os.path.join(os.path.dirname(__file__))
107        for i in range(n_dir):
108            if i > 1:
109                f_dir, _ = os.path.split(f_dir)
110            plugin_path = os.path.join(f_dir, PLUGIN_DIR)
111            if os.path.isdir(plugin_path):
112                p_dir = plugin_path
113                break
114        if not p_dir:
115            raise
116    # Place example user models as needed
117    if os.path.isdir(p_dir):
118        for file in os.listdir(p_dir):
119            file_path = os.path.join(p_dir, file)
120            if os.path.isfile(file_path):
121                if file.split(".")[-1] == 'py' and\
122                    file.split(".")[0] != '__init__':
123                    if not os.path.isfile(os.path.join(dir, file)):
124                        shutil.copy(file_path, dir)
125
126    return dir
127
128
129class ReportProblem:
130    def __nonzero__(self):
131        type, value, traceback = sys.exc_info()
132        if type is not None and issubclass(type, py_compile.PyCompileError):
133            print "Problem with", repr(value)
134            raise type, value, traceback
135        return 1
136   
137report_problem = ReportProblem()
138
139
140def compile_file(dir):
141    """
142    Compile a py file
143    """
144    try:
145        import compileall
146        compileall.compile_dir(dir=dir, ddir=dir, force=1,
147                               quiet=report_problem)
148    except:
149        type, value, traceback = sys.exc_info()
150        return value
151    return None
152
153
154def _findModels(dir):
155    """
156    """
157    # List of plugin objects
158    plugins = {}
159    # Go through files in plug-in directory
160    #always recompile the folder plugin
161    dir = find_plugins_dir()
162    if not os.path.isdir(dir):
163        msg = "SasView couldn't locate Model plugin folder."
164        msg += """ "%s" does not exist""" % dir
165        logging.warning(msg)
166        return plugins
167    else:
168        log("looking for models in: %s" % str(dir))
169        compile_file(dir)
170        logging.info("pluging model dir: %s\n" % str(dir))
171    try:
172        list = os.listdir(dir)
173        for item in list:
174            toks = os.path.splitext(os.path.basename(item))
175            if toks[1] == '.py' and not toks[0] == '__init__':
176                name = toks[0]
177           
178                path = [os.path.abspath(dir)]
179                file = None
180                try:
181                    (file, path, info) = imp.find_module(name, path)
182                    module = imp.load_module(name, file, item, info)
183                    if hasattr(module, "Model"):
184                        try:
185                            if _check_plugin(module.Model, name) != None:
186                                plugins[name] = module.Model
187                        except:
188                            msg = "Error accessing Model"
189                            msg += "in %s\n  %s %s\n" % (name,
190                                    str(sys.exc_type), sys.exc_value)
191                            log(msg)
192                except:
193                    msg = "Error accessing Model"
194                    msg += " in %s\n  %s %s \n" % (name,
195                                    str(sys.exc_type), sys.exc_value)
196                    log(msg)
197                finally:
198             
199                    if not file == None:
200                        file.close()
201    except:
202        # Don't deal with bad plug-in imports. Just skip.
203        msg = "Could not import model plugin: %s\n" % sys.exc_value
204        log(msg)
205        pass
206    return plugins
207
208
209class ModelList(object):
210    """
211    Contains dictionary of model and their type
212    """
213    def __init__(self):
214        """
215        """
216        self.mydict = {}
217       
218    def set_list(self, name, mylist):
219        """
220        :param name: the type of the list
221        :param mylist: the list to add
222       
223        """
224        if name not in self.mydict.keys():
225            self.reset_list(name, mylist)
226           
227    def reset_list(self, name, mylist):
228        """
229        :param name: the type of the list
230        :param mylist: the list to add
231        """
232        self.mydict[name] = mylist
233           
234    def get_list(self):
235        """
236        return all the list stored in a dictionary object
237        """
238        return self.mydict
239       
240       
241class ModelManagerBase:
242    """
243        Base class for the model manager
244    """
245    ## external dict for models
246    model_combobox = ModelList()
247    ## Dictionary of form factor models
248    form_factor_dict = {}
249    ## dictionary of structure factor models
250    struct_factor_dict = {}
251    ##list of shape models -- this is superseded by categories
252#    shape_list = []
253    ## shape independent model list-- this is superseded by categories
254#    shape_indep_list = []
255    ##list of structure factors
256    struct_list = []
257    ##list of model allowing multiplication by a structure factor
258    multiplication_factor = []
259    ##list of multifunctional shapes (i.e. that have user defined number of levels
260    multi_func_list = []
261    ## list of added models -- currently python models found in the plugin dir.
262    plugins = []
263    ## Event owner (guiframe)
264    event_owner = None
265    last_time_dir_modified = 0
266   
267    def __init__(self):
268        """
269        """
270        self.model_dictionary = {}
271        self.stored_plugins = {}
272        self._getModelList()
273       
274    def findModels(self):
275        """
276        find  plugin model in directory of plugin .recompile all file
277        in the directory if file were modified
278        """
279        temp = {}
280        if self.is_changed():
281            return  _findModels(dir)
282        logging.info("pluging model : %s\n" % str(temp))
283        return temp
284       
285    def _getModelList(self):
286        """
287        List of models we want to make available by default
288        for this application
289   
290        :return: the next free event ID following the new menu events
291       
292        """
293
294        ## NOTE: as of April 26, 2014, as part of first pass on fixing categories,
295        ## all the appends to shape_list or shape_independent_list are
296        ## commented out.  They should be possible to remove.  They are in
297        ## fact a "category" of model whereas the other list are actually
298        ## "attributes" of a model.  In other words is it a structure factor
299        ## that can be used against a form factor, is it a form factor that is
300        ## knows how to be multiplied by a structure factor, does it have user
301        ## defined number of parameters, etc.
302        ##
303        ## We hope this whole list will be superseded by the new C models
304        ## structure where each model will provide a method to interrogate it
305        ## about its "attributes" -- then this long list becomes a loop reading
306        ## each model in the category list to populate the "attribute"lists. 
307        ## We should also refactor the whole category vs attribute list
308        ## structure when doing this as now the attribute lists think they are
309        ## also category lists.
310        ##
311        ##   -PDB  April 26, 2014
312
313        # regular model names only
314        self.model_name_list = []
315
316        #Build list automagically from sasmodels package
317        import pkgutil
318        from importlib import import_module
319        import sasmodels.models
320        for importer,modname,ispkg in pkgutil.iter_modules(sasmodels.models.__path__):
321            if not ispkg:
322                module = import_module('.'+modname,'sasmodels.models')
323                self.model_dictionary[module.oldname] = make_class(module, dtype='single',namestyle='oldname')
324                self.model_name_list.append(module.oldname)
325
326
327        ### NASTY HACK - Comment out most of these lines as models are added to sasmodels.
328        ### Still need the lines that put models into multiplication etc
329
330        try:
331        #     # from sas.models.SphereModel import SphereModel
332        #     from sasmodels.models import sphere
333        #     SphereModel = make_class(sphere, dtype='single',namestyle='oldname')
334        #     self.model_dictionary[SphereModel.__name__] = SphereModel
335        #     #        self.shape_list.append(SphereModel)
336             self.multiplication_factor.append(SphereModel)
337        #     self.model_name_list.append(SphereModel.__name__)
338        except:
339             pass
340
341        try:
342            from sas.models.BinaryHSModel import BinaryHSModel
343            self.model_dictionary[BinaryHSModel.__name__] = BinaryHSModel
344            #        self.shape_list.append(BinaryHSModel)
345            self.model_name_list.append(BinaryHSModel.__name__)
346        except:
347            pass
348
349        try:
350            from sas.models.FuzzySphereModel import FuzzySphereModel
351            self.model_dictionary[FuzzySphereModel.__name__] = FuzzySphereModel
352            #        self.shape_list.append(FuzzySphereModel)
353            self.multiplication_factor.append(FuzzySphereModel)
354            self.model_name_list.append(FuzzySphereModel.__name__)
355        except:
356            pass
357
358        try:
359            from sas.models.RaspBerryModel import RaspBerryModel
360            self.model_dictionary[RaspBerryModel.__name__] = RaspBerryModel
361            #        self.shape_list.append(RaspBerryModel)
362            self.model_name_list.append(RaspBerryModel.__name__)
363        except:
364            pass
365
366        try:
367            from sas.models.CoreShellModel import CoreShellModel
368
369            self.model_dictionary[CoreShellModel.__name__] = CoreShellModel
370            #        self.shape_list.append(CoreShellModel)
371            self.multiplication_factor.append(CoreShellModel)
372            self.model_name_list.append(CoreShellModel.__name__)
373        except:
374            pass
375
376        try:
377            from sas.models.Core2ndMomentModel import Core2ndMomentModel
378            self.model_dictionary[Core2ndMomentModel.__name__] = Core2ndMomentModel
379            #        self.shape_list.append(Core2ndMomentModel)
380            self.model_name_list.append(Core2ndMomentModel.__name__)
381        except:
382            pass
383
384        try:
385            from sas.models.CoreMultiShellModel import CoreMultiShellModel
386            self.model_dictionary[CoreMultiShellModel.__name__] = CoreMultiShellModel
387            #        self.shape_list.append(CoreMultiShellModel)
388            self.multiplication_factor.append(CoreMultiShellModel)
389            self.multi_func_list.append(CoreMultiShellModel)
390        except:
391            pass
392
393        try:
394            from sas.models.VesicleModel import VesicleModel
395            self.model_dictionary[VesicleModel.__name__] = VesicleModel
396            #        self.shape_list.append(VesicleModel)
397            self.multiplication_factor.append(VesicleModel)
398            self.model_name_list.append(VesicleModel.__name__)
399        except:
400            pass
401
402        try:
403            from sas.models.MultiShellModel import MultiShellModel
404            self.model_dictionary[MultiShellModel.__name__] = MultiShellModel
405            #        self.shape_list.append(MultiShellModel)
406            self.multiplication_factor.append(MultiShellModel)
407            self.model_name_list.append(MultiShellModel.__name__)
408        except:
409            pass
410
411        try:
412            from sas.models.OnionExpShellModel import OnionExpShellModel
413            self.model_dictionary[OnionExpShellModel.__name__] = OnionExpShellModel
414            #        self.shape_list.append(OnionExpShellModel)
415            self.multiplication_factor.append(OnionExpShellModel)
416            self.multi_func_list.append(OnionExpShellModel)
417        except:
418            pass
419
420        try:
421            from sas.models.SphericalSLDModel import SphericalSLDModel
422
423            self.model_dictionary[SphericalSLDModel.__name__] = SphericalSLDModel
424            #        self.shape_list.append(SphericalSLDModel)
425            self.multiplication_factor.append(SphericalSLDModel)
426            self.multi_func_list.append(SphericalSLDModel)
427        except:
428            pass
429
430        try:
431            from sas.models.LinearPearlsModel import LinearPearlsModel
432
433            self.model_dictionary[LinearPearlsModel.__name__] = LinearPearlsModel
434            #        self.shape_list.append(LinearPearlsModel)
435            self.model_name_list.append(LinearPearlsModel.__name__)
436        except:
437            pass
438
439        try:
440            from sas.models.PearlNecklaceModel import PearlNecklaceModel
441
442            self.model_dictionary[PearlNecklaceModel.__name__] = PearlNecklaceModel
443            #        self.shape_list.append(PearlNecklaceModel)
444            self.model_name_list.append(PearlNecklaceModel.__name__)
445        except:
446            pass
447
448        try:
449            from sas.models.CylinderModel import CylinderModel
450
451            self.model_dictionary[CylinderModel.__name__] = CylinderModel
452            #        self.shape_list.append(CylinderModel)
453            self.multiplication_factor.append(CylinderModel)
454            self.model_name_list.append(CylinderModel.__name__)
455        except:
456            pass
457
458        try:
459            from sas.models.CoreShellCylinderModel import CoreShellCylinderModel
460
461            self.model_dictionary[CoreShellCylinderModel.__name__] = CoreShellCylinderModel
462            #        self.shape_list.append(CoreShellCylinderModel)
463            self.multiplication_factor.append(CoreShellCylinderModel)
464            self.model_name_list.append(CoreShellCylinderModel.__name__)
465        except:
466            pass
467
468        try:
469            from sas.models.CoreShellBicelleModel import CoreShellBicelleModel
470
471            self.model_dictionary[CoreShellBicelleModel.__name__] = CoreShellBicelleModel
472            #        self.shape_list.append(CoreShellBicelleModel)
473            self.multiplication_factor.append(CoreShellBicelleModel)
474            self.model_name_list.append(CoreShellBicelleModel.__name__)
475        except:
476            pass
477
478        try:
479            from sas.models.HollowCylinderModel import HollowCylinderModel
480
481            self.model_dictionary[HollowCylinderModel.__name__] = HollowCylinderModel
482            #        self.shape_list.append(HollowCylinderModel)
483            self.multiplication_factor.append(HollowCylinderModel)
484            self.model_name_list.append(HollowCylinderModel.__name__)
485        except:
486            pass
487
488        try:
489            from sas.models.FlexibleCylinderModel import FlexibleCylinderModel
490
491            self.model_dictionary[FlexibleCylinderModel.__name__] = FlexibleCylinderModel
492            #        self.shape_list.append(FlexibleCylinderModel)
493            self.model_name_list.append(FlexibleCylinderModel.__name__)
494        except:
495            pass
496
497        try:
498            from sas.models.FlexCylEllipXModel import FlexCylEllipXModel
499
500            self.model_dictionary[FlexCylEllipXModel.__name__] = FlexCylEllipXModel
501            #        self.shape_list.append(FlexCylEllipXModel)
502            self.model_name_list.append(FlexCylEllipXModel.__name__)
503        except:
504            pass
505
506        try:
507            from sas.models.StackedDisksModel import StackedDisksModel
508
509            self.model_dictionary[StackedDisksModel.__name__] = StackedDisksModel
510            #        self.shape_list.append(StackedDisksModel)
511            self.multiplication_factor.append(StackedDisksModel)
512            self.model_name_list.append(StackedDisksModel.__name__)
513        except:
514            pass
515
516        try:
517            from sas.models.ParallelepipedModel import ParallelepipedModel
518
519            self.model_dictionary[ParallelepipedModel.__name__] = ParallelepipedModel
520            #        self.shape_list.append(ParallelepipedModel)
521            self.multiplication_factor.append(ParallelepipedModel)
522            self.model_name_list.append(ParallelepipedModel.__name__)
523        except:
524            pass
525
526        try:
527            from sas.models.CSParallelepipedModel import CSParallelepipedModel
528
529            self.model_dictionary[CSParallelepipedModel.__name__] = CSParallelepipedModel
530            #        self.shape_list.append(CSParallelepipedModel)
531            self.multiplication_factor.append(CSParallelepipedModel)
532            self.model_name_list.append(CSParallelepipedModel.__name__)
533        except:
534            pass
535
536        try:
537            from sas.models.EllipticalCylinderModel import EllipticalCylinderModel
538
539            self.model_dictionary[EllipticalCylinderModel.__name__] = EllipticalCylinderModel
540            #        self.shape_list.append(EllipticalCylinderModel)
541            self.multiplication_factor.append(EllipticalCylinderModel)
542            self.model_name_list.append(EllipticalCylinderModel.__name__)
543        except:
544            pass
545
546        try:
547            from sas.models.CappedCylinderModel import CappedCylinderModel
548
549            self.model_dictionary[CappedCylinderModel.__name__] = CappedCylinderModel
550            #       self.shape_list.append(CappedCylinderModel)
551            self.model_name_list.append(CappedCylinderModel.__name__)
552        except:
553            pass
554
555        try:
556            from sas.models.EllipsoidModel import EllipsoidModel
557
558            self.model_dictionary[EllipsoidModel.__name__] = EllipsoidModel
559            #        self.shape_list.append(EllipsoidModel)
560            self.multiplication_factor.append(EllipsoidModel)
561            self.model_name_list.append(EllipsoidModel.__name__)
562        except:
563            pass
564
565        try:
566            from sas.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
567
568            self.model_dictionary[CoreShellEllipsoidModel.__name__] = CoreShellEllipsoidModel
569            #        self.shape_list.append(CoreShellEllipsoidModel)
570            self.multiplication_factor.append(CoreShellEllipsoidModel)
571            self.model_name_list.append(CoreShellEllipsoidModel.__name__)
572        except:
573            pass
574
575        try:
576            from sas.models.CoreShellEllipsoidXTModel import CoreShellEllipsoidXTModel
577
578            self.model_dictionary[CoreShellEllipsoidXTModel.__name__] = CoreShellEllipsoidXTModel
579            #        self.shape_list.append(CoreShellEllipsoidXTModel)
580            self.multiplication_factor.append(CoreShellEllipsoidXTModel)
581            self.model_name_list.append(CoreShellEllipsoidXTModel.__name__)
582        except:
583            pass
584
585        try:
586            from sas.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
587
588            self.model_dictionary[TriaxialEllipsoidModel.__name__] = TriaxialEllipsoidModel
589            #        self.shape_list.append(TriaxialEllipsoidModel)
590            self.multiplication_factor.append(TriaxialEllipsoidModel)
591            self.model_name_list.append(TriaxialEllipsoidModel.__name__)
592        except:
593            pass
594
595        try:
596            from sas.models.LamellarModel import LamellarModel
597
598            self.model_dictionary[LamellarModel.__name__] = LamellarModel
599            #        self.shape_list.append(LamellarModel)
600            self.model_name_list.append(LamellarModel.__name__)
601        except:
602            pass
603
604        try:
605            from sas.models.LamellarFFHGModel import LamellarFFHGModel
606
607            self.model_dictionary[LamellarFFHGModel.__name__] = LamellarFFHGModel
608            #        self.shape_list.append(LamellarFFHGModel)
609            self.model_name_list.append(LamellarFFHGModel.__name__)
610        except:
611            pass
612
613        try:
614            from sas.models.LamellarPSModel import LamellarPSModel
615
616            self.model_dictionary[LamellarPSModel.__name__] = LamellarPSModel
617            #        self.shape_list.append(LamellarPSModel)
618            self.model_name_list.append(LamellarPSModel.__name__)
619        except:
620            pass
621
622        try:
623            from sas.models.LamellarPSHGModel import LamellarPSHGModel
624
625            self.model_dictionary[LamellarPSHGModel.__name__] = LamellarPSHGModel
626            #        self.shape_list.append(LamellarPSHGModel)
627            self.model_name_list.append(LamellarPSHGModel.__name__)
628        except:
629            pass
630
631        try:
632            from sas.models.LamellarPCrystalModel import LamellarPCrystalModel
633
634            self.model_dictionary[LamellarPCrystalModel.__name__] = LamellarPCrystalModel
635            #        self.shape_list.append(LamellarPCrystalModel)
636            self.model_name_list.append(LamellarPCrystalModel.__name__)
637        except:
638            pass
639
640        try:
641            from sas.models.SCCrystalModel import SCCrystalModel
642
643            self.model_dictionary[SCCrystalModel.__name__] = SCCrystalModel
644            #        self.shape_list.append(SCCrystalModel)
645            self.model_name_list.append(SCCrystalModel.__name__)
646        except:
647            pass
648
649        try:
650            from sas.models.FCCrystalModel import FCCrystalModel
651
652            self.model_dictionary[FCCrystalModel.__name__] = FCCrystalModel
653            #        self.shape_list.append(FCCrystalModel)
654            self.model_name_list.append(FCCrystalModel.__name__)
655        except:
656            pass
657
658        try:
659            from sas.models.BCCrystalModel import BCCrystalModel
660
661            self.model_dictionary[BCCrystalModel.__name__] = BCCrystalModel
662            #        self.shape_list.append(BCCrystalModel)
663            self.model_name_list.append(BCCrystalModel.__name__)
664        except:
665            pass
666
667
668        ## Structure factor
669        try:
670            from sas.models.SquareWellStructure import SquareWellStructure
671
672            self.model_dictionary[SquareWellStructure.__name__] = SquareWellStructure
673            self.struct_list.append(SquareWellStructure)
674            self.model_name_list.append(SquareWellStructure.__name__)
675        except:
676            pass
677
678        try:
679            from sas.models.HardsphereStructure import HardsphereStructure
680
681            self.model_dictionary[HardsphereStructure.__name__] = HardsphereStructure
682            self.struct_list.append(HardsphereStructure)
683            self.model_name_list.append(HardsphereStructure.__name__)
684        except:
685            pass
686
687        try:
688            from sas.models.StickyHSStructure import StickyHSStructure
689
690            self.model_dictionary[StickyHSStructure.__name__] = StickyHSStructure
691            self.struct_list.append(StickyHSStructure)
692            self.model_name_list.append(StickyHSStructure.__name__)
693        except:
694            pass
695
696        try:
697            from sas.models.HayterMSAStructure import HayterMSAStructure
698
699            self.model_dictionary[HayterMSAStructure.__name__] = HayterMSAStructure
700            self.struct_list.append(HayterMSAStructure)
701            self.model_name_list.append(HayterMSAStructure.__name__)
702        except:
703            pass
704
705
706
707        ##shape-independent models
708        try:
709            from sas.models.PowerLawAbsModel import PowerLawAbsModel
710
711            self.model_dictionary[PowerLawAbsModel.__name__] = PowerLawAbsModel
712            #        self.shape_indep_list.append(PowerLawAbsModel)
713            self.model_name_list.append(PowerLawAbsModel.__name__)
714        except:
715            pass
716
717        try:
718            from sas.models.BEPolyelectrolyte import BEPolyelectrolyte
719
720            self.model_dictionary[BEPolyelectrolyte.__name__] = BEPolyelectrolyte
721            #        self.shape_indep_list.append(BEPolyelectrolyte)
722            self.model_name_list.append(BEPolyelectrolyte.__name__)
723            self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
724        except:
725            pass
726
727        try:
728            from sas.models.BroadPeakModel import BroadPeakModel
729
730            self.model_dictionary[BroadPeakModel.__name__] = BroadPeakModel
731            #        self.shape_indep_list.append(BroadPeakModel)
732            self.model_name_list.append(BroadPeakModel.__name__)
733        except:
734            pass
735
736        try:
737            from sas.models.CorrLengthModel import CorrLengthModel
738
739            self.model_dictionary[CorrLengthModel.__name__] = CorrLengthModel
740            #        self.shape_indep_list.append(CorrLengthModel)
741            self.model_name_list.append(CorrLengthModel.__name__)
742        except:
743            pass
744
745        try:
746            from sas.models.DABModel import DABModel
747
748            self.model_dictionary[DABModel.__name__] = DABModel
749            #        self.shape_indep_list.append(DABModel)
750            self.model_name_list.append(DABModel.__name__)
751        except:
752            pass
753
754        try:
755            from sas.models.DebyeModel import DebyeModel
756
757            self.model_dictionary[DebyeModel.__name__] = DebyeModel
758            #        self.shape_indep_list.append(DebyeModel)
759            self.model_name_list.append(DebyeModel.__name__)
760        except:
761            pass
762
763        try:
764            from sas.models.FractalModel import FractalModel
765
766            self.model_dictionary[FractalModel.__name__] = FractalModel
767            #        self.shape_indep_list.append(FractalModel)
768            self.model_name_list.append(FractalModel.__name__)
769        except:
770            pass
771
772        try:
773            from sas.models.FractalCoreShellModel import FractalCoreShellModel
774
775            self.model_dictionary[FractalCoreShellModel.__name__] = FractalCoreShellModel
776            #        self.shape_indep_list.append(FractalCoreShellModel)
777            self.model_name_list.append(FractalCoreShellModel.__name__)
778        except:
779            pass
780
781        try:
782            from sas.models.GaussLorentzGelModel import GaussLorentzGelModel
783
784            self.model_dictionary[GaussLorentzGelModel.__name__] = GaussLorentzGelModel
785            #        self.shape_indep_list.append(GaussLorentzGelModel)
786            self.model_name_list.append(GaussLorentzGelModel.__name__)
787        except:
788            pass
789
790        try:
791            from sas.models.GuinierModel import GuinierModel
792
793            self.model_dictionary[GuinierModel.__name__] = GuinierModel
794            #        self.shape_indep_list.append(GuinierModel)
795            self.model_name_list.append(GuinierModel.__name__)
796        except:
797            pass
798
799        try:
800            from sas.models.GuinierPorodModel import GuinierPorodModel
801
802            self.model_dictionary[GuinierPorodModel.__name__] = GuinierPorodModel
803            #        self.shape_indep_list.append(GuinierPorodModel)
804            self.model_name_list.append(GuinierPorodModel.__name__)
805        except:
806            pass
807
808        try:
809            from sas.models.LorentzModel import LorentzModel
810
811            self.model_dictionary[LorentzModel.__name__] = LorentzModel
812            #        self.shape_indep_list.append(LorentzModel)
813            self.model_name_list.append(LorentzModel.__name__)
814        except:
815            pass
816
817        try:
818            from sas.models.MassFractalModel import MassFractalModel
819
820            self.model_dictionary[MassFractalModel.__name__] = MassFractalModel
821            #        self.shape_indep_list.append(MassFractalModel)
822            self.model_name_list.append(MassFractalModel.__name__)
823        except:
824            pass
825
826        try:
827            from sas.models.MassSurfaceFractal import MassSurfaceFractal
828
829            self.model_dictionary[MassSurfaceFractal.__name__] = MassSurfaceFractal
830            #        self.shape_indep_list.append(MassSurfaceFractal)
831            self.model_name_list.append(MassSurfaceFractal.__name__)
832        except:
833            pass
834
835        try:
836            from sas.models.PeakGaussModel import PeakGaussModel
837
838            self.model_dictionary[PeakGaussModel.__name__] = PeakGaussModel
839            #        self.shape_indep_list.append(PeakGaussModel)
840            self.model_name_list.append(PeakGaussModel.__name__)
841        except:
842            pass
843
844        try:
845            from sas.models.PeakLorentzModel import PeakLorentzModel
846
847            self.model_dictionary[PeakLorentzModel.__name__] = PeakLorentzModel
848            #        self.shape_indep_list.append(PeakLorentzModel)
849            self.model_name_list.append(PeakLorentzModel.__name__)
850        except:
851            pass
852
853        try:
854            from sas.models.Poly_GaussCoil import Poly_GaussCoil
855
856            self.model_dictionary[Poly_GaussCoil.__name__] = Poly_GaussCoil
857            #        self.shape_indep_list.append(Poly_GaussCoil)
858            self.model_name_list.append(Poly_GaussCoil.__name__)
859        except:
860            pass
861
862        try:
863            from sas.models.PolymerExclVolume import PolymerExclVolume
864
865            self.model_dictionary[PolymerExclVolume.__name__] = PolymerExclVolume
866            #        self.shape_indep_list.append(PolymerExclVolume)
867            self.model_name_list.append(PolymerExclVolume.__name__)
868        except:
869            pass
870
871        try:
872            from sas.models.PorodModel import PorodModel
873
874            self.model_dictionary[PorodModel.__name__] = PorodModel
875            #        self.shape_indep_list.append(PorodModel)
876            self.model_name_list.append(PorodModel.__name__)
877        except:
878            pass
879
880        try:
881            from sas.models.RPA10Model import RPA10Model
882
883            self.model_dictionary[RPA10Model.__name__] = RPA10Model
884            #        self.shape_indep_list.append(RPA10Model)
885            self.multi_func_list.append(RPA10Model)
886        except:
887            pass
888
889        try:
890            from sas.models.StarPolymer import StarPolymer
891
892            self.model_dictionary[StarPolymer.__name__] = StarPolymer
893            #        self.shape_indep_list.append(StarPolymer)
894            self.model_name_list.append(StarPolymer.__name__)
895        except:
896            pass
897
898        try:
899            from sas.models.SurfaceFractalModel import SurfaceFractalModel
900
901            self.model_dictionary[SurfaceFractalModel.__name__] = SurfaceFractalModel
902            #        self.shape_indep_list.append(SurfaceFractalModel)
903            self.model_name_list.append(SurfaceFractalModel.__name__)
904        except:
905            pass
906
907        try:
908            from sas.models.TeubnerStreyModel import TeubnerStreyModel
909
910            self.model_dictionary[TeubnerStreyModel.__name__] = TeubnerStreyModel
911            #        self.shape_indep_list.append(TeubnerStreyModel)
912            self.model_name_list.append(TeubnerStreyModel.__name__)
913        except:
914            pass
915
916        try:
917            from sas.models.TwoLorentzianModel import TwoLorentzianModel
918
919            self.model_dictionary[TwoLorentzianModel.__name__] = TwoLorentzianModel
920            #        self.shape_indep_list.append(TwoLorentzianModel)
921            self.model_name_list.append(TwoLorentzianModel.__name__)
922        except:
923            pass
924
925        try:
926            from sas.models.TwoPowerLawModel import TwoPowerLawModel
927
928            self.model_dictionary[TwoPowerLawModel.__name__] = TwoPowerLawModel
929            #        self.shape_indep_list.append(TwoPowerLawModel)
930            self.model_name_list.append(TwoPowerLawModel.__name__)
931        except:
932            pass
933
934        try:
935            from sas.models.UnifiedPowerRgModel import UnifiedPowerRgModel
936
937            self.model_dictionary[UnifiedPowerRgModel.__name__] = UnifiedPowerRgModel
938            #        self.shape_indep_list.append(UnifiedPowerRgModel)
939            self.multi_func_list.append(UnifiedPowerRgModel)
940        except:
941            pass
942
943        try:
944            from sas.models.LineModel import LineModel
945
946            self.model_dictionary[LineModel.__name__] = LineModel
947            #        self.shape_indep_list.append(LineModel)
948            self.model_name_list.append(LineModel.__name__)
949        except:
950            pass
951
952        try:
953            from sas.models.ReflectivityModel import ReflectivityModel
954
955            self.model_dictionary[ReflectivityModel.__name__] = ReflectivityModel
956            #        self.shape_indep_list.append(ReflectivityModel)
957            self.multi_func_list.append(ReflectivityModel)
958        except:
959            pass
960
961        try:
962            from sas.models.ReflectivityIIModel import ReflectivityIIModel
963
964            self.model_dictionary[ReflectivityIIModel.__name__] = ReflectivityIIModel
965            #        self.shape_indep_list.append(ReflectivityIIModel)
966            self.multi_func_list.append(ReflectivityIIModel)
967        except:
968            pass
969
970        try:
971            from sas.models.GelFitModel import GelFitModel
972
973            self.model_dictionary[GelFitModel.__name__] = GelFitModel
974            #        self.shape_indep_list.append(GelFitModel)
975            self.model_name_list.append(GelFitModel.__name__)
976        except:
977            pass
978
979        try:
980            from sas.models.PringlesModel import PringlesModel
981
982            self.model_dictionary[PringlesModel.__name__] = PringlesModel
983            #        self.shape_indep_list.append(PringlesModel)
984            self.model_name_list.append(PringlesModel.__name__)
985        except:
986            pass
987
988        try:
989            from sas.models.RectangularPrismModel import RectangularPrismModel
990
991            self.model_dictionary[RectangularPrismModel.__name__] = RectangularPrismModel
992            #        self.shape_list.append(RectangularPrismModel)
993            self.multiplication_factor.append(RectangularPrismModel)
994            self.model_name_list.append(RectangularPrismModel.__name__)
995        except:
996            pass
997
998        try:
999            from sas.models.RectangularHollowPrismInfThinWallsModel import RectangularHollowPrismInfThinWallsModel
1000
1001            self.model_dictionary[RectangularHollowPrismInfThinWallsModel.__name__] = RectangularHollowPrismInfThinWallsModel
1002            #        self.shape_list.append(RectangularHollowPrismInfThinWallsModel)
1003            self.multiplication_factor.append(RectangularHollowPrismInfThinWallsModel)
1004            self.model_name_list.append(RectangularHollowPrismInfThinWallsModel.__name__)
1005        except:
1006            pass
1007
1008        try:
1009            from sas.models.RectangularHollowPrismModel import RectangularHollowPrismModel
1010
1011            self.model_dictionary[RectangularHollowPrismModel.__name__] = RectangularHollowPrismModel
1012            #        self.shape_list.append(RectangularHollowPrismModel)
1013            self.multiplication_factor.append(RectangularHollowPrismModel)
1014            self.model_name_list.append(RectangularHollowPrismModel.__name__)
1015        except:
1016            pass
1017
1018        try:
1019            from sas.models.MicelleSphCoreModel import MicelleSphCoreModel
1020
1021            self.model_dictionary[MicelleSphCoreModel.__name__] = MicelleSphCoreModel
1022            #        self.shape_list.append(MicelleSphCoreModel)
1023            self.multiplication_factor.append(MicelleSphCoreModel)
1024            self.model_name_list.append(MicelleSphCoreModel.__name__)
1025        except:
1026            pass
1027
1028
1029
1030        #from sas.models.FractalO_Z import FractalO_Z
1031        #self.model_dictionary[FractalO_Z.__name__] = FractalO_Z
1032        #self.shape_indep_list.append(FractalO_Z)
1033        #self.model_name_list.append(FractalO_Z.__name__)
1034   
1035        #Looking for plugins
1036        self.stored_plugins = self.findModels()
1037        self.plugins = self.stored_plugins.values()
1038        for name, plug in self.stored_plugins.iteritems():
1039            self.model_dictionary[name] = plug
1040           
1041        self._get_multifunc_models()
1042       
1043        return 0
1044
1045    def is_changed(self):
1046        """
1047        check the last time the plugin dir has changed and return true
1048         is the directory was modified else return false
1049        """
1050        is_modified = False
1051        plugin_dir = find_plugins_dir()
1052        if os.path.isdir(plugin_dir):
1053            temp = os.path.getmtime(plugin_dir)
1054            if  self.last_time_dir_modified != temp:
1055                is_modified = True
1056                self.last_time_dir_modified = temp
1057       
1058        return is_modified
1059   
1060    def update(self):
1061        """
1062        return a dictionary of model if
1063        new models were added else return empty dictionary
1064        """
1065        new_plugins = self.findModels()
1066        if len(new_plugins) > 0:
1067            for name, plug in  new_plugins.iteritems():
1068                if name not in self.stored_plugins.keys():
1069                    self.stored_plugins[name] = plug
1070                    self.plugins.append(plug)
1071                    self.model_dictionary[name] = plug
1072            self.model_combobox.set_list("Customized Models", self.plugins)
1073            return self.model_combobox.get_list()
1074        else:
1075            return {}
1076   
1077    def pulgins_reset(self):
1078        """
1079        return a dictionary of model
1080        """
1081        self.plugins = []
1082        new_plugins = _findModels(dir)
1083        for name, plug in  new_plugins.iteritems():
1084            for stored_name, stored_plug in self.stored_plugins.iteritems():
1085                if name == stored_name:
1086                    del self.stored_plugins[name]
1087                    del self.model_dictionary[name]
1088                    break
1089            self.stored_plugins[name] = plug
1090            self.plugins.append(plug)
1091            self.model_dictionary[name] = plug
1092
1093        self.model_combobox.reset_list("Customized Models", self.plugins)
1094        return self.model_combobox.get_list()
1095       
1096##   I believe the next four methods are for the old form factor GUI
1097##   where the dropdown showed a list of categories which then rolled out
1098##   in a second dropdown to the side. Some testing shows they indeed no longer
1099##   seem to be called.  If no problems are found during testing of release we
1100##   can remove this huge chunck of stuff.
1101##
1102##   -PDB  April 26, 2014
1103
1104#   def populate_menu(self, modelmenu, event_owner):
1105#       """
1106#       Populate a menu with our models
1107#       
1108#       :param id: first menu event ID to use when binding the menu events
1109#       :param modelmenu: wx.Menu object to populate
1110#       :param event_owner: wx object to bind the menu events to
1111#       
1112#       :return: the next free event ID following the new menu events
1113#       
1114#       """
1115#
1116        ## Fill model lists
1117#        self._getModelList()
1118        ## store reference to model menu of guiframe
1119#        self.modelmenu = modelmenu
1120        ## guiframe reference
1121#        self.event_owner = event_owner
1122       
1123#        shape_submenu = wx.Menu()
1124#        shape_indep_submenu = wx.Menu()
1125#        structure_factor = wx.Menu()
1126#        added_models = wx.Menu()
1127#        multip_models = wx.Menu()
1128        ## create menu with shape
1129#        self._fill_simple_menu(menuinfo=["Shapes",
1130#                                         shape_submenu,
1131#                                         " simple shape"],
1132#                         list1=self.shape_list)
1133       
1134#        self._fill_simple_menu(menuinfo=["Shape-Independent",
1135#                                         shape_indep_submenu,
1136#                                         "List of shape-independent models"],
1137#                         list1=self.shape_indep_list)
1138       
1139#        self._fill_simple_menu(menuinfo=["Structure Factors",
1140#                                         structure_factor,
1141#                                         "List of Structure factors models"],
1142#                                list1=self.struct_list)
1143       
1144#        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
1145#                                            "List of additional models"],
1146#                                 list1=self.plugins)
1147       
1148#        self._fill_menu(menuinfo=["P(Q)*S(Q)", multip_models,
1149#                                  "mulplication of 2 models"],
1150#                                   list1=self.multiplication_factor,
1151#                                   list2=self.struct_list)
1152#        return 0
1153   
1154#    def _fill_plugin_menu(self, menuinfo, list1):
1155#        """
1156#        fill the plugin menu with costumized models
1157#        """
1158#        print ("got to fill plugin menu")
1159#        if len(list1) == 0:
1160#            id = wx.NewId()
1161#            msg = "No model available check plugins.log for errors to fix problem"
1162#            menuinfo[1].Append(int(id), "Empty", msg)
1163#        self._fill_simple_menu(menuinfo, list1)
1164       
1165#   def _fill_simple_menu(self, menuinfo, list1):
1166#       """
1167#       Fill the menu with list item
1168#       
1169#       :param modelmenu: the menu to fill
1170#       :param menuinfo: submenu item for the first column of this modelmenu
1171#                        with info.Should be a list :
1172#                        [name(string) , menu(wx.menu), help(string)]
1173#       :param list1: contains item (form factor )to fill modelmenu second column
1174#       
1175#       """
1176#       if len(list1) > 0:
1177#           self.model_combobox.set_list(menuinfo[0], list1)
1178           
1179#            for item in list1:
1180#                try:
1181#                    id = wx.NewId()
1182#                    struct_factor = item()
1183#                    struct_name = struct_factor.__class__.__name__
1184#                    if hasattr(struct_factor, "name"):
1185#                        struct_name = struct_factor.name
1186#                       
1187#                    menuinfo[1].Append(int(id), struct_name, struct_name)
1188#                    if not  item in self.struct_factor_dict.itervalues():
1189#                        self.struct_factor_dict[str(id)] = item
1190#                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
1191#                except:
1192#                    msg = "Error Occured: %s" % sys.exc_value
1193#                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
1194#               
1195#        id = wx.NewId()
1196#        self.modelmenu.AppendMenu(id, menuinfo[0], menuinfo[1], menuinfo[2])
1197#       
1198#    def _fill_menu(self, menuinfo, list1, list2):
1199#        """
1200#        Fill the menu with list item
1201#       
1202#        :param menuinfo: submenu item for the first column of this modelmenu
1203#                         with info.Should be a list :
1204#                         [name(string) , menu(wx.menu), help(string)]
1205#        :param list1: contains item (form factor )to fill modelmenu second column
1206#        :param list2: contains item (Structure factor )to fill modelmenu
1207#                third column
1208#               
1209#        """
1210#        if len(list1) > 0:
1211#            self.model_combobox.set_list(menuinfo[0], list1)
1212#           
1213#            for item in list1:
1214#                form_factor = item()
1215#                form_name = form_factor.__class__.__name__
1216#                if hasattr(form_factor, "name"):
1217#                    form_name = form_factor.name
1218#                ### store form factor to return to other users
1219#                newmenu = wx.Menu()
1220#                if len(list2) > 0:
1221#                    for model  in list2:
1222#                        id = wx.NewId()
1223#                        struct_factor = model()
1224#                        name = struct_factor.__class__.__name__
1225#                        if hasattr(struct_factor, "name"):
1226#                            name = struct_factor.name
1227#                        newmenu.Append(id, name, name)
1228#                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
1229#                        ## save form_fact and struct_fact
1230#                        self.form_factor_dict[int(id)] = [form_factor,
1231#                                                          struct_factor]
1232#                       
1233#                form_id = wx.NewId()
1234#                menuinfo[1].AppendMenu(int(form_id), form_name,
1235#                                       newmenu, menuinfo[2])
1236#        id = wx.NewId()
1237#        self.modelmenu.AppendMenu(id, menuinfo[0], menuinfo[1], menuinfo[2])
1238       
1239    def _on_model(self, evt):
1240        """
1241        React to a model menu event
1242       
1243        :param event: wx menu event
1244       
1245        """
1246        if int(evt.GetId()) in self.form_factor_dict.keys():
1247            from sas.models.MultiplicationModel import MultiplicationModel
1248            self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel
1249            model1, model2 = self.form_factor_dict[int(evt.GetId())]
1250            model = MultiplicationModel(model1, model2)
1251        else:
1252            model = self.struct_factor_dict[str(evt.GetId())]()
1253       
1254        #TODO: investigate why the following two lines were left in the code
1255        #      even though the ModelEvent class doesn't exist
1256        #evt = ModelEvent(model=model)
1257        #wx.PostEvent(self.event_owner, evt)
1258       
1259    def _get_multifunc_models(self):
1260        """
1261        Get the multifunctional models
1262        """
1263        for item in self.plugins:
1264            try:
1265                # check the multiplicity if any
1266                if item.multiplicity_info[0] > 1:
1267                    self.multi_func_list.append(item)
1268            except:
1269                # pass to other items
1270                pass
1271                   
1272    def get_model_list(self):
1273        """
1274        return dictionary of models for fitpanel use
1275       
1276        """
1277        ## Model_list now only contains attribute lists not category list.
1278        ## Eventually this should be in one master list -- read in category
1279        ## list then pull those models that exist and get attributes then add
1280        ## to list ..and if model does not exist remove from list as now
1281        ## and update json file.
1282        ##
1283        ## -PDB   April 26, 2014
1284       
1285#        self.model_combobox.set_list("Shapes", self.shape_list)
1286#        self.model_combobox.set_list("Shape-Independent",
1287#                                     self.shape_indep_list)
1288        self.model_combobox.set_list("Structure Factors", self.struct_list)
1289        self.model_combobox.set_list("Customized Models", self.plugins)
1290        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
1291        self.model_combobox.set_list("multiplication",
1292                                     self.multiplication_factor)
1293        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
1294        return self.model_combobox.get_list()
1295   
1296    def get_model_name_list(self):
1297        """
1298        return regular model name list
1299        """
1300        return self.model_name_list
1301
1302    def get_model_dictionary(self):
1303        """
1304        return dictionary linking model names to objects
1305        """
1306        return self.model_dictionary
1307 
1308       
1309class ModelManager(object):
1310    """
1311    implement model
1312    """
1313    __modelmanager = ModelManagerBase()
1314    cat_model_list = [model_name for model_name \
1315                      in __modelmanager.model_dictionary.keys() \
1316                      if model_name not in __modelmanager.stored_plugins.keys()]
1317
1318    CategoryInstaller.check_install(model_list=cat_model_list)
1319    def findModels(self):
1320        return self.__modelmanager.findModels()
1321   
1322    def _getModelList(self):
1323        return self.__modelmanager._getModelList()
1324   
1325    def is_changed(self):
1326        return self.__modelmanager.is_changed()
1327   
1328    def update(self):
1329        return self.__modelmanager.update()
1330   
1331    def pulgins_reset(self):
1332        return self.__modelmanager.pulgins_reset()
1333   
1334    def populate_menu(self, modelmenu, event_owner):
1335        return self.__modelmanager.populate_menu(modelmenu, event_owner)
1336   
1337    def _on_model(self, evt):
1338        return self.__modelmanager._on_model(evt)
1339   
1340    def _get_multifunc_models(self):
1341        return self.__modelmanager._get_multifunc_models()
1342   
1343    def get_model_list(self):
1344        return self.__modelmanager.get_model_list()
1345   
1346    def get_model_name_list(self):
1347        return self.__modelmanager.get_model_name_list()
1348
1349    def get_model_dictionary(self):
1350        return self.__modelmanager.get_model_dictionary()
Note: See TracBrowser for help on using the repository browser.