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

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 ef8d42f was 61184df, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

Fixing code style problems and bugs

  • 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       
[fb59ed9]486        #FractalModel (a c-model)is now being used instead of FractalAbsModel.
[ce07fa8]487        from sans.models.FractalModel import FractalModel
488        self.shape_indep_list.append(FractalModel )
[7c8d3093]489        self.model_name_list.append(FractalModel.__name__)
[bb18ef1]490       
[fb59ed9]491        from sans.models.FractalCoreShellModel import FractalCoreShellModel
492        self.shape_indep_list.append(FractalCoreShellModel )
[7c8d3093]493        self.model_name_list.append(FractalCoreShellModel.__name__)
[fb59ed9]494       
495        from sans.models.GaussLorentzGelModel import GaussLorentzGelModel
496        self.shape_indep_list.append(GaussLorentzGelModel) 
[7c8d3093]497        self.model_name_list.append(GaussLorentzGelModel.__name__)
[fb59ed9]498               
499        from sans.models.GuinierModel import GuinierModel
500        self.shape_indep_list.append(GuinierModel )
[7c8d3093]501        self.model_name_list.append(GuinierModel.__name__)
[fb59ed9]502       
503        from sans.models.GuinierPorodModel import GuinierPorodModel
504        self.shape_indep_list.append(GuinierPorodModel )
[7c8d3093]505        self.model_name_list.append(GuinierPorodModel.__name__)
[fb59ed9]506
[ce07fa8]507        from sans.models.LorentzModel import LorentzModel
508        self.shape_indep_list.append( LorentzModel) 
[7c8d3093]509        self.model_name_list.append(LorentzModel.__name__)
[51da9dc]510
511        from sans.models.MassFractalModel import MassFractalModel
512        self.shape_indep_list.append(MassFractalModel)
513        self.model_name_list.append(MassFractalModel.__name__)
514       
515        from sans.models.MassSurfaceFractal import MassSurfaceFractal
516        self.shape_indep_list.append(MassSurfaceFractal)
517        self.model_name_list.append(MassSurfaceFractal.__name__)
[442895f]518       
[cee6867]519        from sans.models.PeakGaussModel import PeakGaussModel
520        self.shape_indep_list.append(PeakGaussModel)
[7c8d3093]521        self.model_name_list.append(PeakGaussModel.__name__)
[cee6867]522       
523        from sans.models.PeakLorentzModel import PeakLorentzModel
524        self.shape_indep_list.append(PeakLorentzModel)
[7c8d3093]525        self.model_name_list.append( PeakLorentzModel.__name__)
[cee6867]526       
[ce07fa8]527        from sans.models.Poly_GaussCoil import Poly_GaussCoil
528        self.shape_indep_list.append(Poly_GaussCoil)
[7c8d3093]529        self.model_name_list.append(Poly_GaussCoil.__name__)
[fb59ed9]530       
531        from sans.models.PolymerExclVolume import PolymerExclVolume
532        self.shape_indep_list.append(PolymerExclVolume)
[7c8d3093]533        self.model_name_list.append(PolymerExclVolume.__name__)
[fb59ed9]534       
[ce07fa8]535        from sans.models.PorodModel import PorodModel
[7c8d3093]536        self.shape_indep_list.append(PorodModel ) 
537        self.model_name_list.append(PorodModel.__name__)   
[442895f]538       
[fb59ed9]539        from sans.models.RPA10Model import RPA10Model
540        self.shape_indep_list.append(RPA10Model)
541        self.multi_func_list.append(RPA10Model)
[51da9dc]542
543        from sans.models.SurfaceFractalModel import SurfaceFractalModel
544        self.shape_indep_list.append(SurfaceFractalModel)
545        self.model_name_list.append(SurfaceFractalModel.__name__)
[81bece4]546       
[442895f]547        from sans.models.TeubnerStreyModel import TeubnerStreyModel
[bb18ef1]548        self.shape_indep_list.append(TeubnerStreyModel )
[7c8d3093]549        self.model_name_list.append(TeubnerStreyModel.__name__)
[eddff027]550       
[fb59ed9]551        from sans.models.TwoLorentzianModel import TwoLorentzianModel
552        self.shape_indep_list.append(TwoLorentzianModel )
[7c8d3093]553        self.model_name_list.append(TwoLorentzianModel.__name__)
[fb59ed9]554       
555        from sans.models.TwoPowerLawModel import TwoPowerLawModel
556        self.shape_indep_list.append(TwoPowerLawModel )
[7c8d3093]557        self.model_name_list.append(TwoPowerLawModel.__name__)
[fb59ed9]558       
559        from sans.models.UnifiedPowerRgModel import UnifiedPowerRgModel
560        self.shape_indep_list.append(UnifiedPowerRgModel )
561        self.multi_func_list.append(UnifiedPowerRgModel)
562       
[eddff027]563        from sans.models.LineModel import LineModel
564        self.shape_indep_list.append(LineModel)
[7c8d3093]565        self.model_name_list.append(LineModel.__name__)
[5062bbf]566       
[fb59ed9]567        from sans.models.ReflectivityModel import ReflectivityModel
568        self.multi_func_list.append(ReflectivityModel)
[1cc23fd]569       
570        from sans.models.ReflectivityIIModel import ReflectivityIIModel
571        self.multi_func_list.append(ReflectivityIIModel)
[fb59ed9]572   
[49b7efa]573        #Looking for plugins
[9466f2d6]574        self.stored_plugins = self.findModels()
[b2d9826]575        self.plugins = self.stored_plugins.values()
[fb59ed9]576        self.plugins.append(ReflectivityModel)
[1cc23fd]577        self.plugins.append(ReflectivityIIModel)
[b2d9826]578        self._get_multifunc_models()
579       
[d89f09b]580        return 0
581
[9466f2d6]582    def is_changed(self):
583        """
584        check the last time the plugin dir has changed and return true
585         is the directory was modified else return false
586        """
587        is_modified = False
[96814e1]588        plugin_dir = find_plugins_dir()
589        if os.path.isdir(plugin_dir):
590            temp =  os.path.getmtime(plugin_dir)
[9466f2d6]591            if  self.last_time_dir_modified != temp:
592                is_modified = True
593                self.last_time_dir_modified = temp
[bb9f322]594       
[9466f2d6]595        return is_modified
[d89f09b]596   
[b2d9826]597    def update(self):
598        """
[9466f2d6]599        return a dictionary of model if
600        new models were added else return empty dictionary
[b2d9826]601        """
[9466f2d6]602        new_plugins = self.findModels()
603        if len(new_plugins) > 0:
604            for name, plug in  new_plugins.iteritems():
605                if name not in self.stored_plugins.keys():
606                    self.stored_plugins[name] = plug
607                    self.plugins.append(plug)
608            self.model_combobox.set_list("Customized Models", self.plugins)
609            return self.model_combobox.get_list()
610        else:
611            return {}
[5d1c1f4]612   
[916f5c0]613    def pulgins_reset(self):
614        """
615        return a dictionary of model
616        """
617        self.plugins = []
618        new_plugins = _findModels(dir)
619        for name, plug in  new_plugins.iteritems():
620            for stored_name, stored_plug in self.stored_plugins.iteritems():
621                if name == stored_name:
622                    del self.stored_plugins[name]
623                    break
624            self.stored_plugins[name] = plug
625            self.plugins.append(plug)
626        from sans.models.ReflectivityModel import ReflectivityModel
627        from sans.models.ReflectivityIIModel import ReflectivityIIModel
628        self.plugins.append(ReflectivityModel)
629        self.plugins.append(ReflectivityIIModel)
630        self.model_combobox.reset_list("Customized Models", self.plugins)
631        return self.model_combobox.get_list()
632       
[d89f09b]633    def populate_menu(self, modelmenu, event_owner):
634        """
[5062bbf]635        Populate a menu with our models
636       
637        :param id: first menu event ID to use when binding the menu events
638        :param modelmenu: wx.Menu object to populate
639        :param event_owner: wx object to bind the menu events to
640       
641        :return: the next free event ID following the new menu events
642       
[d89f09b]643        """
[bb18ef1]644        ## Fill model lists
[d89f09b]645        self._getModelList()
[bb18ef1]646        ## store reference to model menu of guiframe
647        self.modelmenu = modelmenu
648        ## guiframe reference
[d89f09b]649        self.event_owner = event_owner
[bb18ef1]650       
651        shape_submenu = wx.Menu()
652        shape_indep_submenu = wx.Menu()
653        structure_factor = wx.Menu()
[b30f001]654        added_models = wx.Menu()
[376916c]655        multip_models = wx.Menu()
[bb18ef1]656        ## create menu with shape
[5062bbf]657        self._fill_simple_menu(menuinfo=["Shapes",shape_submenu," simple shape"],
658                         list1=self.shape_list)
[376916c]659       
[5062bbf]660        self._fill_simple_menu(menuinfo=["Shape-Independent",shape_indep_submenu,
[bb18ef1]661                                    "List of shape-independent models"],
[5062bbf]662                         list1=self.shape_indep_list )
[bb18ef1]663       
[5062bbf]664        self._fill_simple_menu(menuinfo=["Structure Factors",structure_factor,
[bb18ef1]665                                          "List of Structure factors models" ],
[5062bbf]666                                list1=self.struct_list)
[bb18ef1]667       
[5062bbf]668        self._fill_plugin_menu(menuinfo=["Customized Models", added_models,
[376916c]669                                            "List of additional models"],
[5062bbf]670                                 list1=self.plugins)
[376916c]671       
672        self._fill_menu(menuinfo=["P(Q)*S(Q)",multip_models,
673                                  "mulplication of 2 models"],
[5062bbf]674                                   list1=self.multiplication_factor ,
675                                   list2= self.struct_list)
[d89f09b]676        return 0
677   
[5062bbf]678    def _fill_plugin_menu(self, menuinfo, list1):
[bfe4644]679        """
[5062bbf]680        fill the plugin menu with costumized models
[bfe4644]681        """
682        if len(list1)==0:
683            id = wx.NewId() 
684            msg= "No model available check plugins.log for errors to fix problem"
685            menuinfo[1].Append(int(id),"Empty",msg)
686        self._fill_simple_menu( menuinfo,list1)
687       
[5062bbf]688    def _fill_simple_menu(self, menuinfo, list1):
[bb18ef1]689        """
[5062bbf]690        Fill the menu with list item
691       
692        :param modelmenu: the menu to fill
693        :param menuinfo: submenu item for the first column of this modelmenu
694                         with info.Should be a list :
695                         [name(string) , menu(wx.menu), help(string)]
696        :param list1: contains item (form factor )to fill modelmenu second column
697       
[bb18ef1]698        """
699        if len(list1)>0:
700            self.model_combobox.set_list(menuinfo[0],list1)
[e7b1ccf]701           
[bb18ef1]702            for item in list1:
[e7b1ccf]703                try:
704                    id = wx.NewId() 
705                    struct_factor=item()
706                    struct_name = struct_factor.__class__.__name__
707                    if hasattr(struct_factor, "name"):
708                        struct_name = struct_factor.name
709                       
710                    menuinfo[1].Append(int(id),struct_name,struct_name)
711                    if not  item in self.struct_factor_dict.itervalues():
712                        self.struct_factor_dict[str(id)]= item
713                    wx.EVT_MENU(self.event_owner, int(id), self._on_model)
714                except:
715                    msg= "Error Occured: %s"%sys.exc_value
716                    wx.PostEvent(self.event_owner, StatusEvent(status=msg))
[bb18ef1]717               
718        id = wx.NewId()         
719        self.modelmenu.AppendMenu(id, menuinfo[0],menuinfo[1],menuinfo[2])
720       
[5062bbf]721    def _fill_menu(self, menuinfo, list1, list2):
[bb18ef1]722        """
[5062bbf]723        Fill the menu with list item
724       
725        :param menuinfo: submenu item for the first column of this modelmenu
726                         with info.Should be a list :
727                         [name(string) , menu(wx.menu), help(string)]
728        :param list1: contains item (form factor )to fill modelmenu second column
729        :param list2: contains item (Structure factor )to fill modelmenu
730                third column
731               
[bb18ef1]732        """
733        if len(list1)>0:
734            self.model_combobox.set_list(menuinfo[0],list1)
735           
736            for item in list1:   
737                form_factor= item()
738                form_name = form_factor.__class__.__name__
739                if hasattr(form_factor, "name"):
740                    form_name = form_factor.name
741                ### store form factor to return to other users   
742                newmenu= wx.Menu()
743                if len(list2)>0:
744                    for model  in list2:
745                        id = wx.NewId()
746                        struct_factor = model()
747                        name = struct_factor.__class__.__name__
748                        if hasattr(struct_factor, "name"):
749                            name = struct_factor.name
750                        newmenu.Append(id,name, name)
751                        wx.EVT_MENU(self.event_owner, int(id), self._on_model)
752                        ## save form_fact and struct_fact
753                        self.form_factor_dict[int(id)] = [form_factor,struct_factor]
754                       
755                form_id= wx.NewId()   
756                menuinfo[1].AppendMenu(int(form_id), form_name,newmenu,menuinfo[2])
757        id=wx.NewId()
758        self.modelmenu.AppendMenu(id,menuinfo[0],menuinfo[1], menuinfo[2])
759       
[d89f09b]760    def _on_model(self, evt):
761        """
[5062bbf]762        React to a model menu event
763       
764        :param event: wx menu event
765       
[d89f09b]766        """
[bb18ef1]767        if int(evt.GetId()) in self.form_factor_dict.keys():
768            from sans.models.MultiplicationModel import MultiplicationModel
769            model1, model2 = self.form_factor_dict[int(evt.GetId())]
[5062bbf]770            model = MultiplicationModel(model1, model2)   
[bb18ef1]771        else:
772            model= self.struct_factor_dict[str(evt.GetId())]()
[61184df]773       
774        #TODO: investigate why the following two lines were left in the code
775        #      even though the ModelEvent class doesn't exist
776        #evt = ModelEvent(model=model)
777        #wx.PostEvent(self.event_owner, evt)
[d89f09b]778       
[fb59ed9]779    def _get_multifunc_models(self):
780        """
781        Get the multifunctional models
782        """
783        for item in self.plugins:
784            try:
785                # check the multiplicity if any
786                if item.multiplicity_info[0] > 1:
787                    self.multi_func_list.append(item)
788            except:
789                # pass to other items
790                pass
791                   
[d89f09b]792    def get_model_list(self):   
[5062bbf]793        """
794        return dictionary of models for fitpanel use
795       
796        """
[6bbeacd4]797        self.model_combobox.set_list("Shapes", self.shape_list)
798        self.model_combobox.set_list("Shape-Independent", self.shape_indep_list)
799        self.model_combobox.set_list("Structure Factors", self.struct_list)
800        self.model_combobox.set_list("Customized Models", self.plugins)
801        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
[376916c]802        self.model_combobox.set_list("multiplication", self.multiplication_factor)
[e87f9fc]803        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
[b2d9826]804        return self.model_combobox.get_list()
[d89f09b]805   
[7c8d3093]806    def get_model_name_list(self):
807        """
808        return regular model name list
809        """
810        return self.model_name_list
[376916c]811 
[bb18ef1]812       
[bb9f322]813class ModelManager(object):
814    """
815    implement model
816    """
817    __modelmanager = ModelManagerBase()
818   
819    def findModels(self):
820        return self.__modelmanager.findModels()
821   
822    def _getModelList(self):
823        return self.__modelmanager._getModelList()
824   
825    def is_changed(self):
826        return self.__modelmanager.is_changed()
827   
828    def update(self):
829        return self.__modelmanager.update()
830   
[916f5c0]831    def pulgins_reset(self):
832        return self.__modelmanager.pulgins_reset()
833   
[bb9f322]834    def populate_menu(self, modelmenu, event_owner):
835        return self.__modelmanager.populate_menu(modelmenu, event_owner)
836   
837    def _on_model(self, evt):
838        return self.__modelmanager._on_model(evt)
839   
840    def _get_multifunc_models(self):
841        return self.__modelmanager._get_multifunc_models()
842   
843    def get_model_list(self): 
844        return self.__modelmanager.get_model_list()
[bb18ef1]845   
[7c8d3093]846    def get_model_name_list(self):
847        return self.__modelmanager.get_model_name_list()
848   
[d89f09b]849   
[bb18ef1]850 
Note: See TracBrowser for help on using the repository browser.