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

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 992b594 was b30ed8f, checked in by Jae Cho <jhjcho@…>, 13 years ago

move plugin log to plugin_models dir

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