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

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 2ee5c61 was 279e371, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Fixing code style problems

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