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

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

removed frataloz (same as masssurfacefractal) from fitting

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