source: sasview/src/sas/perspectives/fitting/models.py @ 0e4e554

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 0e4e554 was 0e4e554, checked in by ajj, 9 years ago

start switching to sasmodels including dispersion

  • Property mode set to 100644
File size: 49.8 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        try:
316            # from sas.models.SphereModel import SphereModel
317            from sasmodels.models import sphere
318            SphereModel = make_class(sphere, dtype='single')
319            self.model_dictionary[SphereModel.__name__] = SphereModel
320            #        self.shape_list.append(SphereModel)
321            self.multiplication_factor.append(SphereModel)
322            self.model_name_list.append(SphereModel.__name__)
323        except:
324            pass
325
326        try:
327            from sas.models.BinaryHSModel import BinaryHSModel
328            self.model_dictionary[BinaryHSModel.__name__] = BinaryHSModel
329            #        self.shape_list.append(BinaryHSModel)
330            self.model_name_list.append(BinaryHSModel.__name__)
331        except:
332            pass
333
334        try:
335            from sas.models.FuzzySphereModel import FuzzySphereModel
336            self.model_dictionary[FuzzySphereModel.__name__] = FuzzySphereModel
337            #        self.shape_list.append(FuzzySphereModel)
338            self.multiplication_factor.append(FuzzySphereModel)
339            self.model_name_list.append(FuzzySphereModel.__name__)
340        except:
341            pass
342
343        try:
344            from sas.models.RaspBerryModel import RaspBerryModel
345            self.model_dictionary[RaspBerryModel.__name__] = RaspBerryModel
346            #        self.shape_list.append(RaspBerryModel)
347            self.model_name_list.append(RaspBerryModel.__name__)
348        except:
349            pass
350
351        try:
352            from sas.models.CoreShellModel import CoreShellModel
353
354            self.model_dictionary[CoreShellModel.__name__] = CoreShellModel
355            #        self.shape_list.append(CoreShellModel)
356            self.multiplication_factor.append(CoreShellModel)
357            self.model_name_list.append(CoreShellModel.__name__)
358        except:
359            pass
360
361        try:
362            from sas.models.Core2ndMomentModel import Core2ndMomentModel
363            self.model_dictionary[Core2ndMomentModel.__name__] = Core2ndMomentModel
364            #        self.shape_list.append(Core2ndMomentModel)
365            self.model_name_list.append(Core2ndMomentModel.__name__)
366        except:
367            pass
368
369        try:
370            from sas.models.CoreMultiShellModel import CoreMultiShellModel
371            self.model_dictionary[CoreMultiShellModel.__name__] = CoreMultiShellModel
372            #        self.shape_list.append(CoreMultiShellModel)
373            self.multiplication_factor.append(CoreMultiShellModel)
374            self.multi_func_list.append(CoreMultiShellModel)
375        except:
376            pass
377
378        try:
379            from sas.models.VesicleModel import VesicleModel
380            self.model_dictionary[VesicleModel.__name__] = VesicleModel
381            #        self.shape_list.append(VesicleModel)
382            self.multiplication_factor.append(VesicleModel)
383            self.model_name_list.append(VesicleModel.__name__)
384        except:
385            pass
386
387        try:
388            from sas.models.MultiShellModel import MultiShellModel
389            self.model_dictionary[MultiShellModel.__name__] = MultiShellModel
390            #        self.shape_list.append(MultiShellModel)
391            self.multiplication_factor.append(MultiShellModel)
392            self.model_name_list.append(MultiShellModel.__name__)
393        except:
394            pass
395
396        try:
397            from sas.models.OnionExpShellModel import OnionExpShellModel
398            self.model_dictionary[OnionExpShellModel.__name__] = OnionExpShellModel
399            #        self.shape_list.append(OnionExpShellModel)
400            self.multiplication_factor.append(OnionExpShellModel)
401            self.multi_func_list.append(OnionExpShellModel)
402        except:
403            pass
404
405        try:
406            from sas.models.SphericalSLDModel import SphericalSLDModel
407
408            self.model_dictionary[SphericalSLDModel.__name__] = SphericalSLDModel
409            #        self.shape_list.append(SphericalSLDModel)
410            self.multiplication_factor.append(SphericalSLDModel)
411            self.multi_func_list.append(SphericalSLDModel)
412        except:
413            pass
414
415        try:
416            from sas.models.LinearPearlsModel import LinearPearlsModel
417
418            self.model_dictionary[LinearPearlsModel.__name__] = LinearPearlsModel
419            #        self.shape_list.append(LinearPearlsModel)
420            self.model_name_list.append(LinearPearlsModel.__name__)
421        except:
422            pass
423
424        try:
425            from sas.models.PearlNecklaceModel import PearlNecklaceModel
426
427            self.model_dictionary[PearlNecklaceModel.__name__] = PearlNecklaceModel
428            #        self.shape_list.append(PearlNecklaceModel)
429            self.model_name_list.append(PearlNecklaceModel.__name__)
430        except:
431            pass
432
433        try:
434            from sas.models.CylinderModel import CylinderModel
435
436            self.model_dictionary[CylinderModel.__name__] = CylinderModel
437            #        self.shape_list.append(CylinderModel)
438            self.multiplication_factor.append(CylinderModel)
439            self.model_name_list.append(CylinderModel.__name__)
440        except:
441            pass
442
443        try:
444            from sas.models.CoreShellCylinderModel import CoreShellCylinderModel
445
446            self.model_dictionary[CoreShellCylinderModel.__name__] = CoreShellCylinderModel
447            #        self.shape_list.append(CoreShellCylinderModel)
448            self.multiplication_factor.append(CoreShellCylinderModel)
449            self.model_name_list.append(CoreShellCylinderModel.__name__)
450        except:
451            pass
452
453        try:
454            from sas.models.CoreShellBicelleModel import CoreShellBicelleModel
455
456            self.model_dictionary[CoreShellBicelleModel.__name__] = CoreShellBicelleModel
457            #        self.shape_list.append(CoreShellBicelleModel)
458            self.multiplication_factor.append(CoreShellBicelleModel)
459            self.model_name_list.append(CoreShellBicelleModel.__name__)
460        except:
461            pass
462
463        try:
464            from sas.models.HollowCylinderModel import HollowCylinderModel
465
466            self.model_dictionary[HollowCylinderModel.__name__] = HollowCylinderModel
467            #        self.shape_list.append(HollowCylinderModel)
468            self.multiplication_factor.append(HollowCylinderModel)
469            self.model_name_list.append(HollowCylinderModel.__name__)
470        except:
471            pass
472
473        try:
474            from sas.models.FlexibleCylinderModel import FlexibleCylinderModel
475
476            self.model_dictionary[FlexibleCylinderModel.__name__] = FlexibleCylinderModel
477            #        self.shape_list.append(FlexibleCylinderModel)
478            self.model_name_list.append(FlexibleCylinderModel.__name__)
479        except:
480            pass
481
482        try:
483            from sas.models.FlexCylEllipXModel import FlexCylEllipXModel
484
485            self.model_dictionary[FlexCylEllipXModel.__name__] = FlexCylEllipXModel
486            #        self.shape_list.append(FlexCylEllipXModel)
487            self.model_name_list.append(FlexCylEllipXModel.__name__)
488        except:
489            pass
490
491        try:
492            from sas.models.StackedDisksModel import StackedDisksModel
493
494            self.model_dictionary[StackedDisksModel.__name__] = StackedDisksModel
495            #        self.shape_list.append(StackedDisksModel)
496            self.multiplication_factor.append(StackedDisksModel)
497            self.model_name_list.append(StackedDisksModel.__name__)
498        except:
499            pass
500
501        try:
502            from sas.models.ParallelepipedModel import ParallelepipedModel
503
504            self.model_dictionary[ParallelepipedModel.__name__] = ParallelepipedModel
505            #        self.shape_list.append(ParallelepipedModel)
506            self.multiplication_factor.append(ParallelepipedModel)
507            self.model_name_list.append(ParallelepipedModel.__name__)
508        except:
509            pass
510
511        try:
512            from sas.models.CSParallelepipedModel import CSParallelepipedModel
513
514            self.model_dictionary[CSParallelepipedModel.__name__] = CSParallelepipedModel
515            #        self.shape_list.append(CSParallelepipedModel)
516            self.multiplication_factor.append(CSParallelepipedModel)
517            self.model_name_list.append(CSParallelepipedModel.__name__)
518        except:
519            pass
520
521        try:
522            from sas.models.EllipticalCylinderModel import EllipticalCylinderModel
523
524            self.model_dictionary[EllipticalCylinderModel.__name__] = EllipticalCylinderModel
525            #        self.shape_list.append(EllipticalCylinderModel)
526            self.multiplication_factor.append(EllipticalCylinderModel)
527            self.model_name_list.append(EllipticalCylinderModel.__name__)
528        except:
529            pass
530
531        try:
532            from sas.models.CappedCylinderModel import CappedCylinderModel
533
534            self.model_dictionary[CappedCylinderModel.__name__] = CappedCylinderModel
535            #       self.shape_list.append(CappedCylinderModel)
536            self.model_name_list.append(CappedCylinderModel.__name__)
537        except:
538            pass
539
540        try:
541            from sas.models.EllipsoidModel import EllipsoidModel
542
543            self.model_dictionary[EllipsoidModel.__name__] = EllipsoidModel
544            #        self.shape_list.append(EllipsoidModel)
545            self.multiplication_factor.append(EllipsoidModel)
546            self.model_name_list.append(EllipsoidModel.__name__)
547        except:
548            pass
549
550        try:
551            from sas.models.CoreShellEllipsoidModel import CoreShellEllipsoidModel
552
553            self.model_dictionary[CoreShellEllipsoidModel.__name__] = CoreShellEllipsoidModel
554            #        self.shape_list.append(CoreShellEllipsoidModel)
555            self.multiplication_factor.append(CoreShellEllipsoidModel)
556            self.model_name_list.append(CoreShellEllipsoidModel.__name__)
557        except:
558            pass
559
560        try:
561            from sas.models.CoreShellEllipsoidXTModel import CoreShellEllipsoidXTModel
562
563            self.model_dictionary[CoreShellEllipsoidXTModel.__name__] = CoreShellEllipsoidXTModel
564            #        self.shape_list.append(CoreShellEllipsoidXTModel)
565            self.multiplication_factor.append(CoreShellEllipsoidXTModel)
566            self.model_name_list.append(CoreShellEllipsoidXTModel.__name__)
567        except:
568            pass
569
570        try:
571            from sas.models.TriaxialEllipsoidModel import TriaxialEllipsoidModel
572
573            self.model_dictionary[TriaxialEllipsoidModel.__name__] = TriaxialEllipsoidModel
574            #        self.shape_list.append(TriaxialEllipsoidModel)
575            self.multiplication_factor.append(TriaxialEllipsoidModel)
576            self.model_name_list.append(TriaxialEllipsoidModel.__name__)
577        except:
578            pass
579
580        try:
581            from sas.models.LamellarModel import LamellarModel
582
583            self.model_dictionary[LamellarModel.__name__] = LamellarModel
584            #        self.shape_list.append(LamellarModel)
585            self.model_name_list.append(LamellarModel.__name__)
586        except:
587            pass
588
589        try:
590            from sas.models.LamellarFFHGModel import LamellarFFHGModel
591
592            self.model_dictionary[LamellarFFHGModel.__name__] = LamellarFFHGModel
593            #        self.shape_list.append(LamellarFFHGModel)
594            self.model_name_list.append(LamellarFFHGModel.__name__)
595        except:
596            pass
597
598        try:
599            from sas.models.LamellarPSModel import LamellarPSModel
600
601            self.model_dictionary[LamellarPSModel.__name__] = LamellarPSModel
602            #        self.shape_list.append(LamellarPSModel)
603            self.model_name_list.append(LamellarPSModel.__name__)
604        except:
605            pass
606
607        try:
608            from sas.models.LamellarPSHGModel import LamellarPSHGModel
609
610            self.model_dictionary[LamellarPSHGModel.__name__] = LamellarPSHGModel
611            #        self.shape_list.append(LamellarPSHGModel)
612            self.model_name_list.append(LamellarPSHGModel.__name__)
613        except:
614            pass
615
616        try:
617            from sas.models.LamellarPCrystalModel import LamellarPCrystalModel
618
619            self.model_dictionary[LamellarPCrystalModel.__name__] = LamellarPCrystalModel
620            #        self.shape_list.append(LamellarPCrystalModel)
621            self.model_name_list.append(LamellarPCrystalModel.__name__)
622        except:
623            pass
624
625        try:
626            from sas.models.SCCrystalModel import SCCrystalModel
627
628            self.model_dictionary[SCCrystalModel.__name__] = SCCrystalModel
629            #        self.shape_list.append(SCCrystalModel)
630            self.model_name_list.append(SCCrystalModel.__name__)
631        except:
632            pass
633
634        try:
635            from sas.models.FCCrystalModel import FCCrystalModel
636
637            self.model_dictionary[FCCrystalModel.__name__] = FCCrystalModel
638            #        self.shape_list.append(FCCrystalModel)
639            self.model_name_list.append(FCCrystalModel.__name__)
640        except:
641            pass
642
643        try:
644            from sas.models.BCCrystalModel import BCCrystalModel
645
646            self.model_dictionary[BCCrystalModel.__name__] = BCCrystalModel
647            #        self.shape_list.append(BCCrystalModel)
648            self.model_name_list.append(BCCrystalModel.__name__)
649        except:
650            pass
651
652
653        ## Structure factor
654        try:
655            from sas.models.SquareWellStructure import SquareWellStructure
656
657            self.model_dictionary[SquareWellStructure.__name__] = SquareWellStructure
658            self.struct_list.append(SquareWellStructure)
659            self.model_name_list.append(SquareWellStructure.__name__)
660        except:
661            pass
662
663        try:
664            from sas.models.HardsphereStructure import HardsphereStructure
665
666            self.model_dictionary[HardsphereStructure.__name__] = HardsphereStructure
667            self.struct_list.append(HardsphereStructure)
668            self.model_name_list.append(HardsphereStructure.__name__)
669        except:
670            pass
671
672        try:
673            from sas.models.StickyHSStructure import StickyHSStructure
674
675            self.model_dictionary[StickyHSStructure.__name__] = StickyHSStructure
676            self.struct_list.append(StickyHSStructure)
677            self.model_name_list.append(StickyHSStructure.__name__)
678        except:
679            pass
680
681        try:
682            from sas.models.HayterMSAStructure import HayterMSAStructure
683
684            self.model_dictionary[HayterMSAStructure.__name__] = HayterMSAStructure
685            self.struct_list.append(HayterMSAStructure)
686            self.model_name_list.append(HayterMSAStructure.__name__)
687        except:
688            pass
689
690
691
692        ##shape-independent models
693        try:
694            from sas.models.PowerLawAbsModel import PowerLawAbsModel
695
696            self.model_dictionary[PowerLawAbsModel.__name__] = PowerLawAbsModel
697            #        self.shape_indep_list.append(PowerLawAbsModel)
698            self.model_name_list.append(PowerLawAbsModel.__name__)
699        except:
700            pass
701
702        try:
703            from sas.models.BEPolyelectrolyte import BEPolyelectrolyte
704
705            self.model_dictionary[BEPolyelectrolyte.__name__] = BEPolyelectrolyte
706            #        self.shape_indep_list.append(BEPolyelectrolyte)
707            self.model_name_list.append(BEPolyelectrolyte.__name__)
708            self.form_factor_dict[str(wx.NewId())] =  [SphereModel]
709        except:
710            pass
711
712        try:
713            from sas.models.BroadPeakModel import BroadPeakModel
714
715            self.model_dictionary[BroadPeakModel.__name__] = BroadPeakModel
716            #        self.shape_indep_list.append(BroadPeakModel)
717            self.model_name_list.append(BroadPeakModel.__name__)
718        except:
719            pass
720
721        try:
722            from sas.models.CorrLengthModel import CorrLengthModel
723
724            self.model_dictionary[CorrLengthModel.__name__] = CorrLengthModel
725            #        self.shape_indep_list.append(CorrLengthModel)
726            self.model_name_list.append(CorrLengthModel.__name__)
727        except:
728            pass
729
730        try:
731            from sas.models.DABModel import DABModel
732
733            self.model_dictionary[DABModel.__name__] = DABModel
734            #        self.shape_indep_list.append(DABModel)
735            self.model_name_list.append(DABModel.__name__)
736        except:
737            pass
738
739        try:
740            from sas.models.DebyeModel import DebyeModel
741
742            self.model_dictionary[DebyeModel.__name__] = DebyeModel
743            #        self.shape_indep_list.append(DebyeModel)
744            self.model_name_list.append(DebyeModel.__name__)
745        except:
746            pass
747
748        try:
749            from sas.models.FractalModel import FractalModel
750
751            self.model_dictionary[FractalModel.__name__] = FractalModel
752            #        self.shape_indep_list.append(FractalModel)
753            self.model_name_list.append(FractalModel.__name__)
754        except:
755            pass
756
757        try:
758            from sas.models.FractalCoreShellModel import FractalCoreShellModel
759
760            self.model_dictionary[FractalCoreShellModel.__name__] = FractalCoreShellModel
761            #        self.shape_indep_list.append(FractalCoreShellModel)
762            self.model_name_list.append(FractalCoreShellModel.__name__)
763        except:
764            pass
765
766        try:
767            from sas.models.GaussLorentzGelModel import GaussLorentzGelModel
768
769            self.model_dictionary[GaussLorentzGelModel.__name__] = GaussLorentzGelModel
770            #        self.shape_indep_list.append(GaussLorentzGelModel)
771            self.model_name_list.append(GaussLorentzGelModel.__name__)
772        except:
773            pass
774
775        try:
776            from sas.models.GuinierModel import GuinierModel
777
778            self.model_dictionary[GuinierModel.__name__] = GuinierModel
779            #        self.shape_indep_list.append(GuinierModel)
780            self.model_name_list.append(GuinierModel.__name__)
781        except:
782            pass
783
784        try:
785            from sas.models.GuinierPorodModel import GuinierPorodModel
786
787            self.model_dictionary[GuinierPorodModel.__name__] = GuinierPorodModel
788            #        self.shape_indep_list.append(GuinierPorodModel)
789            self.model_name_list.append(GuinierPorodModel.__name__)
790        except:
791            pass
792
793        try:
794            from sas.models.LorentzModel import LorentzModel
795
796            self.model_dictionary[LorentzModel.__name__] = LorentzModel
797            #        self.shape_indep_list.append(LorentzModel)
798            self.model_name_list.append(LorentzModel.__name__)
799        except:
800            pass
801
802        try:
803            from sas.models.MassFractalModel import MassFractalModel
804
805            self.model_dictionary[MassFractalModel.__name__] = MassFractalModel
806            #        self.shape_indep_list.append(MassFractalModel)
807            self.model_name_list.append(MassFractalModel.__name__)
808        except:
809            pass
810
811        try:
812            from sas.models.MassSurfaceFractal import MassSurfaceFractal
813
814            self.model_dictionary[MassSurfaceFractal.__name__] = MassSurfaceFractal
815            #        self.shape_indep_list.append(MassSurfaceFractal)
816            self.model_name_list.append(MassSurfaceFractal.__name__)
817        except:
818            pass
819
820        try:
821            from sas.models.PeakGaussModel import PeakGaussModel
822
823            self.model_dictionary[PeakGaussModel.__name__] = PeakGaussModel
824            #        self.shape_indep_list.append(PeakGaussModel)
825            self.model_name_list.append(PeakGaussModel.__name__)
826        except:
827            pass
828
829        try:
830            from sas.models.PeakLorentzModel import PeakLorentzModel
831
832            self.model_dictionary[PeakLorentzModel.__name__] = PeakLorentzModel
833            #        self.shape_indep_list.append(PeakLorentzModel)
834            self.model_name_list.append(PeakLorentzModel.__name__)
835        except:
836            pass
837
838        try:
839            from sas.models.Poly_GaussCoil import Poly_GaussCoil
840
841            self.model_dictionary[Poly_GaussCoil.__name__] = Poly_GaussCoil
842            #        self.shape_indep_list.append(Poly_GaussCoil)
843            self.model_name_list.append(Poly_GaussCoil.__name__)
844        except:
845            pass
846
847        try:
848            from sas.models.PolymerExclVolume import PolymerExclVolume
849
850            self.model_dictionary[PolymerExclVolume.__name__] = PolymerExclVolume
851            #        self.shape_indep_list.append(PolymerExclVolume)
852            self.model_name_list.append(PolymerExclVolume.__name__)
853        except:
854            pass
855
856        try:
857            from sas.models.PorodModel import PorodModel
858
859            self.model_dictionary[PorodModel.__name__] = PorodModel
860            #        self.shape_indep_list.append(PorodModel)
861            self.model_name_list.append(PorodModel.__name__)
862        except:
863            pass
864
865        try:
866            from sas.models.RPA10Model import RPA10Model
867
868            self.model_dictionary[RPA10Model.__name__] = RPA10Model
869            #        self.shape_indep_list.append(RPA10Model)
870            self.multi_func_list.append(RPA10Model)
871        except:
872            pass
873
874        try:
875            from sas.models.StarPolymer import StarPolymer
876
877            self.model_dictionary[StarPolymer.__name__] = StarPolymer
878            #        self.shape_indep_list.append(StarPolymer)
879            self.model_name_list.append(StarPolymer.__name__)
880        except:
881            pass
882
883        try:
884            from sas.models.SurfaceFractalModel import SurfaceFractalModel
885
886            self.model_dictionary[SurfaceFractalModel.__name__] = SurfaceFractalModel
887            #        self.shape_indep_list.append(SurfaceFractalModel)
888            self.model_name_list.append(SurfaceFractalModel.__name__)
889        except:
890            pass
891
892        try:
893            from sas.models.TeubnerStreyModel import TeubnerStreyModel
894
895            self.model_dictionary[TeubnerStreyModel.__name__] = TeubnerStreyModel
896            #        self.shape_indep_list.append(TeubnerStreyModel)
897            self.model_name_list.append(TeubnerStreyModel.__name__)
898        except:
899            pass
900
901        try:
902            from sas.models.TwoLorentzianModel import TwoLorentzianModel
903
904            self.model_dictionary[TwoLorentzianModel.__name__] = TwoLorentzianModel
905            #        self.shape_indep_list.append(TwoLorentzianModel)
906            self.model_name_list.append(TwoLorentzianModel.__name__)
907        except:
908            pass
909
910        try:
911            from sas.models.TwoPowerLawModel import TwoPowerLawModel
912
913            self.model_dictionary[TwoPowerLawModel.__name__] = TwoPowerLawModel
914            #        self.shape_indep_list.append(TwoPowerLawModel)
915            self.model_name_list.append(TwoPowerLawModel.__name__)
916        except:
917            pass
918
919        try:
920            from sas.models.UnifiedPowerRgModel import UnifiedPowerRgModel
921
922            self.model_dictionary[UnifiedPowerRgModel.__name__] = UnifiedPowerRgModel
923            #        self.shape_indep_list.append(UnifiedPowerRgModel)
924            self.multi_func_list.append(UnifiedPowerRgModel)
925        except:
926            pass
927
928        try:
929            from sas.models.LineModel import LineModel
930
931            self.model_dictionary[LineModel.__name__] = LineModel
932            #        self.shape_indep_list.append(LineModel)
933            self.model_name_list.append(LineModel.__name__)
934        except:
935            pass
936
937        try:
938            from sas.models.ReflectivityModel import ReflectivityModel
939
940            self.model_dictionary[ReflectivityModel.__name__] = ReflectivityModel
941            #        self.shape_indep_list.append(ReflectivityModel)
942            self.multi_func_list.append(ReflectivityModel)
943        except:
944            pass
945
946        try:
947            from sas.models.ReflectivityIIModel import ReflectivityIIModel
948
949            self.model_dictionary[ReflectivityIIModel.__name__] = ReflectivityIIModel
950            #        self.shape_indep_list.append(ReflectivityIIModel)
951            self.multi_func_list.append(ReflectivityIIModel)
952        except:
953            pass
954
955        try:
956            from sas.models.GelFitModel import GelFitModel
957
958            self.model_dictionary[GelFitModel.__name__] = GelFitModel
959            #        self.shape_indep_list.append(GelFitModel)
960            self.model_name_list.append(GelFitModel.__name__)
961        except:
962            pass
963
964        try:
965            from sas.models.PringlesModel import PringlesModel
966
967            self.model_dictionary[PringlesModel.__name__] = PringlesModel
968            #        self.shape_indep_list.append(PringlesModel)
969            self.model_name_list.append(PringlesModel.__name__)
970        except:
971            pass
972
973        try:
974            from sas.models.RectangularPrismModel import RectangularPrismModel
975
976            self.model_dictionary[RectangularPrismModel.__name__] = RectangularPrismModel
977            #        self.shape_list.append(RectangularPrismModel)
978            self.multiplication_factor.append(RectangularPrismModel)
979            self.model_name_list.append(RectangularPrismModel.__name__)
980        except:
981            pass
982
983        try:
984            from sas.models.RectangularHollowPrismInfThinWallsModel import RectangularHollowPrismInfThinWallsModel
985
986            self.model_dictionary[RectangularHollowPrismInfThinWallsModel.__name__] = RectangularHollowPrismInfThinWallsModel
987            #        self.shape_list.append(RectangularHollowPrismInfThinWallsModel)
988            self.multiplication_factor.append(RectangularHollowPrismInfThinWallsModel)
989            self.model_name_list.append(RectangularHollowPrismInfThinWallsModel.__name__)
990        except:
991            pass
992
993        try:
994            from sas.models.RectangularHollowPrismModel import RectangularHollowPrismModel
995
996            self.model_dictionary[RectangularHollowPrismModel.__name__] = RectangularHollowPrismModel
997            #        self.shape_list.append(RectangularHollowPrismModel)
998            self.multiplication_factor.append(RectangularHollowPrismModel)
999            self.model_name_list.append(RectangularHollowPrismModel.__name__)
1000        except:
1001            pass
1002
1003        try:
1004            from sas.models.MicelleSphCoreModel import MicelleSphCoreModel
1005
1006            self.model_dictionary[MicelleSphCoreModel.__name__] = MicelleSphCoreModel
1007            #        self.shape_list.append(MicelleSphCoreModel)
1008            self.multiplication_factor.append(MicelleSphCoreModel)
1009            self.model_name_list.append(MicelleSphCoreModel.__name__)
1010        except:
1011            pass
1012
1013
1014
1015        #from sas.models.FractalO_Z import FractalO_Z
1016        #self.model_dictionary[FractalO_Z.__name__] = FractalO_Z
1017        #self.shape_indep_list.append(FractalO_Z)
1018        #self.model_name_list.append(FractalO_Z.__name__)
1019   
1020        #Looking for plugins
1021        self.stored_plugins = self.findModels()
1022        self.plugins = self.stored_plugins.values()
1023        for name, plug in self.stored_plugins.iteritems():
1024            self.model_dictionary[name] = plug
1025           
1026        self._get_multifunc_models()
1027       
1028        return 0
1029
1030    def is_changed(self):
1031        """
1032        check the last time the plugin dir has changed and return true
1033         is the directory was modified else return false
1034        """
1035        is_modified = False
1036        plugin_dir = find_plugins_dir()
1037        if os.path.isdir(plugin_dir):
1038            temp = os.path.getmtime(plugin_dir)
1039            if  self.last_time_dir_modified != temp:
1040                is_modified = True
1041                self.last_time_dir_modified = temp
1042       
1043        return is_modified
1044   
1045    def update(self):
1046        """
1047        return a dictionary of model if
1048        new models were added else return empty dictionary
1049        """
1050        new_plugins = self.findModels()
1051        if len(new_plugins) > 0:
1052            for name, plug in  new_plugins.iteritems():
1053                if name not in self.stored_plugins.keys():
1054                    self.stored_plugins[name] = plug
1055                    self.plugins.append(plug)
1056                    self.model_dictionary[name] = plug
1057            self.model_combobox.set_list("Customized Models", self.plugins)
1058            return self.model_combobox.get_list()
1059        else:
1060            return {}
1061   
1062    def pulgins_reset(self):
1063        """
1064        return a dictionary of model
1065        """
1066        self.plugins = []
1067        new_plugins = _findModels(dir)
1068        for name, plug in  new_plugins.iteritems():
1069            for stored_name, stored_plug in self.stored_plugins.iteritems():
1070                if name == stored_name:
1071                    del self.stored_plugins[name]
1072                    del self.model_dictionary[name]
1073                    break
1074            self.stored_plugins[name] = plug
1075            self.plugins.append(plug)
1076            self.model_dictionary[name] = plug
1077
1078        self.model_combobox.reset_list("Customized Models", self.plugins)
1079        return self.model_combobox.get_list()
1080       
1081##   I believe the next four methods are for the old form factor GUI
1082##   where the dropdown showed a list of categories which then rolled out
1083##   in a second dropdown to the side. Some testing shows they indeed no longer
1084##   seem to be called.  If no problems are found during testing of release we
1085##   can remove this huge chunck of stuff.
1086##
1087##   -PDB  April 26, 2014
1088
1089#   def populate_menu(self, modelmenu, event_owner):
1090#       """
1091#       Populate a menu with our models
1092#       
1093#       :param id: first menu event ID to use when binding the menu events
1094#       :param modelmenu: wx.Menu object to populate
1095#       :param event_owner: wx object to bind the menu events to
1096#       
1097#       :return: the next free event ID following the new menu events
1098#       
1099#       """
1100#
1101        ## Fill model lists
1102#        self._getModelList()
1103        ## store reference to model menu of guiframe
1104#        self.modelmenu = modelmenu
1105        ## guiframe reference
1106#        self.event_owner = event_owner
1107       
1108#        shape_submenu = wx.Menu()
1109#        shape_indep_submenu = wx.Menu()
1110#        structure_factor = wx.Menu()
1111#        added_models = wx.Menu()
1112#        multip_models = wx.Menu()
1113        ## create menu with shape
1114#        self._fill_simple_menu(menuinfo=["Shapes",
1115#                                         shape_submenu,
1116#                                         " simple shape"],
1117#                         list1=self.shape_list)
1118       
1119#        self._fill_simple_menu(menuinfo=["Shape-Independent",
1120#                                         shape_indep_submenu,
1121#                                         "List of shape-independent models"],
1122#                         list1=self.shape_indep_list)
1123       
1124#        self._fill_simple_menu(menuinfo=["Structure Factors",
1125#                                         structure_factor,
1126#                                         "List of Structure factors models"],
1127#                                list1=self.struct_list)
1128       
1129#        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
1130#                                            "List of additional models"],
1131#                                 list1=self.plugins)
1132       
1133#        self._fill_menu(menuinfo=["P(Q)*S(Q)", multip_models,
1134#                                  "mulplication of 2 models"],
1135#                                   list1=self.multiplication_factor,
1136#                                   list2=self.struct_list)
1137#        return 0
1138   
1139#    def _fill_plugin_menu(self, menuinfo, list1):
1140#        """
1141#        fill the plugin menu with costumized models
1142#        """
1143#        print ("got to fill plugin menu")
1144#        if len(list1) == 0:
1145#            id = wx.NewId()
1146#            msg = "No model available check plugins.log for errors to fix problem"
1147#            menuinfo[1].Append(int(id), "Empty", msg)
1148#        self._fill_simple_menu(menuinfo, list1)
1149       
1150#   def _fill_simple_menu(self, menuinfo, list1):
1151#       """
1152#       Fill the menu with list item
1153#       
1154#       :param modelmenu: the menu to fill
1155#       :param menuinfo: submenu item for the first column of this modelmenu
1156#                        with info.Should be a list :
1157#                        [name(string) , menu(wx.menu), help(string)]
1158#       :param list1: contains item (form factor )to fill modelmenu second column
1159#       
1160#       """
1161#       if len(list1) > 0:
1162#           self.model_combobox.set_list(menuinfo[0], list1)
1163           
1164#            for item in list1:
1165#                try:
1166#                    id = wx.NewId()
1167#                    struct_factor = item()
1168#                    struct_name = struct_factor.__class__.__name__
1169#                    if hasattr(struct_factor, "name"):
1170#                        struct_name = struct_factor.name
1171#                       
1172#                    menuinfo[1].Append(int(id), struct_name, struct_name)
1173#                    if not  item in self.struct_factor_dict.itervalues():
1174#                        self.struct_factor_dict[str(id)] = item
1175#                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
1176#                except:
1177#                    msg = "Error Occured: %s" % sys.exc_value
1178#                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
1179#               
1180#        id = wx.NewId()
1181#        self.modelmenu.AppendMenu(id, menuinfo[0], menuinfo[1], menuinfo[2])
1182#       
1183#    def _fill_menu(self, menuinfo, list1, list2):
1184#        """
1185#        Fill the menu with list item
1186#       
1187#        :param menuinfo: submenu item for the first column of this modelmenu
1188#                         with info.Should be a list :
1189#                         [name(string) , menu(wx.menu), help(string)]
1190#        :param list1: contains item (form factor )to fill modelmenu second column
1191#        :param list2: contains item (Structure factor )to fill modelmenu
1192#                third column
1193#               
1194#        """
1195#        if len(list1) > 0:
1196#            self.model_combobox.set_list(menuinfo[0], list1)
1197#           
1198#            for item in list1:
1199#                form_factor = item()
1200#                form_name = form_factor.__class__.__name__
1201#                if hasattr(form_factor, "name"):
1202#                    form_name = form_factor.name
1203#                ### store form factor to return to other users
1204#                newmenu = wx.Menu()
1205#                if len(list2) > 0:
1206#                    for model  in list2:
1207#                        id = wx.NewId()
1208#                        struct_factor = model()
1209#                        name = struct_factor.__class__.__name__
1210#                        if hasattr(struct_factor, "name"):
1211#                            name = struct_factor.name
1212#                        newmenu.Append(id, name, name)
1213#                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
1214#                        ## save form_fact and struct_fact
1215#                        self.form_factor_dict[int(id)] = [form_factor,
1216#                                                          struct_factor]
1217#                       
1218#                form_id = wx.NewId()
1219#                menuinfo[1].AppendMenu(int(form_id), form_name,
1220#                                       newmenu, menuinfo[2])
1221#        id = wx.NewId()
1222#        self.modelmenu.AppendMenu(id, menuinfo[0], menuinfo[1], menuinfo[2])
1223       
1224    def _on_model(self, evt):
1225        """
1226        React to a model menu event
1227       
1228        :param event: wx menu event
1229       
1230        """
1231        if int(evt.GetId()) in self.form_factor_dict.keys():
1232            from sas.models.MultiplicationModel import MultiplicationModel
1233            self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel
1234            model1, model2 = self.form_factor_dict[int(evt.GetId())]
1235            model = MultiplicationModel(model1, model2)
1236        else:
1237            model = self.struct_factor_dict[str(evt.GetId())]()
1238       
1239        #TODO: investigate why the following two lines were left in the code
1240        #      even though the ModelEvent class doesn't exist
1241        #evt = ModelEvent(model=model)
1242        #wx.PostEvent(self.event_owner, evt)
1243       
1244    def _get_multifunc_models(self):
1245        """
1246        Get the multifunctional models
1247        """
1248        for item in self.plugins:
1249            try:
1250                # check the multiplicity if any
1251                if item.multiplicity_info[0] > 1:
1252                    self.multi_func_list.append(item)
1253            except:
1254                # pass to other items
1255                pass
1256                   
1257    def get_model_list(self):
1258        """
1259        return dictionary of models for fitpanel use
1260       
1261        """
1262        ## Model_list now only contains attribute lists not category list.
1263        ## Eventually this should be in one master list -- read in category
1264        ## list then pull those models that exist and get attributes then add
1265        ## to list ..and if model does not exist remove from list as now
1266        ## and update json file.
1267        ##
1268        ## -PDB   April 26, 2014
1269       
1270#        self.model_combobox.set_list("Shapes", self.shape_list)
1271#        self.model_combobox.set_list("Shape-Independent",
1272#                                     self.shape_indep_list)
1273        self.model_combobox.set_list("Structure Factors", self.struct_list)
1274        self.model_combobox.set_list("Customized Models", self.plugins)
1275        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
1276        self.model_combobox.set_list("multiplication",
1277                                     self.multiplication_factor)
1278        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
1279        return self.model_combobox.get_list()
1280   
1281    def get_model_name_list(self):
1282        """
1283        return regular model name list
1284        """
1285        return self.model_name_list
1286
1287    def get_model_dictionary(self):
1288        """
1289        return dictionary linking model names to objects
1290        """
1291        return self.model_dictionary
1292 
1293       
1294class ModelManager(object):
1295    """
1296    implement model
1297    """
1298    __modelmanager = ModelManagerBase()
1299    cat_model_list = [model_name for model_name \
1300                      in __modelmanager.model_dictionary.keys() \
1301                      if model_name not in __modelmanager.stored_plugins.keys()]
1302
1303    CategoryInstaller.check_install(model_list=cat_model_list)
1304    def findModels(self):
1305        return self.__modelmanager.findModels()
1306   
1307    def _getModelList(self):
1308        return self.__modelmanager._getModelList()
1309   
1310    def is_changed(self):
1311        return self.__modelmanager.is_changed()
1312   
1313    def update(self):
1314        return self.__modelmanager.update()
1315   
1316    def pulgins_reset(self):
1317        return self.__modelmanager.pulgins_reset()
1318   
1319    def populate_menu(self, modelmenu, event_owner):
1320        return self.__modelmanager.populate_menu(modelmenu, event_owner)
1321   
1322    def _on_model(self, evt):
1323        return self.__modelmanager._on_model(evt)
1324   
1325    def _get_multifunc_models(self):
1326        return self.__modelmanager._get_multifunc_models()
1327   
1328    def get_model_list(self):
1329        return self.__modelmanager.get_model_list()
1330   
1331    def get_model_name_list(self):
1332        return self.__modelmanager.get_model_name_list()
1333
1334    def get_model_dictionary(self):
1335        return self.__modelmanager.get_model_dictionary()
Note: See TracBrowser for help on using the repository browser.