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

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 cbe8c5c was 6f82ba1, checked in by ajj, 10 years ago

adding try-except to prepare for removing models

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